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.

Feat/spotify native (#31)

Salman Qureshie5bcf5637fb3
diff --git a/.env.example b/.env.example
index 760b6285..3e46da38 100644
--- a/.env.example
+++ b/.env.example
@@ -80,3 +80,10 @@ [email protected]
# Default repo for GitHub tools (optional — you can also specify per-call)
GITHUB_DEFAULT_OWNER=
GITHUB_DEFAULT_REPO=
+
+# ── Spotify (optional) ──
+# Register your app at https://developer.spotify.com/dashboard
+# Set redirect URI to http://127.0.0.1:8888/callback in your Spotify app settings
+SPOTIFY_CLIENT_ID=
+SPOTIFY_CLIENT_SECRET=
+SPOTIFY_REDIRECT_URI=http://127.0.0.1:8888/callback
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index da61587e..b46eb318 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -24,6 +24,10 @@ Mercury is a soul-driven, token-efficient AI agent that runs 24/7. It is an **or
| Channels | Communication | `src/channels/` |
| Heartbeat/scheduler | Circadian rhythm | `src/core/scheduler.ts` |
| Lifecycle | Awake/Sleep/Think | `src/core/lifecycle.ts` |
+| Sub-agents | Worker bees | `src/core/sub-agent.ts` + `src/core/supervisor.ts` |
+| File locks | Coordination | `src/core/file-lock.ts` |
+| Task board | Shared state | `src/core/task-board.ts` |
+| Resource manager | Capacity planner | `src/core/resource-manager.ts` |
## Directory Structure
@@ -38,7 +42,12 @@ src/
├── core/ # Channel-agnostic brain
│ ├── agent.ts # Multi-step agentic loop (generateText with tools)
│ ├── lifecycle.ts # State machine
-│ └── scheduler.ts # Cron + heartbeat
+│ ├── scheduler.ts # Cron + heartbeat
+│ ├── sub-agent.ts # Sub-agent worker (isolated agentic loop)
+│ ├── supervisor.ts # Sub-agent supervisor (spawn/halt/orchestrate)
+│ ├── file-lock.ts # File lock manager (reader-writer locks)
+│ ├── task-board.ts # Shared task state persistence
+│ └── resource-manager.ts # System resource detection
├── capabilities/ # Agentic tools & permissions
│ ├── permissions.ts # Permission manager (read/write scope, shell blocklist)
│ ├── registry.ts # Registers all AI SDK tools + skill/scheduler tools
@@ -52,6 +61,10 @@ src/
│ ├── schedule-task.ts
│ ├── list-tasks.ts
│ └── cancel-task.ts
+│ └── subagents/ # Sub-agent tools
+│ ├── delegate-task.ts
+│ ├── list-agents.ts
+│ └── stop-agent.ts
├── memory/ # Persistence layer
│ ├── store.ts # Short/long/episodic memory
│ ├── second-brain-db.ts # SQLite storage engine (FTS5)
@@ -295,4 +308,188 @@ When a scheduled task fires:
- `schedule_task`: Create a cron task with prompt or skill_name
- `list_scheduled_tasks`: Show all scheduled tasks
-- `cancel_scheduled_task`: Remove a scheduled task
\ No newline at end of file
+- `cancel_scheduled_task`: Remove a scheduled task
+
+## Sub-Agents
+
+Mercury supports sub-agents — independent worker processes that run in the same Node.js process as async coroutines. Sub-agents allow Mercury to handle multiple tasks concurrently without blocking the main agent.
+
+### Why Sub-Agents?
+
+- **Non-blocking**: The main agent stays available for new messages while sub-agents work
+- **Resource-aware**: Max concurrent agents auto-detected from CPU cores and available RAM
+- **Coordinated**: File locks prevent conflicting writes between agents
+- **Controllable**: `/agents`, `/halt`, `/stop`, `/reset` commands for full user control
+
+### Architecture
+
+```
+User message → Main Agent → Decide:
+ ├─ Quick response → Handle inline, respond directly
+ └─ Heavy task → delegate_task tool → Spawn Sub-Agent
+ → Main Agent responds: "Working on it. Agent a1 tasked."
+ → Main Agent stays available for next message
+ → Sub-Agent completes → Main Agent notifies user
+```
+
+### Component Overview
+
+| Component | File | Purpose |
+|---|---|---|
+| SubAgent | `src/core/sub-agent.ts` | Worker: isolated agentic loop with abort, file locks, progress |
+| SubAgentSupervisor | `src/core/supervisor.ts` | Orchestrator: spawn/halt/queue, resource management |
+| FileLockManager | `src/core/file-lock.ts` | Read/write locks: multiple readers, exclusive writer, auto-release |
+| TaskBoard | `src/core/task-board.ts` | Shared state: task status, progress, persisted to disk |
+| ResourceManager | `src/core/resource-manager.ts` | System detection: CPU cores, RAM, max concurrent formula |
+
+### Resource Limits
+
+Default max concurrent sub-agents = `clamp(1, cpus - 1, floor(availableRAM_GB / 2))`
+
+Override via `/agents set max <n>` or `SUBAGENTS_MAX_CONCURRENT` env var.
+
+### Lifecycle
+
+```
+unborn → birthing → onboarding → idle ⇄ thinking → responding → idle
+ ↓
+ idle → delegating → idle
+ idle → sleeping → awakening → idle
+```
+
+The `delegating` state covers when the main agent hands off a task to a sub-agent.
+
+### Sub-Agent Tools
+
+| Tool | Description |
+|---|---|
+| `delegate_task` | Delegate a task to a sub-agent worker |
+| `list_agents` | List active sub-agents and their status |
+| `stop_agent` | Stop a sub-agent (or all) |
+
+### User Commands
+
+| Command | Description |
+|---|---|
+| `/agents` | List all sub-agents (status, task, progress) |
+| `/agents stop <id>` | Halt a specific sub-agent |
+| `/agents stop all` | Halt all sub-agents |
+| `/agents pause <id>` | Pause a sub-agent after current step |
+| `/agents resume <id>` | Resume a paused sub-agent |
+| `/agents config` | Show resource allocation |
+| `/agents set max <n>` | Override max concurrent agents |
+| `/halt` | Emergency stop all agents + clear queue |
+| `/stop` | Stop all agents + clear queue + release locks + clear task board |
+| `/reset` | Full reset: stop all + clear context (requires confirmation) |
+
+### Programming Mode
+
+Mercury has a built-in programming mode (activated via `/code plan`) that optimizes it for IDE-grade coding tasks. It operates in two states:
+
+**Plan Mode** (`/code plan`): Mercury explores the codebase, analyzes problems, presents multiple approaches via `ask_user`, and outlines a step-by-step implementation plan — without writing code.
+
+**Execute Mode** (`/code execute`): Mercury implements the approved plan step by step, running builds/tests after changes, committing at checkpoints, and delegating independent subtasks to sub-agents.
+
+| Command | Description |
+|---|---|
+| `/code` | Show current programming mode status |
+| `/code plan` | Switch to plan mode (analyze, present options, no coding) |
+| `/code execute` | Switch to execute mode (implement plan step by step) |
+| `/code off` | Exit programming mode |
+| `/code toggle` | Cycle: off → plan → execute → off |
+
+The `ask_user` tool enables Mercury to present choices (approaches, libraries, strategies) using arrow-key menus in CLI and inline keyboards in Telegram.
+
+### File Lock Semantics
+
+- **Read locks**: Multiple sub-agents can read the same file simultaneously
+- **Write locks**: Exclusive — only one agent can write to a file at a time
+- **Auto-release**: Locks are released when a sub-agent terminates ( completion, failure, or halt)
+- **Deadlock detection**: Supervisor detects circular wait conditions between agents
+
+### Task Board Persistence
+
+All sub-agent task states are persisted to `~/.mercury/memory/task-board.json`, surviving process restarts.
+
+### Config
+
+```yaml
+subagents:
+ enabled: true # Enable/disable sub-agent system
+ maxConcurrent: 0 # 0 = auto-detect from CPU/RAM, >0 = manual override
+ mode: auto # auto = auto-detect, manual = use maxConcurrent value
+```
+
+Environment overrides: `SUBAGENTS_ENABLED`, `SUBAGENTS_MAX_CONCURRENT`, `SUBAGENTS_MODE`
+## Spotify Integration
+
+Mercury can control the user's Spotify playback remotely via the Spotify Web API. Music plays on the user's own devices (phone, web, desktop, TV, speakers) — not locally.
+
+### Setup
+
+1. Create a Spotify app at https://developer.spotify.com/dashboard
+2. Set the redirect URI to `http://127.0.0.1:8888/callback`
+3. Set `SPOTIFY_CLIENT_ID` and `SPOTIFY_CLIENT_SECRET` in `.env`
+4. Run `/spotify auth` in Mercury — this opens a browser for OAuth authorization
+5. Tokens are stored in `~/.mercury/mercury.yaml` and auto-refreshed
+
+### Device Selection
+
+Spotify's device API lists all active devices the user is logged into. Mercury sends play/pause/skip commands to whichever device the user selects — it never plays audio locally.
+
+### DJ Skill
+
+The `spotify` skill (`/skills/spotify/SKILL.md`) activates DJ mode:
+- Searches Spotify based on mood/genre/activity
+- Presents choices via `ask_user` (arrow keys on CLI, inline buttons on Telegram)
+- Manages playback, queues, likes, and playlists
+- Creates curated playlists from user's taste
+
+### Player UI
+
+**CLI**: `/spotify player` opens an interactive arrow-key menu:
+```
+ ▶ Play / Resume
+ ⏸ Pause
+ ⏭ Next Track
+ ⏮ Previous Track
+ 🔀 Toggle Shuffle
+ 🔁 Cycle Repeat
+ 🎵 Now Playing
+ 📱 Devices
+ 🔍 Search & Play
+ 🔊 Set Volume
+ 📋 Add to Queue
+ ❤️ Like Current Track
+ ✕ Exit Player
+```
+
+**Telegram**: Playback controls as inline keyboard buttons.
+
+### Commands
+
+| Command | Description |
+|---|---|
+| `/spotify` | Show connection status |
+| `/spotify auth` | Start OAuth flow (opens browser) |
+| `/spotify player` | Interactive player (CLI only) |
+| `/spotify devices` | List active Spotify devices |
+| `/spotify device <id>` | Set active device |
+| `/spotify now` | Show currently playing track |
+
+### Config
+
+```yaml
+spotify:
+ enabled: true
+ clientId: ...
+ clientSecret: ...
+ redirectUri: http://127.0.0.1:8888/callback
+ accessToken: ...
+ refreshToken: ...
+ expiresAt: ...
+ scopes: [...]
+ deviceId: ...
+```
+
+Environment overrides: `SPOTIFY_CLIENT_ID`, `SPOTIFY_CLIENT_SECRET`, `SPOTIFY_REDIRECT_URI`
diff --git a/skills/code/SKILL.md b/skills/code/SKILL.md
new file mode 100644
index 00000000..2efb6766
--- /dev/null
+++ b/skills/code/SKILL.md
@@ -0,0 +1,97 @@
+---
+name: code
+description: Programming mode — IDE-grade coding agent with plan/execute workflow, approach selection, and sub-agent delegation
+version: 1.0.0
+allowed-tools:
+ - read_file
+ - write_file
+ - create_file
+ - edit_file
+ - delete_file
+ - list_dir
+ - run_command
+ - git_status
+ - git_diff
+ - git_log
+ - git_add
+ - git_commit
+ - git_push
+ - create_pr
+ - review_pr
+ - list_issues
+ - create_issue
+ - github_api
+ - fetch_url
+ - delegate_task
+ - list_agents
+ - stop_agent
+ - ask_user
+ - approve_scope
+ - approve_command
+ - cd
+---
+
+# Code — Programming Mode
+
+You are now in **Programming Mode**. You are an IDE-grade coding agent.
+
+## Core Principles
+
+- **Understand before acting**: Read the codebase first. Use `read_file`, `list_dir`, `git_diff` to understand context before making changes.
+- **Minimal, precise changes**: Edit only what needs to change. Prefer `edit_file` over `write_file` for existing files. Never rewrite entire files when a surgical edit suffices.
+- **Preserve existing style**: Match the codebase's conventions — imports, naming, formatting, error patterns. Look at neighboring files for style cues.
+- **No unnecessary comments**: Do not add comments unless they explain *why*, not *what*. The user will specifically ask for comments if they want them.
+- **Test-aware**: If the project has tests, run them after changes. If no tests exist, mention it.
+
+## Plan/Execute Workflow
+
+You operate in two modes:
+
+### Plan Mode
+When in plan mode or when a task is complex:
+1. **Explore**: Read relevant files, understand the directory structure, check git history for recent changes.
+2. **Analyze**: Identify all files that need to change, dependencies, and potential breaking changes.
+3. **Present options**: If there are multiple approaches (2+), use the `ask_user` tool to present them as choices. Describe tradeoffs clearly.
+4. **Outline the plan**: Present a numbered, step-by-step implementation plan BEFORE writing any code.
+5. **Wait for approval**: Use `ask_user` to confirm the plan or adjust it. Only proceed to execution when the user approves.
+
+### Execute Mode
+When in execute mode or after plan is approved:
+1. **Implement step by step**: Follow the plan. One logical change per step.
+2. **Verify frequently**: Run `run_command` to build, lint, or test after each significant change.
+3. **Commit at logical checkpoints**: Use `git_add` + `git_commit` after completing a coherent unit of work.
+4. **Report progress**: Briefly state what was done and what's next.
+
+## When to Delegate to Sub-Agents
+
+Use `delegate_task` when:
+- A task has **independent subtasks** that can run in parallel (e.g., writing tests while you refactor)
+- A task involves **analyzing many files** (e.g., codebase-wide search/replace)
+- You need to **keep the main conversation free** for the user to ask questions
+
+When delegating, set `workingDirectory` to the project root and `allowedTools` to only what the sub-agent needs.
+
+## Approach Selection
+
+When you identify 2+ viable approaches for a problem:
+1. List each approach with a brief name, description, and key tradeoff
+2. Use `ask_user` with `choices` array to present them
+3. Example approaches to present choices for:
+ - Library choice (e.g., zod vs joi vs valibot)
+ - Architecture pattern (e.g., plugin vs middleware vs decorator)
+ - Implementation strategy (e.g., refactor-first vs feature-first vs big-bang)
+ - Testing approach (e.g., unit vs integration vs e2e)
+
+## File Coordination
+
+When working with sub-agents on the same project:
+- Write operations (`write_file`, `edit_file`, `create_file`, `delete_file`) acquire exclusive file locks
+- If a file is locked by another agent, wait briefly then try again. Report the lock status to the user.
+- Use `/agents` to check what agents are running and which files they hold.
+
+## Error Recovery
+
+- If a build fails, read the error carefully and fix the root cause — don't just suppress the error.
+- If tests fail, read the test output, understand why, and fix the code (not the test, unless the test is wrong).
+- If you hit a permissions error, use `approve_scope` or `approve_command` as needed.
+- If you're stuck, tell the user clearly. Suggest alternatives or ask for guidance using `ask_user`.
\ No newline at end of file
diff --git a/skills/spotify/SKILL.md b/skills/spotify/SKILL.md
new file mode 100644
index 00000000..d2fb1eb1
--- /dev/null
+++ b/skills/spotify/SKILL.md
@@ -0,0 +1,102 @@
+---
+name: spotify
+description: DJ mode — control Spotify playback, search music, manage queues, and curate playlists based on user taste
+version: 1.0.0
+allowed-tools:
+ - spotify_search
+ - spotify_play
+ - spotify_pause
+ - spotify_next
+ - spotify_previous
+ - spotify_now_playing
+ - spotify_devices
+ - spotify_queue
+ - spotify_like
+ - spotify_volume
+ - spotify_shuffle
+ - spotify_repeat
+ - spotify_top_tracks
+ - spotify_playlists
+ - ask_user
+---
+
+# Spotify — DJ Mode
+
+You are Mercury, now in **DJ Mode**. You control the user's Spotify playback.
+
+## Premium Requirement
+
+**Playback control tools require a Spotify Premium account.** This includes: `spotify_play`, `spotify_pause`, `spotify_next`, `spotify_previous`, `spotify_volume`, `spotify_shuffle`, `spotify_repeat`, `spotify_queue`.
+
+**Read-only tools work on free accounts:** `spotify_search`, `spotify_now_playing`, `spotify_devices`, `spotify_top_tracks`, `spotify_playlists`, `spotify_like`.
+
+If a playback tool returns a 403/Premium-required error, tell the user clearly: "Spotify Premium is required for playback control. Read-only features (search, playlists, liked songs) still work on free accounts."
+
+## Core Principles
+
+- **Play on the user's devices**: Always play through Spotify's device system — phone, web, desktop, TV, speaker. Never try to play audio locally.
+- **Device awareness**: Before playing, check available devices with `spotify_devices`. If no device is active, ask the user which one to use.
+- **User taste first**: Use `spotify_top_tracks` and `spotify_playlists` to understand what the user likes before making recommendations.
+- **Interactive DJing**: When the user asks for music by mood/genre/activity, search Spotify, present options via `ask_user`, then play their choice.
+
+## How to DJ
+
+### When user says "play something" / "play music"
+1. Check devices with `spotify_devices`. If none active, tell user to open Spotify on a device.
+2. Check what's currently playing with `spotify_now_playing`.
+3. Ask the user what they're in the mood for using `ask_user` with genre/mood options.
+4. Search based on their preference with `spotify_search`.
+5. Present top results and ask which to play.
+6. Play their choice with `spotify_play`.
+
+### When user asks for a specific song/artist
+1. Search with `spotify_search`.
+2. If exact match found, play it directly.
+3. If multiple matches, present top 3-5 options via `ask_user`.
+
+### When user says "play my stuff" / "play my music"
+1. Use `spotify_top_tracks` to get their favorites.
+2. Use `spotify_playlists` to find their playlists.
+3. Present options: "Your top tracks" or their playlists.
+4. Play their choice.
+
+### When user wants to skip/pause/volume
+- Use direct tools: `spotify_next`, `spotify_previous`, `spotify_pause`, `spotify_volume`.
+- No need to search or confirm for simple controls.
+
+### Curation and playlists
+- When user says "make me a playlist for X", search for tracks matching the vibe.
+- Present 10-20 candidate tracks, let user verify, then create playlist.
+- Use `ask_user` for key decisions: playlist name, public/private, which tracks to include.
+
+## Mood/Activity Mapping
+
+When user describes a mood or activity, map it to search terms:
+
+| User says | Search terms |
+|---|---|
+| Focus / study | "focus music", "lo-fi study", "ambient focus" |
+| Workout / gym | "workout", "high energy gym", "running" |
+| Chill / relax | "chill vibes", "relaxing", "mellow" |
+| Party / dance | "party mix", "dance hits", "upbeat" |
+| Sleep / bedtime | "sleep", "white noise", "calm sleep" |
+| Road trip | "road trip", "driving", "open road" |
+| Cooking | "cooking music", "kitchen vibes" |
+| Sad / moody | "melancholy", "sad songs", "emo" |
+| Happy / upbeat | "feel good", "happy hits", "summer vibes" |
+
+Always use `ask_user` to narrow down if the mood is ambiguous.
+
+## Playback Control Quick Reference
+
+- Play track: `spotify_play` with uri
+- Play album/playlist: `spotify_play` with context uri
+- Pause: `spotify_pause`
+- Skip: `spotify_next`
+- Previous: `spotify_previous`
+- Volume: `spotify_volume` (0-100)
+- Shuffle: `spotify_shuffle` (on/off)
+- Repeat: `spotify_repeat` (off/track/context)
+- Add to queue: `spotify_queue` with uri
+- Like current: `spotify_like` with track id
+- Check playing: `spotify_now_playing`
\ No newline at end of file
diff --git a/src/capabilities/interaction/ask-user.ts b/src/capabilities/interaction/ask-user.ts
new file mode 100644
index 00000000..1bf8e312
--- /dev/null
+++ b/src/capabilities/interaction/ask-user.ts
@@ -0,0 +1,33 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { zodSchema } from 'ai';
+
+type AskUserCallback = (question: string, choices: string[], channelId: string, channelType: string) => Promise<string>;
+
+let askUserHandler: AskUserCallback | null = null;
+
+export function setAskUserHandler(handler: AskUserCallback): void {
+ askUserHandler = handler;
+}
+
+export function createAskUserTool(getContext: () => { channelId: string; channelType: string }) {
+ return tool({
+ description: 'Ask the user a question with multiple choice options. Use this when there are multiple viable approaches and you need the user to decide. Also use for confirmation before proceeding with important actions. The user selects from the choices you provide.',
+ inputSchema: zodSchema(z.object({
+ question: z.string().describe('The question to ask the user'),
+ choices: z.array(z.string()).min(2).describe('List of choices for the user to pick from (minimum 2). Each choice should be a short, clear option label.'),
+ })),
+ execute: async ({ question, choices }) => {
+ if (!askUserHandler) {
+ return 'Unable to ask user: no handler available. Proceed with your best judgment.';
+ }
+ try {
+ const ctx = getContext();
+ const answer = await askUserHandler(question, choices, ctx.channelId, ctx.channelType);
+ return answer;
+ } catch (err: any) {
+ return `User did not respond: ${err.message}. Proceed with your best judgment.`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/interaction/index.ts b/src/capabilities/interaction/index.ts
new file mode 100644
index 00000000..238bf4e1
--- /dev/null
+++ b/src/capabilities/interaction/index.ts
@@ -0,0 +1 @@
+export { createAskUserTool, setAskUserHandler } from './ask-user.js';
\ No newline at end of file
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index 7d98f604..dcbf83c3 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -31,10 +31,30 @@ 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 {
+ createSpotifySearchTool,
+ createSpotifyPlayTool,
+ createSpotifyPauseTool,
+ createSpotifyNextTool,
+ createSpotifyPreviousTool,
+ createSpotifyNowPlayingTool,
+ createSpotifyDevicesTool,
+ createSpotifyQueueTool,
+ createSpotifyLikeTool,
+ createSpotifyVolumeTool,
+ createSpotifyShuffleTool,
+ createSpotifyRepeatTool,
+ createSpotifyTopTracksTool,
+ createSpotifyPlaylistsTool,
+} from './spotify/index.js';
+import { createAskUserTool, setAskUserHandler } from './interaction/index.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';
+import type { SubAgentSupervisor } from '../core/supervisor.js';
+import type { SpotifyClient } from '../spotify/client.js';
+import { createDelegateTaskTool, createListAgentsTool, createStopAgentTool } from './subagents/index.js';
import { logger } from '../utils/logger.js';
export interface ChatCommandContext {
@@ -56,6 +76,8 @@ export class CapabilityRegistry {
private skillLoader?: SkillLoader;
private scheduler?: Scheduler;
private tokenBudget?: TokenBudget;
+ private supervisor?: SubAgentSupervisor;
+ private spotifyClient?: SpotifyClient;
private sendFileHandler?: (filePath: string) => Promise<void>;
private sendMessageHandler?: (content: string) => Promise<void>;
private currentChannelId = 'cli';
@@ -63,11 +85,12 @@ export class CapabilityRegistry {
private chatCommandContext?: ChatCommandContext;
private currentCwd = process.cwd();
- constructor(skillLoader?: SkillLoader, scheduler?: Scheduler, tokenBudget?: TokenBudget) {
+ constructor(skillLoader?: SkillLoader, scheduler?: Scheduler, tokenBudget?: TokenBudget, supervisor?: SubAgentSupervisor) {
this.permissions = new PermissionManager();
this.skillLoader = skillLoader;
this.scheduler = scheduler;
this.tokenBudget = tokenBudget;
+ this.supervisor = supervisor;
}
setChatCommandContext(ctx: ChatCommandContext): void {
@@ -103,6 +126,33 @@ export class CapabilityRegistry {
this.sendMessageHandler = handler;
}
+ setSupervisor(supervisor: SubAgentSupervisor): void {
+ this.supervisor = supervisor;
+ }
+
+ setSpotifyClient(client: SpotifyClient): void {
+ this.spotifyClient = client;
+ }
+
+ registerSpotifyTools(): void {
+ if (!this.spotifyClient) return;
+ this.tools.spotify_search = createSpotifySearchTool(this.spotifyClient);
+ this.tools.spotify_play = createSpotifyPlayTool(this.spotifyClient);
+ this.tools.spotify_pause = createSpotifyPauseTool(this.spotifyClient);
+ this.tools.spotify_next = createSpotifyNextTool(this.spotifyClient);
+ this.tools.spotify_previous = createSpotifyPreviousTool(this.spotifyClient);
+ this.tools.spotify_now_playing = createSpotifyNowPlayingTool(this.spotifyClient);
+ this.tools.spotify_devices = createSpotifyDevicesTool(this.spotifyClient);
+ this.tools.spotify_queue = createSpotifyQueueTool(this.spotifyClient);
+ this.tools.spotify_like = createSpotifyLikeTool(this.spotifyClient);
+ this.tools.spotify_volume = createSpotifyVolumeTool(this.spotifyClient);
+ this.tools.spotify_shuffle = createSpotifyShuffleTool(this.spotifyClient);
+ this.tools.spotify_repeat = createSpotifyRepeatTool(this.spotifyClient);
+ this.tools.spotify_top_tracks = createSpotifyTopTracksTool(this.spotifyClient);
+ this.tools.spotify_playlists = createSpotifyPlaylistsTool(this.spotifyClient);
+ logger.info('Spotify tools registered');
+ }
+
registerAll(): void {
const manifest = this.permissions.getManifest();
@@ -175,6 +225,16 @@ export class CapabilityRegistry {
this.tools.fetch_url = createFetchUrlTool();
logger.info('Web fetch tool registered');
+
+ if (this.supervisor) {
+ this.tools.delegate_task = createDelegateTaskTool(this.supervisor);
+ this.tools.list_agents = createListAgentsTool(this.supervisor);
+ this.tools.stop_agent = createStopAgentTool(this.supervisor);
+ logger.info('Sub-agent tools registered');
+ }
+
+ this.tools.ask_user = createAskUserTool(() => this.getChannelContext());
+ logger.info('Interaction tools registered');
}
getTools(): Record<string, Tool> {
diff --git a/src/capabilities/spotify/index.ts b/src/capabilities/spotify/index.ts
new file mode 100644
index 00000000..15ac2a01
--- /dev/null
+++ b/src/capabilities/spotify/index.ts
@@ -0,0 +1,271 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { zodSchema } from 'ai';
+import type { SpotifyClient } from '../../spotify/client.js';
+
+export function createSpotifySearchTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Search Spotify for tracks, artists, albums, or playlists. Returns matching items with Spotify URIs that can be used with play/queue commands.',
+ inputSchema: zodSchema(z.object({
+ query: z.string().describe('Search query (song name, artist, album, etc.)'),
+ type: z.enum(['track', 'artist', 'album', 'playlist']).optional().default('track').describe('Type of item to search for'),
+ limit: z.number().optional().default(10).describe('Maximum number of results (1-50)'),
+ })),
+ execute: async ({ query, type, limit }) => {
+ try {
+ const data = await spotify.search(query, type, limit);
+ if (!data) return 'No results found.';
+
+ const items = data[`${type}s`]?.items || [];
+ if (items.length === 0) return `No ${type}s found for "${query}".`;
+
+ const lines = [`**Search results for "${query}"** (${type}s):\n`];
+ for (const item of items.slice(0, 10)) {
+ if (type === 'track') {
+ const artists = item.artists?.map((a: any) => a.name).join(', ');
+ lines.push(`• ${artists} — ${item.name} [${item.album?.name || ''}] (uri: ${item.uri})`);
+ } else if (type === 'artist') {
+ lines.push(`• ${item.name} (${item.followers?.total?.toLocaleString() || '?'} followers) (uri: ${item.uri})`);
+ } else if (type === 'album') {
+ const artists = item.artists?.map((a: any) => a.name).join(', ');
+ lines.push(`• ${artists} — ${item.name} (${item.release_date?.slice(0, 4) || '?'}) (uri: ${item.uri})`);
+ } else if (type === 'playlist') {
+ lines.push(`• ${item.name} by ${item.owner?.display_name || '?'} (${item.tracks?.total || '?'} tracks) (uri: ${item.uri})`);
+ }
+ }
+ return lines.join('\n');
+ } catch (err: any) {
+ return `Search failed: ${err.message}`;
+ }
+ },
+ });
+}
+
+export function createSpotifyPlayTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Play a track, album, or playlist on Spotify. Use URIs from search results. Resumes playback if no URI provided.',
+ inputSchema: zodSchema(z.object({
+ uri: z.string().optional().describe('Spotify URI to play (e.g. spotify:track:xxx, spotify:album:xxx, spotify:playlist:xxx)'),
+ deviceId: z.string().optional().describe('Specific device ID to play on (use list_devices to see available)'),
+ })),
+ execute: async ({ uri, deviceId }) => {
+ try {
+ if (uri) {
+ const isContext = uri.startsWith('spotify:album:') || uri.startsWith('spotify:playlist:');
+ if (isContext) {
+ return await spotify.play(undefined, uri, deviceId);
+ }
+ return await spotify.play([uri], undefined, deviceId);
+ }
+ return await spotify.play(undefined, undefined, deviceId);
+ } catch (err: any) {
+ return `Play failed: ${err.message}`;
+ }
+ },
+ });
+}
+
+export function createSpotifyPauseTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Pause the current Spotify playback.',
+ inputSchema: zodSchema(z.object({
+ deviceId: z.string().optional().describe('Device ID to pause on'),
+ })),
+ execute: async ({ deviceId }) => {
+ try {
+ return await spotify.pause(deviceId);
+ } catch (err: any) {
+ return `Pause failed: ${err.message}`;
+ }
+ },
+ });
+}
+
+export function createSpotifyNextTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Skip to the next track on Spotify.',
+ inputSchema: zodSchema(z.object({})),
+ execute: async () => {
+ try { return await spotify.next(); } catch (err: any) { return `Next failed: ${err.message}`; }
+ },
+ });
+}
+
+export function createSpotifyPreviousTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Skip to the previous track on Spotify.',
+ inputSchema: zodSchema(z.object({})),
+ execute: async () => {
+ try { return await spotify.previous(); } catch (err: any) { return `Previous failed: ${err.message}`; }
+ },
+ });
+}
+
+export function createSpotifyNowPlayingTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Get information about what is currently playing on Spotify, including track name, artist, progress, and duration.',
+ inputSchema: zodSchema(z.object({})),
+ execute: async () => {
+ try {
+ const data = await spotify.getCurrentlyPlaying();
+ if (!data || !data.item) return 'Nothing is currently playing.';
+
+ const track = data.item;
+ const artists = track.artists?.map((a: any) => a.name).join(', ') || 'Unknown';
+ const progress = data.progress_ms ? Math.floor(data.progress_ms / 1000) : 0;
+ const duration = track.duration_ms ? Math.floor(track.duration_ms / 1000) : 0;
+ const pct = duration ? Math.floor((progress / duration) * 100) : 0;
+ const shuffle = data.shuffle_state ? 'Shuffle on' : 'Shuffle off';
+ const repeat = data.repeat_state || 'off';
+ const isPlaying = data.is_playing ? '▶ Playing' : '⏸ Paused';
+
+ const bar = formatBar(progress, duration);
+ const lines = [
+ `${isPlaying} — **${track.name}** by ${artists}`,
+ `${bar} ${formatTime(progress)}/${formatTime(duration)} (${pct}%)`,
+ `Album: ${track.album?.name || 'Unknown'} | ${shuffle} | Repeat: ${repeat}`,
+ ];
+ return lines.join('\n');
+ } catch (err: any) {
+ return `Now playing check failed: ${err.message}`;
+ }
+ },
+ });
+}
+
+export function createSpotifyDevicesTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'List available Spotify devices the user can play music on.',
+ inputSchema: zodSchema(z.object({})),
+ execute: async () => {
+ try {
+ const data = await spotify.getDevices();
+ if (!data?.devices || data.devices.length === 0) return 'No active Spotify devices found. Open Spotify on a device first.';
+
+ const lines = ['**Available Spotify devices:**\n'];
+ for (const device of data.devices) {
+ const icon = device.is_active ? '▶' : '○';
+ const type = device.type || 'Unknown';
+ lines.push(`${icon} **${device.name}** (${type}) — id: \`${device.id}\`${device.is_active ? ' [active]' : ''}`);
+ }
+ lines.push('\nUse `/spotify device <id>` to switch the active device.');
+ return lines.join('\n');
+ } catch (err: any) {
+ return `Device listing failed: ${err.message}`;
+ }
+ },
+ });
+}
+
+export function createSpotifyQueueTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Add a track to the Spotify playback queue by URI. Use URIs from search results.',
+ inputSchema: zodSchema(z.object({
+ uri: z.string().describe('Spotify track URI to add to queue (e.g. spotify:track:xxx)'),
+ })),
+ execute: async ({ uri }) => {
+ try { return await spotify.addToQueue(uri); } catch (err: any) { return `Queue add failed: ${err.message}`; }
+ },
+ });
+}
+
+export function createSpotifyLikeTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Like (save) a Spotify track to the user\'s library.',
+ inputSchema: zodSchema(z.object({
+ trackId: z.string().describe('Spotify track ID (not the full URI, just the ID part)'),
+ })),
+ execute: async ({ trackId }) => {
+ try { return await spotify.likeTrack(trackId); } catch (err: any) { return `Like failed: ${err.message}`; }
+ },
+ });
+}
+
+export function createSpotifyVolumeTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Set Spotify playback volume percentage.',
+ inputSchema: zodSchema(z.object({
+ percent: z.number().min(0).max(100).describe('Volume percentage (0-100)'),
+ })),
+ execute: async ({ percent }) => {
+ try { return await spotify.setVolume(percent); } catch (err: any) { return `Volume change failed: ${err.message}`; }
+ },
+ });
+}
+
+export function createSpotifyShuffleTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Toggle Spotify shuffle on or off.',
+ inputSchema: zodSchema(z.object({
+ state: z.boolean().describe('true to enable shuffle, false to disable'),
+ })),
+ execute: async ({ state }) => {
+ try { return await spotify.setShuffle(state); } catch (err: any) { return `Shuffle toggle failed: ${err.message}`; }
+ },
+ });
+}
+
+export function createSpotifyRepeatTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Set Spotify repeat mode.',
+ inputSchema: zodSchema(z.object({
+ state: z.enum(['off', 'track', 'context']).describe('off = no repeat, track = repeat one, context = repeat all'),
+ })),
+ execute: async ({ state }) => {
+ try { return await spotify.setRepeat(state); } catch (err: any) { return `Repeat change failed: ${err.message}`; }
+ },
+ });
+}
+
+export function createSpotifyTopTracksTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Get the user\'s top tracks on Spotify.',
+ inputSchema: zodSchema(z.object({
+ timeRange: z.enum(['short_term', 'medium_term', 'long_term']).optional().default('medium_term').describe('Time range: short_term (~4 weeks), medium_term (~6 months), long_term (years)'),
+ limit: z.number().optional().default(20).describe('Number of tracks (1-50)'),
+ })),
+ execute: async ({ timeRange, limit }) => {
+ try {
+ const data = await spotify.getTopTracks(timeRange, limit);
+ if (!data?.items?.length) return 'No top tracks found.';
+ const lines = ['**Your Top Tracks:**\n'];
+ for (let i = 0; i < data.items.length; i++) {
+ const t = data.items[i];
+ const artists = t.artists?.map((a: any) => a.name).join(', ');
+ lines.push(`${i + 1}. ${artists} — ${t.name} (uri: ${t.uri})`);
+ }
+ return lines.join('\n');
+ } catch (err: any) { return `Top tracks failed: ${err.message}`; }
+ },
+ });
+}
+
+export function createSpotifyPlaylistsTool(spotify: SpotifyClient) {
+ return tool({
+ description: 'Get the user\'s Spotify playlists.',
+ inputSchema: zodSchema(z.object({})),
+ execute: async () => {
+ try {
+ const data = await spotify.getPlaylists();
+ if (!data?.items?.length) return 'No playlists found.';
+ const lines = ['**Your Playlists:**\n'];
+ for (const p of data.items) {
+ lines.push(`• **${p.name}** (${p.tracks?.total || '?'} tracks) — uri: ${p.uri}`);
+ }
+ return lines.join('\n');
+ } catch (err: any) { return `Playlists failed: ${err.message}`; }
+ },
+ });
+}
+
+function formatBar(progress: number, duration: number): string {
+ if (!duration) return '';
+ const pct = Math.floor((progress / duration) * 20);
+ return `[${'█'.repeat(pct)}${'░'.repeat(20 - pct)}]`;
+}
+
+function formatTime(seconds: number): string {
+ const m = Math.floor(seconds / 60);
+ const s = seconds % 60;
+ return `${m}:${s.toString().padStart(2, '0')}`;
+}
\ No newline at end of file
diff --git a/src/capabilities/subagents/delegate-task.ts b/src/capabilities/subagents/delegate-task.ts
new file mode 100644
index 00000000..78739a95
--- /dev/null
+++ b/src/capabilities/subagents/delegate-task.ts
@@ -0,0 +1,43 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { zodSchema } from 'ai';
+import type { SubAgentSupervisor } from '../../core/supervisor.js';
+import { logger } from '../../utils/logger.js';
+
+export function createDelegateTaskTool(supervisor: SubAgentSupervisor) {
+ return tool({
+ description: 'Delegate a task to a sub-agent worker. Use this for complex, multi-step tasks that would take a long time and should not block the main conversation. The sub-agent will work independently and report back when done. You can continue handling other messages while sub-agents work.',
+ inputSchema: zodSchema(z.object({
+ task: z.string().describe('Clear description of the task for the sub-agent to complete'),
+ workingDirectory: z.string().optional().describe('Working directory for the sub-agent (defaults to current directory)'),
+ priority: z.enum(['low', 'normal', 'high']).optional().describe('Task priority (default: normal)'),
+ allowedTools: z.array(z.string()).optional().describe('Optional list of tool names this sub-agent is allowed to use. If not specified, all tools are available.'),
+ })),
+ execute: async ({ task, workingDirectory, priority, allowedTools }) => {
+ try {
+ logger.info({ task: task.slice(0, 50) }, 'Delegating task to sub-agent');
+
+ const agentId = await supervisor.spawn({
+ task,
+ workingDirectory,
+ priority: priority || 'normal',
+ allowedTools,
+ sourceChannelId: undefined,
+ sourceChannelType: undefined,
+ });
+
+ const resourceInfo = supervisor.getResourceUsage();
+
+ let response = `Task delegated to sub-agent **${agentId}**.\n`;
+ response += `Task: "${task.slice(0, 80)}${task.length > 80 ? '...' : ''}"\n`;
+ response += `Active agents: ${resourceInfo.activeAgents}/${resourceInfo.maxConcurrentAgents}\n`;
+ response += `\nUse /agents to check status, /agents stop ${agentId} to halt.`;
+
+ return response;
+ } catch (err: any) {
+ logger.error({ err }, 'Failed to delegate task');
+ return `Failed to delegate task: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/subagents/index.ts b/src/capabilities/subagents/index.ts
new file mode 100644
index 00000000..26eddeb7
--- /dev/null
+++ b/src/capabilities/subagents/index.ts
@@ -0,0 +1,3 @@
+export { createDelegateTaskTool } from './delegate-task.js';
+export { createListAgentsTool } from './list-agents.js';
+export { createStopAgentTool } from './stop-agent.js';
\ No newline at end of file
diff --git a/src/capabilities/subagents/list-agents.ts b/src/capabilities/subagents/list-agents.ts
new file mode 100644
index 00000000..36524c9d
--- /dev/null
+++ b/src/capabilities/subagents/list-agents.ts
@@ -0,0 +1,48 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { zodSchema } from 'ai';
+import type { SubAgentSupervisor } from '../../core/supervisor.js';
+
+export function createListAgentsTool(supervisor: SubAgentSupervisor) {
+ return tool({
+ description: 'List all active and queued sub-agents with their status, task, and progress. Use this to check what sub-agents are currently working on.',
+ inputSchema: zodSchema(z.object({})),
+ execute: async () => {
+ const agents = supervisor.getActiveAgents();
+ const resourceInfo = supervisor.getResourceUsage();
+
+ if (agents.length === 0) {
+ return `No active sub-agents.\nMax concurrent: ${resourceInfo.maxConcurrentAgents} (auto) | CPU: ${resourceInfo.cpuCores} cores`;
+ }
+
+ const statusIcons: Record<string, string> = {
+ pending: '\u{1f535}',
+ running: '\u{1f7e2}',
+ paused: '\u{1f7e1}',
+ completed: '\u2705',
+ failed: '\u274c',
+ halted: '\u26d4',
+ };
+
+ const lines = [
+ `**Sub-Agents** (${agents.length})`,
+ '',
+ ];
+
+ for (const agent of agents) {
+ const icon = statusIcons[agent.status] || '\u2753';
+ const taskPreview = agent.task.length > 40 ? agent.task.slice(0, 40) + '...' : agent.task;
+ lines.push(`${icon} **${agent.id}** ${taskPreview}`);
+ if (agent.progress) {
+ lines.push(` ${agent.progress}`);
+ }
+ }
+
+ lines.push('');
+ lines.push(`Max concurrent: ${resourceInfo.maxConcurrentAgents} (auto) | CPU: ${resourceInfo.cpuCores} cores`);
+ lines.push(`Active: ${resourceInfo.activeAgents} | Queued: ${resourceInfo.queuedAgents}`);
+
+ return lines.join('\n');
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/subagents/stop-agent.ts b/src/capabilities/subagents/stop-agent.ts
new file mode 100644
index 00000000..e7258388
--- /dev/null
+++ b/src/capabilities/subagents/stop-agent.ts
@@ -0,0 +1,34 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { zodSchema } from 'ai';
+import type { SubAgentSupervisor } from '../../core/supervisor.js';
+import { logger } from '../../utils/logger.js';
+
+export function createStopAgentTool(supervisor: SubAgentSupervisor) {
+ return tool({
+ description: 'Stop a running or queued sub-agent, or stop all sub-agents. The agent will finish its current tool step before halting.',
+ inputSchema: zodSchema(z.object({
+ agentId: z.string().describe('ID of the sub-agent to stop (e.g. "a1"), or "all" to stop every agent'),
+ })),
+ execute: async ({ agentId }) => {
+ try {
+ if (agentId.toLowerCase() === 'all') {
+ await supervisor.haltAll();
+ logger.info('All sub-agents halted via stop_agent tool');
+ return 'All sub-agents have been halted. Any agents currently executing a tool step will finish that step before stopping.';
+ }
+
+ const halted = await supervisor.halt(agentId);
+ if (!halted) {
+ return `No active agent found with ID "${agentId}". Use the list_agents tool to see active agents.`;
+ }
+
+ logger.info({ agentId }, 'Sub-agent halted via stop_agent tool');
+ return `Agent ${agentId} halt signal sent. It will finish its current tool step and then stop. File locks will be released automatically.`;
+ } catch (err: any) {
+ logger.error({ err }, 'Failed to stop agent');
+ return `Failed to stop agent: ${err.message}`;
+ }
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 70a93608..b9286aad 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -12,11 +12,15 @@ import type { ScheduledTaskManifest } from './scheduler.js';
import { DeepSeekProvider } from '../providers/deepseek.js';
import { Lifecycle } from './lifecycle.js';
import { Scheduler } from './scheduler.js';
+import { ProgrammingMode } from './programming-mode.js';
import { logger } from '../utils/logger.js';
import { CLIChannel } from '../channels/cli.js';
import { TelegramChannel } from '../channels/telegram.js';
import { formatToolStep } from '../utils/tool-label.js';
import type { ArrowSelectOption } from '../utils/arrow-select.js';
+import { setAskUserHandler } from '../capabilities/interaction/ask-user.js';
+import type { SpotifyClient } from '../spotify/client.js';
+import { PLAYER_CONTROLS, handlePlayerAction, formatNowPlaying } from '../spotify/ui.js';
import {
approveTelegramPendingRequest,
approveTelegramPendingRequestByPairingCode,
@@ -249,6 +253,9 @@ export class Agent {
private messageQueue: ChannelMessage[] = [];
private processing = false;
private telegramStreaming: boolean;
+ private supervisor?: import('../core/supervisor.js').SubAgentSupervisor;
+ readonly programmingMode: ProgrammingMode;
+ private spotifyClient?: SpotifyClient;
constructor(
private config: MercuryConfig,
@@ -267,6 +274,7 @@ export class Agent {
this.scheduler = scheduler;
this.capabilities = capabilities;
this.telegramStreaming = config.channels.telegram.streaming ?? true;
+ this.programmingMode = new ProgrammingMode();
this.scheduler.setOnScheduledTask(async (manifest) => this.handleScheduledTask(manifest));
@@ -275,6 +283,20 @@ export class Agent {
this.scheduler.onHeartbeat(async () => {
await this.heartbeat();
});
+
+ setAskUserHandler(async (question, choices, channelId, channelType) => {
+ return this.presentChoice(question, choices, channelId, channelType);
+ });
+ }
+
+ setSupervisor(supervisor: import('../core/supervisor.js').SubAgentSupervisor): void {
+ this.supervisor = supervisor;
+ supervisor.setNotifyCallback(async (channelType, channelId, message) => {
+ const channel = this.channels.get(channelType as any);
+ if (channel) {
+ await channel.send(message, channelId).catch(() => {});
+ }
+ });
}
private enqueueMessage(msg: ChannelMessage): void {
@@ -928,6 +950,10 @@ export class Agent {
if (skillContext) {
prompt += '\n\n' + skillContext;
}
+ const programmingSuffix = this.programmingMode.getSystemPromptSuffix();
+ if (programmingSuffix) {
+ prompt += programmingSuffix;
+ }
const budgetStatus = this.tokenBudget.getStatusText();
prompt += '\n\n' + budgetStatus;
if (this.tokenBudget.getUsagePercentage() > 70) {
@@ -1167,6 +1193,81 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub user
logger.info('Mercury has shut down');
}
+ setSpotifyClient(client: SpotifyClient): void {
+ this.spotifyClient = client;
+ }
+
+ async presentChoice(question: string, choices: string[], channelId: string, channelType: string): Promise<string> {
+ const channel = this.channels.get(channelType as any);
+
+ if (channelType === 'cli' && channel instanceof CLIChannel) {
+ const options: ArrowSelectOption[] = choices.map((label, i) => ({
+ value: String(i),
+ label,
+ }));
+
+ try {
+ const selected = await channel.withMenu(async (select) => {
+ return select(question, options);
+ });
+ if (selected === undefined) return choices[0];
+ const index = parseInt(selected, 10);
+ return isNaN(index) ? choices[0] : choices[index];
+ } catch {
+ return choices[0];
+ }
+ }
+
+ if (channelType === 'telegram' && channel instanceof TelegramChannel) {
+ const { InlineKeyboard } = await import('grammy');
+ const kb = new InlineKeyboard();
+ for (let i = 0; i < choices.length; i++) {
+ const callbackData = `choice_${Date.now()}_${i}`;
+ kb.text(choices[i].slice(0, 60), callbackData);
+ if (i < choices.length - 1 && (i + 1) % 2 === 0) {
+ kb.row();
+ }
+ }
+
+ return new Promise<string>((resolve) => {
+ const timeout = setTimeout(() => {
+ (channel as any).pendingApprovals?.delete(`choice_timeout_${question}`);
+ resolve(choices[0]);
+ }, 120000);
+
+ channel.send(question, channelId).catch(() => {});
+
+ const tgBot = (channel as any).bot;
+ if (tgBot) {
+ const chatId = channelId.startsWith('telegram:')
+ ? Number(channelId.split(':')[1])
+ : Number(channelId);
+
+ tgBot.api.sendMessage(chatId, question, { reply_markup: kb }).catch(() => {});
+
+ const handler = async (ctx: any) => {
+ const data = ctx.callbackQuery?.data;
+ if (!data || !data.startsWith('choice_')) return;
+ const parts = data.split('_');
+ if (parts.length < 3) return;
+ const index = parseInt(parts[2], 10);
+ if (isNaN(index)) return;
+ clearTimeout(timeout);
+ try { await ctx.answerCallbackQuery(); } catch {}
+ resolve(choices[index]);
+ };
+
+ if ((channel as any).pendingCallbacks) {
+ (channel as any).pendingCallbacks.push(handler);
+ }
+ }
+ });
+ }
+
+ await channel?.send(`${question}\n${choices.map((c, i) => ` ${i + 1}. ${c}`).join('\n')}`, channelId).catch(() => {});
+ return choices[0];
+ }
+
private async handleBudgetOverrideCLI(channel: import('../channels/base.js').Channel, msg: ChannelMessage): Promise<void> {
const status = this.tokenBudget.getStatusText();
await channel.send(
@@ -1501,6 +1602,216 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub user
return true;
}
+ if (cmd.startsWith('/code')) {
+ const rawArgs = trimmed.slice('/code'.length).trim().toLowerCase();
+
+ if (!rawArgs || rawArgs === 'status') {
+ await channel.send(this.programmingMode.getStatusText(), channelId);
+ return true;
+ }
+
+ if (rawArgs === 'plan') {
+ this.programmingMode.setPlan();
+ await channel.send('Programming mode: **Plan**\nI will explore, analyze, and present a plan before writing any code. Use `/code execute` to switch to execution.', channelId);
+ return true;
+ }
+
+ if (rawArgs === 'execute' || rawArgs === 'exec') {
+ this.programmingMode.setExecute();
+ await channel.send('Programming mode: **Execute**\nI will implement the plan step by step, verifying with builds/tests. Use `/code off` to exit.', channelId);
+ return true;
+ }
+
+ if (rawArgs === 'off' || rawArgs === 'exit') {
+ this.programmingMode.setOff();
+ await channel.send('Programming mode: **Off**\nBack to normal conversation mode.', channelId);
+ return true;
+ }
+
+ if (rawArgs === 'toggle') {
+ const newState = this.programmingMode.toggle();
+ const labels: Record<string, string> = { off: 'Off', plan: 'Plan', execute: 'Execute' };
+ await channel.send(`Programming mode: **${labels[newState]}**`, channelId);
+ return true;
+ }
+
+ await channel.send('Unknown /code command. Available: /code, /code plan, /code execute, /code off, /code toggle', channelId);
+ return true;
+ }
+
+ if (cmd.startsWith('/spotify')) {
+ if (!this.spotifyClient) {
+ await channel.send('Spotify is not connected. Set SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET in your config, then run /spotify auth.', channelId);
+ return true;
+ }
+ const rawArgs = trimmed.slice('/spotify'.length).trim().toLowerCase();
+
+ if (!rawArgs || rawArgs === 'status') {
+ const auth = this.spotifyClient.isAuthenticated() ? 'Connected' : 'Not connected';
+ const device = this.spotifyClient.getDeviceId() || 'none';
+ const premium = this.spotifyClient.getPremiumStatus();
+ const premiumLabel = premium === null ? '' : premium ? ' | Premium' : ' | Free (no playback control)';
+ await channel.send(`Spotify: **${auth}**${premiumLabel}\nDevice: ${device !== 'none' ? device : 'none selected'}`, channelId);
+ return true;
+ }
+
+ if (rawArgs === 'auth') {
+ if (channelType === 'cli' && channel instanceof CLIChannel) {
+ try {
+ const choice = await channel.withMenu(async (select) => {
+ return select('Spotify Authorization', [
+ { value: 'browser', label: 'Open browser (recommended)' },
+ { value: 'manual', label: 'Paste authorization code manually' },
+ { value: 'cancel', label: 'Cancel' },
+ ]);
+ });
+ if (!choice || choice === 'cancel') {
+ await channel.send('Spotify auth cancelled.', channelId);
+ return true;
+ }
+ if (choice === 'manual') {
+ const authUrl = this.spotifyClient.getAuthUrl();
+ await channel.send('1. Open this URL in your browser:\n' + authUrl + '\n\n2. After authorizing, you will be redirected to localhost — it may show an error page, that is OK.\n3. Copy the `code` parameter from the URL in your browser address bar.\n4. Paste it below:', channelId);
+ const code = await channel.prompt('Authorization code: ');
+ if (!code || !code.trim()) {
+ await channel.send('No code provided. Auth cancelled.', channelId);
+ return true;
+ }
+ await this.spotifyClient.authenticateWithCode(code.trim());
+ await channel.send('Spotify connected successfully! Try: play some music', channelId);
+ } else {
+ await channel.send('Opening browser for Spotify authorization...', channelId);
+ await this.spotifyClient.authenticate();
+ await channel.send('Spotify connected successfully! Try: play some music', channelId);
+ }
+ } catch (err: any) {
+ await channel.send(`Spotify auth failed: ${err.message}`, channelId);
+ }
+ } else {
+ const authUrl = this.spotifyClient.getAuthUrl();
+ await channel.send(
+ '**Connect Spotify**\n\n1. Open this URL on any device with a browser:\n' + authUrl + '\n\n2. After authorizing, you will be redirected to localhost — that page may show an error, that is OK.\n3. Copy the `code` from the URL, then type:\n`/spotify code <paste-code-here>`',
+ channelId
+ );
+ }
+ return true;
+ }
+
+ if (rawArgs.startsWith('code ')) {
+ const code = rawArgs.slice('code '.length).trim();
+ if (!code) {
+ await channel.send('Usage: /spotify code <authorization-code>', channelId);
+ return true;
+ }
+ try {
+ await this.spotifyClient.authenticateWithCode(code);
+ await channel.send('Spotify connected successfully! Try: play some music', channelId);
+ } catch (err: any) {
+ await channel.send(`Spotify auth failed: ${err.message}`, channelId);
+ }
+ return true;
+ }
+
+ if (rawArgs === 'devices') {
+ try {
+ const data = await this.spotifyClient.getDevices();
+ if (!data?.devices?.length) { await channel.send('No active devices. Open Spotify on a device first.', channelId); return true; }
+ const lines = ['**Spotify Devices:**\n'];
+ for (const d of data.devices) {
+ lines.push(`${d.is_active ? '▶' : '○'} **${d.name}** (${d.type}) — \`${d.id}\`${d.is_active ? ' [active]' : ''}`);
+ }
+ await channel.send(lines.join('\n'), channelId);
+ } catch (err: any) { await channel.send(`Failed: ${err.message}`, channelId); }
+ return true;
+ }
+
+ if (rawArgs.startsWith('device ')) {
+ const id = rawArgs.slice('device '.length).trim();
+ this.spotifyClient.setDevice(id);
+ await channel.send(`Active device set to: ${id}`, channelId);
+ return true;
+ }
+
+ if (rawArgs === 'player' && channelType === 'cli' && channel instanceof CLIChannel) {
+ await channel.withMenu(async (select) => {
+ while (true) {
+ try {
+ const np = await this.spotifyClient!.getCurrentlyPlaying();
+ if (np) {
+ await channel.send(formatNowPlaying(np), channelId);
+ }
+ } catch {}
+ const action = await select('Spotify Player', PLAYER_CONTROLS);
+ if (action === 'exit' || !action) return;
+ if (action === 'search') {
+ const query = await channel.prompt('Search: ');
+ if (!query) continue;
+ try {
+ const results = await this.spotifyClient!.search(query, 'track', 5);
+ const tracks = results?.tracks?.items || [];
+ if (tracks.length === 0) { await channel.send('No results found.', channelId); continue; }
+ const trackOptions = tracks.map((t: any, i: number) => ({
+ value: t.uri,
+ label: `${t.artists?.map((a: any) => a.name).join(', ')} — ${t.name}`,
+ }));
+ const picked = await select('Play which track?', [...trackOptions, { value: 'back', label: 'Back' }]);
+ if (picked && picked !== 'back') {
+ await this.spotifyClient!.play([picked]);
+ }
+ } catch (err: any) { await channel.send(`Search failed: ${err.message}`, channelId); }
+ continue;
+ }
+ if (action === 'volume') {
+ const vol = await channel.prompt('Volume (0-100): ');
+ const n = parseInt(vol, 10);
+ if (!isNaN(n) && n >= 0 && n <= 100) {
+ await this.spotifyClient!.setVolume(n);
+ await channel.send(`Volume: ${n}%`, channelId);
+ }
+ continue;
+ }
+ if (action === 'queue') {
+ const query = await channel.prompt('Search track to queue: ');
+ if (!query) continue;
+ try {
+ const results = await this.spotifyClient!.search(query, 'track', 5);
+ const tracks = results?.tracks?.items || [];
+ if (tracks.length === 0) { await channel.send('No results.', channelId); continue; }
+ const trackOptions = tracks.map((t: any) => ({
+ value: t.uri,
+ label: `${t.artists?.map((a: any) => a.name).join(', ')} — ${t.name}`,
+ }));
+ const picked = await select('Queue which track?', [...trackOptions, { value: 'back', label: 'Back' }]);
+ if (picked && picked !== 'back') {
+ await this.spotifyClient!.addToQueue(picked);
+ await channel.send('Added to queue.', channelId);
+ }
+ } catch (err: any) { await channel.send(`Failed: ${err.message}`, channelId); }
+ continue;
+ }
+ try {
+ const result = await handlePlayerAction(action, this.spotifyClient!);
+ await channel.send(result, channelId);
+ } catch (err: any) {
+ await channel.send(`Failed: ${err.message}`, channelId);
+ }
+ }
+ });
+ return true;
+ }
+
+ if (rawArgs === 'now' || rawArgs === 'playing' || rawArgs === 'np') {
+ try {
+ const text = await this.spotifyClient.getNowPlayingText();
+ await channel.send(text, channelId);
+ } catch (err: any) { await channel.send(`Failed: ${err.message}`, channelId); }
+ return true;
+ }
+
+ await channel.send('Unknown /spotify command. Available: /spotify, /spotify auth, /spotify code <code>, /spotify player, /spotify devices, /spotify device <id>, /spotify now', channelId);
+ return true;
+ }
+
if (cmd === '/stream on') {
this.telegramStreaming = true;
await channel.send('Telegram streaming enabled. Responses will appear progressively.', channelId);
@@ -1529,6 +1840,154 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub user
return true;
}
+ if (cmd.startsWith('/agents')) {
+ if (!this.supervisor) {
+ await channel.send('Sub-agents are not available.', channelId);
+ return true;
+ }
+ const rawArgs = trimmed.slice('/agents'.length).trim();
+
+ if (!rawArgs) {
+ const agents = this.supervisor.getActiveAgents();
+ const resourceInfo = this.supervisor.getResourceUsage();
+ if (agents.length === 0) {
+ await channel.send(`No active sub-agents.\nMax concurrent: ${resourceInfo.maxConcurrentAgents} (auto) | CPU: ${resourceInfo.cpuCores} cores`, channelId);
+ return true;
+ }
+ const statusIcons: Record<string, string> = { pending: '🔵', running: '🟢', paused: '🟡', completed: '✅', failed: '❌', halted: '⛔' };
+ const lines = [`**Sub-Agents** (${agents.length})`, ''];
+ for (const agent of agents) {
+ const icon = statusIcons[agent.status] || '❓';
+ const taskPreview = agent.task.length > 40 ? agent.task.slice(0, 40) + '...' : agent.task;
+ lines.push(`${icon} **${agent.id}** ${taskPreview}`);
+ if (agent.progress) lines.push(` ${agent.progress}`);
+ }
+ lines.push('');
+ lines.push(`Max concurrent: ${resourceInfo.maxConcurrentAgents} (auto) | CPU: ${resourceInfo.cpuCores} cores`);
+ lines.push(`Active: ${resourceInfo.activeAgents} | Queued: ${resourceInfo.queuedAgents}`);
+ await channel.send(lines.join('\n'), channelId);
+ return true;
+ }
+
+ const parts = rawArgs.split(/\s+/);
+ const action = parts[0]?.toLowerCase();
+
+ if (action === 'stop') {
+ const target = parts[1]?.toLowerCase();
+ if (!target) {
+ await channel.send('Usage: /agents stop <id> or /agents stop all', channelId);
+ return true;
+ }
+ if (target === 'all') {
+ await this.supervisor.haltAll();
+ await channel.send('All sub-agents halted. They will finish their current tool step before stopping.', channelId);
+ } else {
+ const halted = await this.supervisor.halt(target);
+ if (!halted) {
+ await channel.send(`No active agent found with ID "${target}".`, channelId);
+ } else {
+ await channel.send(`Agent ${target} halt signal sent. It will finish its current step then stop.`, channelId);
+ }
+ }
+ return true;
+ }
+
+ if (action === 'pause') {
+ const target = parts[1]?.toLowerCase();
+ if (!target) {
+ await channel.send('Usage: /agents pause <id>', channelId);
+ return true;
+ }
+ const paused = await this.supervisor.pause(target);
+ await channel.send(paused ? `Agent ${target} paused. Use /agents resume ${target} to continue.` : `No running agent found with ID "${target}".`, channelId);
+ return true;
+ }
+
+ if (action === 'resume') {
+ const target = parts[1]?.toLowerCase();
+ if (!target) {
+ await channel.send('Usage: /agents resume <id>', channelId);
+ return true;
+ }
+ const resumed = await this.supervisor.resume(target);
+ await channel.send(resumed ? `Agent ${target} resumed.` : `No paused agent found with ID "${target}".`, channelId);
+ return true;
+ }
+
+ if (action === 'config') {
+ const info = this.supervisor.getResourceUsage();
+ const lines = [
+ '**Sub-Agent Configuration**',
+ `CPU cores: ${info.cpuCores}`,
+ `System RAM: ${info.systemMemoryMB}MB`,
+ `Available RAM: ${info.availableMemoryMB}MB`,
+ `Max concurrent: ${info.maxConcurrentAgents}`,
+ `Active agents: ${info.activeAgents}`,
+ `Queued agents: ${info.queuedAgents}`,
+ `Token budget remaining: ${info.tokenBudgetRemaining.toLocaleString()}`,
+ ];
+ await channel.send(lines.join('\n'), channelId);
+ return true;
+ }
+
+ if (action === 'set' && parts[1]?.toLowerCase() === 'max') {
+ const n = parseInt(parts[2], 10);
+ if (isNaN(n) || n < 1) {
+ await channel.send('Usage: /agents set max <number>', channelId);
+ return true;
+ }
+ this.supervisor.setMaxConcurrent(n);
+ await channel.send(`Max concurrent sub-agents set to ${n}.`, channelId);
+ return true;
+ }
+
+ await channel.send(`Unknown /agents command "${action}". Available: /agents, /agents stop <id|all>, /agents pause <id>, /agents resume <id>, /agents config, /agents set max <n>`, channelId);
+ return true;
+ }
+
+ if (cmd === '/halt') {
+ if (!this.supervisor) {
+ await channel.send('Sub-agents are not available.', channelId);
+ return true;
+ }
+ await this.supervisor.haltAll();
+ await channel.send('All sub-agents halted and queue cleared.', channelId);
+ return true;
+ }
+
+ if (cmd === '/stop') {
+ if (!this.supervisor) {
+ await channel.send('Sub-agents are not available.', channelId);
+ return true;
+ }
+ await this.supervisor.haltAll();
+ this.supervisor.clearTaskBoard();
+ this.lifecycle.transition('idle');
+ await channel.send('All sub-agents stopped, queue cleared, locks released, task board cleared. Short-term memory preserved.', channelId);
+ return true;
+ }
+
+ if (cmd === '/reset') {
+ if (channelType === 'cli' && channel instanceof CLIChannel) {
+ const confirmed = await channel.askToContinue(
+ '⚠ /reset will halt ALL agents, clear queues, release locks, clear task board, and wipe conversation context. Continue? (y/n)',
+ channelId,
+ ).catch(() => false);
+ if (!confirmed) {
+ await channel.send('Reset cancelled.', channelId);
+ return true;
+ }
+ }
+ if (this.supervisor) {
+ await this.supervisor.haltAll();
+ this.supervisor.clearTaskBoard();
+ }
+ this.shortTerm.clearAll();
+ this.lifecycle.transition('idle');
+ await channel.send('Mercury reset. All agents stopped, all state cleared. Long-term memory preserved. Ready for a fresh start.', channelId);
+ return true;
+ }
+
return false;
}
diff --git a/src/core/file-lock.ts b/src/core/file-lock.ts
new file mode 100644
index 00000000..a2eba1b7
--- /dev/null
+++ b/src/core/file-lock.ts
@@ -0,0 +1,163 @@
+import { resolve, dirname } from 'node:path';
+import { logger } from '../utils/logger.js';
+import type { FileLock } from '../types/agent.js';
+
+export class FileLockManager {
+ private locks: Map<string, FileLock[]> = new Map();
+
+ acquire(filePath: string, agentId: string, mode: 'read' | 'write'): boolean {
+ const normalizedPath = resolve(filePath);
+ const existing = this.locks.get(normalizedPath) || [];
+
+ if (mode === 'read') {
+ const writeLock = existing.find(l => l.mode === 'write');
+ if (writeLock && writeLock.agentId !== agentId) {
+ logger.debug({ path: normalizedPath, lockedBy: writeLock.agentId }, 'File locked for writing, cannot acquire read lock');
+ return false;
+ }
+ const existingLock = existing.find(l => l.agentId === agentId && l.mode === 'read');
+ if (existingLock) return true;
+ const lock: FileLock = {
+ filePath: normalizedPath,
+ agentId,
+ mode: 'read',
+ acquiredAt: Date.now(),
+ };
+ existing.push(lock);
+ this.locks.set(normalizedPath, existing);
+ logger.debug({ path: normalizedPath, agentId, mode: 'read' }, 'Read lock acquired');
+ return true;
+ }
+
+ if (mode === 'write') {
+ const conflictingLock = existing.find(l => l.agentId !== agentId);
+ if (conflictingLock) {
+ logger.debug({ path: normalizedPath, lockedBy: conflictingLock.agentId, lockMode: conflictingLock.mode }, 'File locked, cannot acquire write lock');
+ return false;
+ }
+ const existingWriteLock = existing.find(l => l.agentId === agentId && l.mode === 'write');
+ if (existingWriteLock) return true;
+
+ this.releaseAllFor(agentId, normalizedPath);
+
+ const lock: FileLock = {
+ filePath: normalizedPath,
+ agentId,
+ mode: 'write',
+ acquiredAt: Date.now(),
+ };
+ this.locks.set(normalizedPath, [lock]);
+ logger.debug({ path: normalizedPath, agentId, mode: 'write' }, 'Write lock acquired');
+ return true;
+ }
+
+ return false;
+ }
+
+ release(filePath: string, agentId: string): void {
+ const normalizedPath = resolve(filePath);
+ const existing = this.locks.get(normalizedPath);
+ if (!existing) return;
+
+ const updated = existing.filter(l => !(l.agentId === agentId));
+ if (updated.length === 0) {
+ this.locks.delete(normalizedPath);
+ } else {
+ this.locks.set(normalizedPath, updated);
+ }
+ logger.debug({ path: normalizedPath, agentId }, 'Lock released');
+ }
+
+ private releaseAllFor(agentId: string, normalizedPath: string): void {
+ const existing = this.locks.get(normalizedPath);
+ if (!existing) return;
+
+ const updated = existing.filter(l => l.agentId !== agentId);
+ if (updated.length === 0) {
+ this.locks.delete(normalizedPath);
+ } else {
+ this.locks.set(normalizedPath, updated);
+ }
+ }
+
+ releaseAll(agentId: string): void {
+ for (const [normalizedPath, locks] of this.locks.entries()) {
+ const updated = locks.filter(l => l.agentId !== agentId);
+ if (updated.length === 0) {
+ this.locks.delete(normalizedPath);
+ } else {
+ this.locks.set(normalizedPath, updated);
+ }
+ }
+ logger.debug({ agentId }, 'All locks released for agent');
+ }
+
+ isLocked(filePath: string): boolean {
+ const normalizedPath = resolve(filePath);
+ return (this.locks.get(normalizedPath)?.length ?? 0) > 0;
+ }
+
+ isWriteLockedByOther(filePath: string, agentId: string): boolean {
+ const normalizedPath = resolve(filePath);
+ const existing = this.locks.get(normalizedPath) || [];
+ return existing.some(l => l.mode === 'write' && l.agentId !== agentId);
+ }
+
+ getLocksFor(agentId: string): FileLock[] {
+ const result: FileLock[] = [];
+ for (const locks of this.locks.values()) {
+ for (const lock of locks) {
+ if (lock.agentId === agentId) {
+ result.push(lock);
+ }
+ }
+ }
+ return result;
+ }
+
+ getAllLocks(): FileLock[] {
+ const result: FileLock[] = [];
+ for (const locks of this.locks.values()) {
+ result.push(...locks);
+ }
+ return result;
+ }
+
+ clearAll(): void {
+ this.locks.clear();
+ logger.info('All file locks cleared');
+ }
+
+ detectDeadlock(): string[] | null {
+ const allLocks = this.getAllLocks();
+ const writeLocks = allLocks.filter(l => l.mode === 'write');
+ if (writeLocks.length < 2) return null;
+
+ const agentLocks = new Map<string, Set<string>>();
+ for (const lock of allLocks) {
+ if (!agentLocks.has(lock.agentId)) {
+ agentLocks.set(lock.agentId, new Set());
+ }
+ agentLocks.get(lock.agentId)!.add(lock.filePath);
+ }
+
+ const agentIds = [...agentLocks.keys()];
+ for (let i = 0; i < agentIds.length; i++) {
+ for (let j = i + 1; j < agentIds.length; j++) {
+ const a = agentIds[i];
+ const b = agentIds[j];
+ const locksA = agentLocks.get(a)!;
+ const locksB = agentLocks.get(b)!;
+
+ const aWantsBHas = [...locksB].some(p => this.isWriteLockedByOther(p, a));
+ const bWantsAHas = [...locksA].some(p => this.isWriteLockedByOther(p, b));
+
+ if (aWantsBHas && bWantsAHas) {
+ return [a, b];
+ }
+ }
+ }
+
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/src/core/index.ts b/src/core/index.ts
index 8909a398..eb969efb 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -1,3 +1,9 @@
export { Agent } from './agent.js';
export { Lifecycle } from './lifecycle.js';
-export { Scheduler } from './scheduler.js';
\ No newline at end of file
+export { Scheduler } from './scheduler.js';
+export { SubAgent } from './sub-agent.js';
+export { SubAgentSupervisor } from './supervisor.js';
+export { FileLockManager } from './file-lock.js';
+export { TaskBoard } from './task-board.js';
+export { ResourceManager } from './resource-manager.js';
+export { ProgrammingMode } from './programming-mode.js';
\ No newline at end of file
diff --git a/src/core/lifecycle.ts b/src/core/lifecycle.ts
index 7837fe22..31dfc1f1 100644
--- a/src/core/lifecycle.ts
+++ b/src/core/lifecycle.ts
@@ -15,6 +15,8 @@ const VALID_TRANSITIONS: Transition[] = [
{ from: 'awakening', to: 'idle' },
{ from: 'thinking', to: 'idle' },
{ from: 'idle', to: 'onboarding' },
+ { from: 'idle', to: 'delegating' },
+ { from: 'delegating', to: 'idle' },
];
export class Lifecycle {
diff --git a/src/core/programming-mode.ts b/src/core/programming-mode.ts
new file mode 100644
index 00000000..d12e011a
--- /dev/null
+++ b/src/core/programming-mode.ts
@@ -0,0 +1,99 @@
+import { logger } from '../utils/logger.js';
+
+export type ProgrammingModeState = 'off' | 'plan' | 'execute';
+
+export class ProgrammingMode {
+ private state: ProgrammingModeState = 'off';
+ private projectContext: string | null = null;
+
+ getState(): ProgrammingModeState {
+ return this.state;
+ }
+
+ isActive(): boolean {
+ return this.state !== 'off';
+ }
+
+ isPlan(): boolean {
+ return this.state === 'plan';
+ }
+
+ isExecute(): boolean {
+ return this.state === 'execute';
+ }
+
+ setPlan(): void {
+ this.state = 'plan';
+ logger.info('Programming mode: plan');
+ }
+
+ setExecute(): void {
+ this.state = 'execute';
+ logger.info('Programming mode: execute');
+ }
+
+ setOff(): void {
+ this.state = 'off';
+ this.projectContext = null;
+ logger.info('Programming mode: off');
+ }
+
+ toggle(): ProgrammingModeState {
+ if (this.state === 'off') {
+ this.state = 'plan';
+ } else if (this.state === 'plan') {
+ this.state = 'execute';
+ } else {
+ this.state = 'off';
+ }
+ logger.info({ state: this.state }, 'Programming mode toggled');
+ return this.state;
+ }
+
+ setProjectContext(context: string): void {
+ this.projectContext = context;
+ }
+
+ getProjectContext(): string | null {
+ return this.projectContext;
+ }
+
+ getStatusText(): string {
+ const stateLabels: Record<ProgrammingModeState, string> = {
+ off: 'Off',
+ plan: 'Plan',
+ execute: 'Execute',
+ };
+ let text = `Programming mode: ${stateLabels[this.state]}`;
+ if (this.projectContext) {
+ text += ` | Project: ${this.projectContext}`;
+ }
+ return text;
+ }
+
+ getSystemPromptSuffix(): string {
+ if (this.state === 'off') return '';
+
+ let suffix = '\n\n**PROGRAMMING MODE IS ACTIVE**';
+
+ if (this.state === 'plan') {
+ suffix += '\nMode: PLAN';
+ suffix += '\nYou are in planning mode. Explore the codebase, analyze the problem, and present a step-by-step implementation plan.';
+ suffix += '\nDo NOT write code yet. Present your plan using numbered steps.';
+ suffix += '\nWhen multiple approaches exist, use the ask_user tool to present choices.';
+ suffix += '\nWait for user approval before switching to execution.';
+ } else if (this.state === 'execute') {
+ suffix += '\nMode: EXECUTE';
+ suffix += '\nYou are in execution mode. Implement the plan step by step.';
+ suffix += '\nRun builds/tests after each significant change.';
+ suffix += '\nCommit at logical checkpoints.';
+ suffix += '\nDelegate independent subtasks to sub-agents when possible.';
+ }
+
+ if (this.projectContext) {
+ suffix += `\nProject context: ${this.projectContext}`;
+ }
+
+ return suffix;
+ }
+}
\ No newline at end of file
diff --git a/src/core/resource-manager.ts b/src/core/resource-manager.ts
new file mode 100644
index 00000000..2c8d2c7c
--- /dev/null
+++ b/src/core/resource-manager.ts
@@ -0,0 +1,75 @@
+import { cpus, totalmem, freemem } from 'node:os';
+import { logger } from '../utils/logger.js';
+import type { ResourceUsage } from '../types/agent.js';
+
+const MB = 1024 * 1024;
+const RAM_PER_AGENT_MB = 2048;
+const MIN_FREE_RAM_MB = 1024;
+
+export class ResourceManager {
+ private maxConcurrent: number;
+ private userOverride: number | null = null;
+
+ constructor() {
+ this.maxConcurrent = this.calculateMaxConcurrent();
+ logger.info(
+ { cpuCores: cpus().length, maxConcurrent: this.maxConcurrent, totalRAM: `${Math.round(totalmem() / MB)}MB` },
+ 'ResourceManager initialized',
+ );
+ }
+
+ private calculateMaxConcurrent(): number {
+ const cpuCount = cpus().length;
+ const availableMB = freemem() / MB;
+ const totalMB = totalmem() / MB;
+
+ const cpuBasedMax = Math.max(1, cpuCount - 1);
+ const ramBasedMax = Math.max(1, Math.floor((availableMB - MIN_FREE_RAM_MB) / RAM_PER_AGENT_MB));
+ const systemMax = Math.max(1, Math.floor((totalMB / 2) / RAM_PER_AGENT_MB));
+
+ let max = Math.min(cpuBasedMax, ramBasedMax, systemMax);
+
+ if (max < 1) max = 1;
+ if (availableMB < MIN_FREE_RAM_MB * 2) max = 1;
+
+ return max;
+ }
+
+ getMaxConcurrent(): number {
+ return this.userOverride ?? this.maxConcurrent;
+ }
+
+ setMaxConcurrent(n: number): void {
+ this.userOverride = Math.max(1, n);
+ logger.info({ max: this.userOverride }, 'User override set for max concurrent sub-agents');
+ }
+
+ clearOverride(): void {
+ this.userOverride = null;
+ logger.info('User override cleared, using auto-detected max concurrent');
+ }
+
+ canSpawn(): boolean {
+ this.maxConcurrent = this.calculateMaxConcurrent();
+ const effective = this.userOverride ?? this.maxConcurrent;
+ return effective > 0;
+ }
+
+ getResourceUsage(activeAgents: number, queuedAgents: number, tokenBudgetRemaining: number): ResourceUsage {
+ this.maxConcurrent = this.calculateMaxConcurrent();
+ return {
+ cpuCores: cpus().length,
+ maxConcurrentAgents: this.userOverride ?? this.maxConcurrent,
+ activeAgents,
+ queuedAgents,
+ systemMemoryMB: Math.round(totalmem() / MB),
+ availableMemoryMB: Math.round(freemem() / MB),
+ tokenBudgetRemaining,
+ };
+ }
+
+ refresh(): void {
+ this.maxConcurrent = this.calculateMaxConcurrent();
+ logger.debug({ maxConcurrent: this.maxConcurrent }, 'Resource limits refreshed');
+ }
+}
\ No newline at end of file
diff --git a/src/core/sub-agent.ts b/src/core/sub-agent.ts
new file mode 100644
index 00000000..3a1c1950
--- /dev/null
+++ b/src/core/sub-agent.ts
@@ -0,0 +1,337 @@
+import { generateText, stepCountIs } from 'ai';
+import type { ChannelMessage } from '../types/channel.js';
+import type { SubAgentConfig, SubAgentResult, SubAgentStatus } from '../types/agent.js';
+import type { ProviderRegistry } from '../providers/registry.js';
+import type { Identity } from '../soul/identity.js';
+import type { ShortTermMemory, LongTermMemory, EpisodicMemory } from '../memory/store.js';
+import type { UserMemoryStore } from '../memory/user-memory.js';
+import type { MercuryConfig } from '../utils/config.js';
+import type { TokenBudget } from '../utils/tokens.js';
+import type { CapabilityRegistry } from '../capabilities/registry.js';
+import type { FileLockManager } from './file-lock.js';
+import type { TaskBoard } from './task-board.js';
+import { logger } from '../utils/logger.js';
+
+export type ProgressCallback = (agentId: string, progress: string) => void;
+export type CompletionCallback = (result: SubAgentResult) => void;
+
+export class SubAgent {
+ readonly config: SubAgentConfig;
+ private status: SubAgentStatus = 'pending';
+ private abortController: AbortController;
+ private startTime: number = 0;
+ private result: SubAgentResult | null = null;
+ private filesModified: string[] = [];
+
+ private agentConfig: MercuryConfig;
+ private providers: ProviderRegistry;
+ private identity: Identity;
+ private shortTerm: ShortTermMemory;
+ private longTerm: LongTermMemory;
+ private episodic: EpisodicMemory;
+ private userMemory: UserMemoryStore | null;
+ private capabilities: CapabilityRegistry;
+ private tokenBudget: TokenBudget;
+ private fileLockManager: FileLockManager;
+ private taskBoard: TaskBoard;
+
+ private onProgress?: ProgressCallback;
+ private onComplete?: CompletionCallback;
+
+ constructor(
+ config: SubAgentConfig,
+ dependencies: {
+ agentConfig: MercuryConfig;
+ providers: ProviderRegistry;
+ identity: Identity;
+ shortTerm: ShortTermMemory;
+ longTerm: LongTermMemory;
+ episodic: EpisodicMemory;
+ userMemory: UserMemoryStore | null;
+ capabilities: CapabilityRegistry;
+ tokenBudget: TokenBudget;
+ fileLockManager: FileLockManager;
+ taskBoard: TaskBoard;
+ },
+ ) {
+ this.config = config;
+ this.abortController = new AbortController();
+
+ this.agentConfig = dependencies.agentConfig;
+ this.providers = dependencies.providers;
+ this.identity = dependencies.identity;
+ this.shortTerm = dependencies.shortTerm;
+ this.longTerm = dependencies.longTerm;
+ this.episodic = dependencies.episodic;
+ this.userMemory = dependencies.userMemory;
+ this.capabilities = dependencies.capabilities;
+ this.tokenBudget = dependencies.tokenBudget;
+ this.fileLockManager = dependencies.fileLockManager;
+ this.taskBoard = dependencies.taskBoard;
+ }
+
+ getStatus(): SubAgentStatus {
+ return this.status;
+ }
+
+ abort(): void {
+ this.abortController.abort();
+ logger.info({ agentId: this.config.id }, 'Sub-agent abort signal sent');
+ }
+
+ isAborted(): boolean {
+ return this.abortController.signal.aborted;
+ }
+
+ setProgressCallback(cb: ProgressCallback): void {
+ this.onProgress = cb;
+ }
+
+ setCompletionCallback(cb: CompletionCallback): void {
+ this.onComplete = cb;
+ }
+
+ async run(): Promise<SubAgentResult> {
+ this.status = 'running';
+ this.startTime = Date.now();
+
+ this.taskBoard.update(this.config.id, {
+ status: 'running',
+ startedAt: this.startTime,
+ progress: 'Starting task...',
+ });
+
+ logger.info({ agentId: this.config.id, task: this.config.task.slice(0, 80) }, 'Sub-agent starting');
+
+ try {
+ const systemPrompt = this.buildSystemPrompt();
+ const messages: any[] = [];
+
+ messages.push({
+ role: 'user',
+ content: this.config.task,
+ });
+
+ this.taskBoard.update(this.config.id, { progress: 'Processing...' });
+
+ const originalCwd = this.capabilities.getCwd();
+ if (this.config.workingDirectory) {
+ this.capabilities.setCwd(this.config.workingDirectory);
+ }
+
+ this.capabilities.permissions.setAutoApproveAll(true);
+ this.capabilities.permissions.addTempScope('/', true, true);
+
+ this.capabilities.setChannelContext(
+ this.config.sourceChannelId || 'internal',
+ this.config.sourceChannelType || 'internal',
+ );
+
+ try {
+ const provider = this.providers.getDefault();
+ const maxSteps = this.config.maxSteps || 10;
+
+ logger.info({ agentId: this.config.id, provider: provider.name, maxSteps }, 'Sub-agent generating response');
+
+ if (this.onProgress) {
+ this.onProgress(this.config.id, 'Calling LLM provider...');
+ }
+
+ const result = await generateText({
+ model: provider.getModelInstance(),
+ system: systemPrompt,
+ messages,
+ tools: this.capabilities.getTools(),
+ stopWhen: stepCountIs(maxSteps),
+ abortSignal: this.abortController.signal,
+ onStepFinish: async ({ toolCalls, toolResults }) => {
+ if (this.abortController.signal.aborted) return;
+
+ if (toolCalls && toolResults && toolCalls.length > 0) {
+ const names = toolCalls.map((tc: any) => tc.toolName).join(', ');
+ logger.info({ agentId: this.config.id, tools: names }, 'Sub-agent tool step');
+
+ for (let i = 0; i < toolCalls.length; i++) {
+ const tc = toolCalls[i];
+ const toolName = tc.toolName as string;
+
+ if (['write_file', 'edit_file', 'create_file', 'delete_file'].includes(toolName)) {
+ const filePath = (tc.input as any)?.path || (tc.input as any)?.filePath;
+ if (filePath) {
+ const acquired = this.fileLockManager.acquire(filePath, this.config.id, 'write');
+ if (!acquired) {
+ this.filesModified.push(filePath);
+ }
+ }
+ }
+
+ if (['read_file', 'list_dir'].includes(toolName)) {
+ const filePath = (tc.input as any)?.path || (tc.input as any)?.filePath;
+ if (filePath) {
+ this.fileLockManager.acquire(filePath, this.config.id, 'read');
+ }
+ }
+ }
+
+ if (this.onProgress) {
+ this.onProgress(this.config.id, `Using: ${names}`);
+ }
+ }
+ },
+ });
+
+ if (this.abortController.signal.aborted) {
+ this.status = 'halted';
+ const duration = Date.now() - this.startTime;
+ this.result = {
+ agentId: this.config.id,
+ task: this.config.task,
+ status: 'halted',
+ output: 'Task was halted by user.',
+ filesModified: this.filesModified,
+ duration,
+ tokenUsage: {
+ input: result.usage?.inputTokens ?? 0,
+ output: result.usage?.outputTokens ?? 0,
+ },
+ };
+
+ this.taskBoard.update(this.config.id, {
+ status: 'halted',
+ completedAt: Date.now(),
+ result: this.result.output,
+ });
+
+ return this.result;
+ }
+
+ const finalText = (result.text || '').trim() || '(no text response)';
+
+ this.tokenBudget.recordUsage({
+ provider: provider.name,
+ model: provider.getModel(),
+ inputTokens: result.usage?.inputTokens ?? 0,
+ outputTokens: result.usage?.outputTokens ?? 0,
+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),
+ channelType: 'internal',
+ });
+
+ this.episodic.record({
+ type: 'message',
+ summary: `Sub-agent ${this.config.id}: ${this.config.task.slice(0, 60)} → ${finalText.slice(0, 60)}`,
+ channelType: 'internal',
+ });
+
+ this.status = 'completed';
+ const duration = Date.now() - this.startTime;
+ this.result = {
+ agentId: this.config.id,
+ task: this.config.task,
+ status: 'completed',
+ output: finalText,
+ filesModified: this.filesModified,
+ duration,
+ tokenUsage: {
+ input: result.usage?.inputTokens ?? 0,
+ output: result.usage?.outputTokens ?? 0,
+ },
+ };
+
+ this.taskBoard.update(this.config.id, {
+ status: 'completed',
+ completedAt: Date.now(),
+ result: finalText,
+ progress: 'Task completed',
+ });
+
+ logger.info({ agentId: this.config.id, duration }, 'Sub-agent completed');
+
+ return this.result;
+ } finally {
+ if (this.config.workingDirectory) {
+ this.capabilities.setCwd(originalCwd);
+ }
+ this.capabilities.permissions.setAutoApproveAll(false);
+ this.capabilities.permissions.clearElevation();
+ this.fileLockManager.releaseAll(this.config.id);
+ }
+ } catch (err: any) {
+ if (this.abortController.signal.aborted) {
+ this.status = 'halted';
+ const duration = Date.now() - this.startTime;
+ this.result = {
+ agentId: this.config.id,
+ task: this.config.task,
+ status: 'halted',
+ output: 'Task was halted by user.',
+ filesModified: this.filesModified,
+ duration,
+ tokenUsage: { input: 0, output: 0 },
+ };
+
+ this.taskBoard.update(this.config.id, {
+ status: 'halted',
+ completedAt: Date.now(),
+ result: this.result.output,
+ });
+
+ return this.result;
+ }
+
+ this.status = 'failed';
+ const duration = Date.now() - this.startTime;
+ this.result = {
+ agentId: this.config.id,
+ task: this.config.task,
+ status: 'failed',
+ output: `Task failed: ${err.message}`,
+ error: err.message,
+ filesModified: this.filesModified,
+ duration,
+ tokenUsage: { input: 0, output: 0 },
+ };
+
+ this.taskBoard.update(this.config.id, {
+ status: 'failed',
+ completedAt: Date.now(),
+ result: this.result.output,
+ error: err.message,
+ });
+
+ logger.error({ agentId: this.config.id, err }, 'Sub-agent failed');
+
+ return this.result;
+ }
+ }
+
+ private buildSystemPrompt(): string {
+ let prompt = this.identity.getSystemPrompt(this.agentConfig.identity);
+
+ prompt += `\n\nYou are a sub-agent (ID: ${this.config.id}) working independently on a specific task.`;
+ prompt += `\nTask: ${this.config.task}`;
+ prompt += `\nYou have full permissions for this task. Focus only on completing this task efficiently.`;
+ if (this.config.workingDirectory) {
+ prompt += `\nWorking directory: ${this.config.workingDirectory}`;
+ }
+ if (this.config.allowedTools && this.config.allowedTools.length > 0) {
+ prompt += `\nAllowed tools: ${this.config.allowedTools.join(', ')}`;
+ }
+ prompt += `\nWhen done, provide a clear summary of what you accomplished.`;
+
+ const budgetStatus = this.tokenBudget.getStatusText();
+ prompt += '\n\n' + budgetStatus;
+ 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 toolsList = this.config.allowedTools
+ ? toolNames.filter(t => this.config.allowedTools!.includes(t))
+ : toolNames;
+ prompt += `\n\nAvailable tools: ${toolsList.join(', ')}`;
+
+ return prompt;
+ }
+}
\ No newline at end of file
diff --git a/src/core/supervisor.ts b/src/core/supervisor.ts
new file mode 100644
index 00000000..ee7d64d1
--- /dev/null
+++ b/src/core/supervisor.ts
@@ -0,0 +1,344 @@
+import type { MercuryConfig } from '../utils/config.js';
+import type { ProviderRegistry } from '../providers/registry.js';
+import type { Identity } from '../soul/identity.js';
+import type { ShortTermMemory, LongTermMemory, EpisodicMemory } from '../memory/store.js';
+import type { UserMemoryStore } from '../memory/user-memory.js';
+import type { TokenBudget } from '../utils/tokens.js';
+import type { CapabilityRegistry } from '../capabilities/registry.js';
+import type { SubAgentConfig, SubAgentResult, SubAgentStatus, ResourceUsage } from '../types/agent.js';
+import type { ChannelRegistry } from '../channels/registry.js';
+import { SubAgent } from './sub-agent.js';
+import { FileLockManager } from './file-lock.js';
+import { TaskBoard } from './task-board.js';
+import { ResourceManager } from './resource-manager.js';
+import { logger } from '../utils/logger.js';
+
+export type NotifyCallback = (channelType: string, channelId: string, message: string) => Promise<void>;
+
+export class SubAgentSupervisor {
+ private activeAgents: Map<string, SubAgent> = new Map();
+ private waitQueue: SubAgentConfig[] = [];
+ private fileLockManager: FileLockManager;
+ private taskBoard: TaskBoard;
+ private resourceManager: ResourceManager;
+
+ private agentConfig: MercuryConfig;
+ private providers: ProviderRegistry;
+ private identity: Identity;
+ private shortTerm: ShortTermMemory;
+ private longTerm: LongTermMemory;
+ private episodic: EpisodicMemory;
+ private userMemory: UserMemoryStore | null;
+ private capabilities: CapabilityRegistry;
+ private tokenBudget: TokenBudget;
+ private channels: ChannelRegistry;
+
+ private notifyCallback?: NotifyCallback;
+ private pausedAgents: Set<string> = new Set();
+ private pauseResolvers: Map<string, () => void> = new Map();
+
+ constructor(
+ dependencies: {
+ agentConfig: MercuryConfig;
+ providers: ProviderRegistry;
+ identity: Identity;
+ shortTerm: ShortTermMemory;
+ longTerm: LongTermMemory;
+ episodic: EpisodicMemory;
+ userMemory: UserMemoryStore | null;
+ capabilities: CapabilityRegistry;
+ tokenBudget: TokenBudget;
+ channels: ChannelRegistry;
+ },
+ ) {
+ this.agentConfig = dependencies.agentConfig;
+ this.providers = dependencies.providers;
+ this.identity = dependencies.identity;
+ this.shortTerm = dependencies.shortTerm;
+ this.longTerm = dependencies.longTerm;
+ this.episodic = dependencies.episodic;
+ this.userMemory = dependencies.userMemory;
+ this.capabilities = dependencies.capabilities;
+ this.tokenBudget = dependencies.tokenBudget;
+ this.channels = dependencies.channels;
+
+ this.fileLockManager = new FileLockManager();
+ this.taskBoard = new TaskBoard();
+ this.taskBoard.load();
+ this.resourceManager = new ResourceManager();
+ }
+
+ setNotifyCallback(cb: NotifyCallback): void {
+ this.notifyCallback = cb;
+ }
+
+ private async notify(channelType: string, channelId: string, message: string): Promise<void> {
+ if (this.notifyCallback) {
+ await this.notifyCallback(channelType, channelId, message);
+ }
+ }
+
+ async spawn(config: Omit<SubAgentConfig, 'id'>): Promise<string> {
+ const id = this.taskBoard.nextId();
+ const fullConfig: SubAgentConfig = { ...config, id };
+
+ if (!this.resourceManager.canSpawn()) {
+ logger.info({ task: config.task.slice(0, 50) }, 'No resources available, queuing sub-agent task');
+ this.waitQueue.push(fullConfig);
+ this.taskBoard.create({
+ agentId: id,
+ task: config.task,
+ status: 'pending',
+ priority: config.priority || 'normal',
+ startedAt: Date.now(),
+ filesLocked: [],
+ progress: 'Queued — waiting for resources',
+ sourceChannelId: config.sourceChannelId,
+ sourceChannelType: config.sourceChannelType,
+ });
+ return id;
+ }
+
+ const running = this.getRunningCount();
+ const max = this.resourceManager.getMaxConcurrent();
+ if (running >= max) {
+ logger.info({ task: config.task.slice(0, 50), running, max }, 'Max concurrent agents reached, queuing');
+ this.waitQueue.push(fullConfig);
+ this.taskBoard.create({
+ agentId: id,
+ task: config.task,
+ status: 'pending',
+ priority: config.priority || 'normal',
+ startedAt: Date.now(),
+ filesLocked: [],
+ progress: 'Queued — waiting for slot',
+ sourceChannelId: config.sourceChannelId,
+ sourceChannelType: config.sourceChannelType,
+ });
+ return id;
+ }
+
+ this.taskBoard.create({
+ agentId: id,
+ task: config.task,
+ status: 'pending',
+ priority: config.priority || 'normal',
+ startedAt: Date.now(),
+ filesLocked: [],
+ progress: 'Initializing...',
+ sourceChannelId: config.sourceChannelId,
+ sourceChannelType: config.sourceChannelType,
+ });
+
+ await this.startAgent(fullConfig);
+ return id;
+ }
+
+ private async startAgent(config: SubAgentConfig): Promise<void> {
+ const subAgent = new SubAgent(config, {
+ agentConfig: this.agentConfig,
+ providers: this.providers,
+ identity: this.identity,
+ shortTerm: this.shortTerm,
+ longTerm: this.longTerm,
+ episodic: this.episodic,
+ userMemory: this.userMemory,
+ capabilities: this.capabilities,
+ tokenBudget: this.tokenBudget,
+ fileLockManager: this.fileLockManager,
+ taskBoard: this.taskBoard,
+ });
+
+ this.activeAgents.set(config.id, subAgent);
+
+ subAgent.setProgressCallback((agentId, progress) => {
+ this.taskBoard.update(agentId, { progress });
+ });
+
+ subAgent.setCompletionCallback(async (result: SubAgentResult) => {
+ await this.onAgentComplete(config.id, result);
+ });
+
+ logger.info({ agentId: config.id, task: config.task.slice(0, 60) }, 'Starting sub-agent');
+
+ try {
+ const result = await subAgent.run();
+ await this.onAgentComplete(config.id, result);
+ } catch (err) {
+ logger.error({ agentId: config.id, err }, 'Sub-agent threw unexpected error');
+ this.taskBoard.update(config.id, {
+ status: 'failed',
+ completedAt: Date.now(),
+ error: String(err),
+ progress: 'Failed unexpectedly',
+ });
+ }
+ }
+
+ private async onAgentComplete(agentId: string, result: SubAgentResult): Promise<void> {
+ this.activeAgents.delete(agentId);
+ this.fileLockManager.releaseAll(agentId);
+ this.pausedAgents.delete(agentId);
+
+ logger.info({ agentId, status: result.status, duration: result.duration }, 'Sub-agent completed');
+
+ const entry = this.taskBoard.get(agentId);
+ if (entry) {
+ const channelType = entry.sourceChannelType || 'cli';
+ const channelId = entry.sourceChannelId || 'cli';
+
+ if (result.status === 'completed') {
+ await this.notify(channelType, channelId, `✅ Agent ${agentId} completed: "${entry.task.slice(0, 40)}"\n${result.output.slice(0, 200)}${result.output.length > 200 ? '...' : ''}`);
+ } else if (result.status === 'halted') {
+ await this.notify(channelType, channelId, `⛔ Agent ${agentId} halted: "${entry.task.slice(0, 40)}"`);
+ } else if (result.status === 'failed') {
+ await this.notify(channelType, channelId, `❌ Agent ${agentId} failed: "${entry.task.slice(0, 40)}"\nError: ${result.error || 'unknown'}`);
+ }
+ }
+
+ await this.processWaitQueue();
+ }
+
+ private async processWaitQueue(): Promise<void> {
+ while (this.waitQueue.length > 0) {
+ const running = this.getRunningCount();
+ if (running >= this.resourceManager.getMaxConcurrent()) break;
+
+ const nextConfig = this.waitQueue.shift()!;
+ this.taskBoard.update(nextConfig.id, { status: 'running', progress: 'Starting...' });
+ await this.startAgent(nextConfig);
+ }
+ }
+
+ async halt(agentId: string): Promise<boolean> {
+ const agent = this.activeAgents.get(agentId);
+ if (!agent) {
+ logger.warn({ agentId }, 'Cannot halt — agent not found');
+ return false;
+ }
+
+ agent.abort();
+
+ this.waitQueue = this.waitQueue.filter(c => c.id !== agentId);
+
+ const entry = this.taskBoard.get(agentId);
+ if (entry && entry.status === 'pending') {
+ this.taskBoard.update(agentId, {
+ status: 'halted',
+ completedAt: Date.now(),
+ progress: 'Halted while queued',
+ });
+ }
+
+ return true;
+ }
+
+ async haltAll(): Promise<void> {
+ for (const [agentId, agent] of this.activeAgents.entries()) {
+ agent.abort();
+ }
+
+ for (const config of this.waitQueue) {
+ this.taskBoard.update(config.id, {
+ status: 'halted',
+ completedAt: Date.now(),
+ progress: 'Halted while queued',
+ });
+ }
+ this.waitQueue = [];
+ }
+
+ async pause(agentId: string): Promise<boolean> {
+ const agent = this.activeAgents.get(agentId);
+ if (!agent) return false;
+
+ this.pausedAgents.add(agentId);
+ this.taskBoard.update(agentId, { status: 'paused', progress: 'Paused — waiting to resume' });
+
+ logger.info({ agentId }, 'Sub-agent paused (will stop after current step)');
+ return true;
+ }
+
+ async resume(agentId: string): Promise<boolean> {
+ if (!this.pausedAgents.has(agentId)) return false;
+
+ this.pausedAgents.delete(agentId);
+ this.taskBoard.update(agentId, { status: 'running', progress: 'Resumed' });
+
+ const resolve = this.pauseResolvers.get(agentId);
+ if (resolve) {
+ resolve();
+ this.pauseResolvers.delete(agentId);
+ }
+
+ logger.info({ agentId }, 'Sub-agent resumed');
+ return true;
+ }
+
+ clearTaskBoard(): void {
+ this.fileLockManager.clearAll();
+ this.taskBoard.clear();
+ }
+
+ getResourceUsage(): ResourceUsage {
+ return this.resourceManager.getResourceUsage(
+ this.getRunningCount(),
+ this.waitQueue.length,
+ this.tokenBudget.getRemaining(),
+ );
+ }
+
+ getActiveAgents(): Array<{ id: string; task: string; status: SubAgentStatus; progress?: string }> {
+ const agents: Array<{ id: string; task: string; status: SubAgentStatus; progress?: string }> = [];
+
+ for (const [id, agent] of this.activeAgents.entries()) {
+ const entry = this.taskBoard.get(id);
+ agents.push({
+ id,
+ task: agent.config.task,
+ status: entry?.status || agent.getStatus(),
+ progress: entry?.progress,
+ });
+ }
+
+ for (const config of this.waitQueue) {
+ agents.push({
+ id: config.id,
+ task: config.task,
+ status: 'pending',
+ progress: 'Queued',
+ });
+ }
+
+ return agents;
+ }
+
+ getTaskBoard(): TaskBoard {
+ return this.taskBoard;
+ }
+
+ getFileLockManager(): FileLockManager {
+ return this.fileLockManager;
+ }
+
+ getResourceManager(): ResourceManager {
+ return this.resourceManager;
+ }
+
+ setMaxConcurrent(n: number): void {
+ this.resourceManager.setMaxConcurrent(n);
+ }
+
+ clearMaxConcurrentOverride(): void {
+ this.resourceManager.clearOverride();
+ }
+
+ private getRunningCount(): number {
+ let count = 0;
+ for (const agent of this.activeAgents.values()) {
+ const status = agent.getStatus();
+ if (status === 'running' || status === 'paused') count++;
+ }
+ return count;
+ }
+}
\ No newline at end of file
diff --git a/src/core/task-board.ts b/src/core/task-board.ts
new file mode 100644
index 00000000..db9f8b2c
--- /dev/null
+++ b/src/core/task-board.ts
@@ -0,0 +1,105 @@
+import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
+import { join } from 'node:path';
+import { getMercuryHome } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+import type { TaskBoardEntry, SubAgentStatus } from '../types/agent.js';
+
+const TASK_BOARD_FILE = 'task-board.json';
+
+export class TaskBoard {
+ private entries: Map<string, TaskBoardEntry> = new Map();
+
+ load(): void {
+ const filePath = this.getFilePath();
+ if (existsSync(filePath)) {
+ try {
+ const data = readFileSync(filePath, 'utf-8');
+ const parsed = JSON.parse(data);
+ for (const entry of parsed) {
+ this.entries.set(entry.agentId, entry);
+ }
+ logger.info({ count: this.entries.size }, 'Task board loaded');
+ } catch (err) {
+ logger.warn({ err }, 'Failed to load task board, starting fresh');
+ this.entries.clear();
+ }
+ }
+ }
+
+ save(): void {
+ const filePath = this.getFilePath();
+ const dir = join(getMercuryHome(), 'memory');
+ if (!existsSync(dir)) {
+ mkdirSync(dir, { recursive: true });
+ }
+ writeFileSync(filePath, JSON.stringify([...this.entries.values()], null, 2), 'utf-8');
+ }
+
+ create(entry: TaskBoardEntry): void {
+ this.entries.set(entry.agentId, entry);
+ this.save();
+ logger.info({ agentId: entry.agentId, task: entry.task.slice(0, 50) }, 'Task board entry created');
+ }
+
+ update(agentId: string, partial: Partial<TaskBoardEntry>): void {
+ const existing = this.entries.get(agentId);
+ if (!existing) {
+ logger.warn({ agentId }, 'Task board entry not found for update');
+ return;
+ }
+ this.entries.set(agentId, { ...existing, ...partial });
+ this.save();
+ }
+
+ get(agentId: string): TaskBoardEntry | undefined {
+ return this.entries.get(agentId);
+ }
+
+ getAll(): TaskBoardEntry[] {
+ return [...this.entries.values()];
+ }
+
+ getByStatus(status: SubAgentStatus): TaskBoardEntry[] {
+ return [...this.entries.values()].filter(e => e.status === status);
+ }
+
+ remove(agentId: string): void {
+ this.entries.delete(agentId);
+ this.save();
+ logger.info({ agentId }, 'Task board entry removed');
+ }
+
+ clear(): void {
+ this.entries.clear();
+ this.save();
+ logger.info('Task board cleared');
+ }
+
+ getActiveCount(): number {
+ let count = 0;
+ for (const entry of this.entries.values()) {
+ if (entry.status === 'running' || entry.status === 'pending' || entry.status === 'paused') {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ getRunningCount(): number {
+ return this.getByStatus('running').length;
+ }
+
+ nextId(): string {
+ const existing = [...this.entries.keys()].filter(k => k.startsWith('a'));
+ let max = 0;
+ for (const id of existing) {
+ const num = parseInt(id.slice(1), 10);
+ if (!isNaN(num) && num > max) max = num;
+ }
+ return `a${max + 1}`;
+ }
+
+ private getFilePath(): string {
+ return join(getMercuryHome(), 'memory', TASK_BOARD_FILE);
+ }
+}
\ No newline at end of file
diff --git a/src/index.ts b/src/index.ts
index 884a2964..e2225bb4 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -34,6 +34,8 @@ import { isBetterSqlite3Available } from './memory/second-brain-db.js';
import { ProviderRegistry } from './providers/registry.js';
import { Agent } from './core/agent.js';
import { Scheduler } from './core/scheduler.js';
+import { SubAgentSupervisor } from './core/supervisor.js';
+import { SpotifyClient } from './spotify/client.js';
import { ChannelRegistry } from './channels/registry.js';
import { CLIChannel } from './channels/cli.js';
import { TelegramChannel } from './channels/telegram.js';
@@ -886,45 +888,86 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {
console.log(chalk.bold.white(' GitHub Integration (optional)'));
console.log(chalk.dim(' Connect Mercury to GitHub so it can create PRs, manage issues,'));
console.log(chalk.dim(' review code, and co-author commits on your behalf.'));
- console.log(chalk.dim(' Leave empty to skip. You can add it later with mercury doctor.'));
+ console.log(chalk.dim(' 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(` 1. Your GitHub username${ghUserCurrent}: `));
- if (ghUsername) config.github.username = ghUsername;
+ const ghSetup = await ask(chalk.white(' Configure GitHub? (y/N): '));
+ if (ghSetup.toLowerCase() === 'y' || ghSetup.toLowerCase() === 'yes') {
+ const ghUserCurrent = isReconfig && config.github.username ? ` [${config.github.username}]` : '';
+ const ghUsername = await ask(chalk.white(` 1. Your GitHub username${ghUserCurrent}: `));
+ if (ghUsername) config.github.username = ghUsername;
- if (!config.github.email) {
- config.github.email = '[email protected]';
+ if (!config.github.email) {
+ config.github.email = '[email protected]';
+ }
+
+ console.log('');
+ console.log(chalk.dim(' You need a Personal Access Token (PAT) with repo access.'));
+ console.log(chalk.dim(' Fine-grained (recommended): github.com/settings/personal-access-tokens/new'));
+ console.log(chalk.dim(' → Permissions: Contents (R/W), Pull requests (R/W), Issues (R/W)'));
+ console.log(chalk.dim(' Classic: github.com/settings/tokens/new'));
+ console.log(chalk.dim(' → Scope: repo (full control)'));
+ const ghTokenCurrent = process.env.GITHUB_TOKEN ? ` [${maskKey(process.env.GITHUB_TOKEN)}]` : '';
+ const ghToken = await ask(chalk.white(` 2. GitHub PAT${ghTokenCurrent}: `));
+ if (ghToken) {
+ appendToEnv('GITHUB_TOKEN', ghToken);
+ }
+
+ if (config.github.username || process.env.GITHUB_TOKEN) {
+ console.log('');
+ console.log(chalk.dim(' Set a default repo so you can say "create an issue" without'));
+ console.log(chalk.dim(' specifying the repo every time. Enter owner/name or a full URL.'));
+ console.log(chalk.dim(' Example: hotheadhacker/mercury-agent'));
+ console.log(chalk.dim(' Example: https://github.com/hotheadhacker/mercury-agent'));
+ const ghOwnerCurrent = isReconfig && config.github.defaultOwner ? ` [${config.github.defaultOwner}/${config.github.defaultRepo}]` : '';
+ const ghRepoInput = await ask(chalk.white(` 3. Default repo${ghOwnerCurrent}: `));
+ if (ghRepoInput) {
+ const parsed = parseGithubRepo(ghRepoInput);
+ if (parsed) {
+ config.github.defaultOwner = parsed.owner;
+ config.github.defaultRepo = parsed.repo;
+ } else {
+ console.log(chalk.yellow(' Could not parse repo. Use format: owner/repo or a GitHub URL.'));
+ }
+ }
+ }
}
+ hr();
+ console.log('');
+ console.log(chalk.bold.white(' Spotify Integration (optional)'));
+ console.log(chalk.dim(' Connect Mercury to your Spotify so it can play music,'));
+ console.log(chalk.dim(' manage playlists, and act as your DJ on any of your devices.'));
+ console.log(chalk.dim(' You can add it later with mercury doctor.'));
console.log('');
- console.log(chalk.dim(' You need a Personal Access Token (PAT) with repo access.'));
- console.log(chalk.dim(' Fine-grained (recommended): github.com/settings/personal-access-tokens/new'));
- console.log(chalk.dim(' → Permissions: Contents (R/W), Pull requests (R/W), Issues (R/W)'));
- console.log(chalk.dim(' Classic: github.com/settings/tokens/new'));
- console.log(chalk.dim(' → Scope: repo (full control)'));
- const ghTokenCurrent = process.env.GITHUB_TOKEN ? ` [${maskKey(process.env.GITHUB_TOKEN)}]` : '';
- const ghToken = await ask(chalk.white(` 2. GitHub PAT${ghTokenCurrent}: `));
- if (ghToken) {
- appendToEnv('GITHUB_TOKEN', ghToken);
- }
- if (config.github.username || process.env.GITHUB_TOKEN) {
+ const spotifySetup = await ask(chalk.white(' Configure Spotify? (y/N): '));
+ if (spotifySetup.toLowerCase() === 'y' || spotifySetup.toLowerCase() === 'yes') {
console.log('');
- console.log(chalk.dim(' Set a default repo so you can say "create an issue" without'));
- console.log(chalk.dim(' specifying the repo every time. Enter owner/name or a full URL.'));
- console.log(chalk.dim(' Example: hotheadhacker/mercury-agent'));
- console.log(chalk.dim(' Example: https://github.com/hotheadhacker/mercury-agent'));
- const ghOwnerCurrent = isReconfig && config.github.defaultOwner ? ` [${config.github.defaultOwner}/${config.github.defaultRepo}]` : '';
- const ghRepoInput = await ask(chalk.white(` 3. Default repo${ghOwnerCurrent}: `));
- if (ghRepoInput) {
- const parsed = parseGithubRepo(ghRepoInput);
- if (parsed) {
- config.github.defaultOwner = parsed.owner;
- config.github.defaultRepo = parsed.repo;
- } else {
- console.log(chalk.yellow(' Could not parse repo. Use format: owner/repo or a GitHub URL.'));
- }
+ console.log(chalk.dim(' 1. Go to developer.spotify.com/dashboard'));
+ console.log(chalk.dim(' 2. Click "Create app" — set name: Mercury'));
+ console.log(chalk.dim(' 3. Set redirect URI: http://127.0.0.1:8888/callback'));
+ console.log(chalk.dim(' 4. Copy the Client ID and Client Secret'));
+ console.log('');
+
+ const spotifyIdCurrent = isReconfig && config.spotify.clientId ? ` [${maskKey(config.spotify.clientId)}]` : '';
+ const spotifyClientId = await ask(chalk.white(` 1. Spotify Client ID${spotifyIdCurrent}: `));
+ if (spotifyClientId) {
+ config.spotify.clientId = spotifyClientId;
+ appendToEnv('SPOTIFY_CLIENT_ID', spotifyClientId);
+ }
+
+ const spotifySecretCurrent = isReconfig && config.spotify.clientSecret ? ` [${maskKey(config.spotify.clientSecret)}]` : '';
+ const spotifyClientSecret = await ask(chalk.white(` 2. Spotify Client Secret${spotifySecretCurrent}: `));
+ if (spotifyClientSecret) {
+ config.spotify.clientSecret = spotifyClientSecret;
+ appendToEnv('SPOTIFY_CLIENT_SECRET', spotifyClientSecret);
+ }
+
+ if (spotifyClientId || spotifyClientSecret) {
+ config.spotify.enabled = true;
+ console.log('');
+ console.log(chalk.dim(' After Mercury starts, run /spotify auth to connect your account.'));
}
}
@@ -954,6 +997,9 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {
console.log(chalk.green(` ✓ Memory stored in ${home}/memory/`));
console.log(chalk.green(` ✓ Permissions seeded in ${home}/permissions.yaml`));
console.log(chalk.green(` ✓ Skills directory ready in ${home}/skills/`));
+ if (config.spotify.clientId) {
+ console.log(chalk.green(` ✓ Spotify configured — run /spotify auth to connect your account`));
+ }
console.log('');
console.log(chalk.cyan(` ${config.identity.name} is ready. Run \`mercury start\` to chat.`));
console.log(chalk.dim(' mercury.cosmicstack.org'));
@@ -1070,6 +1116,26 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
const channels = new ChannelRegistry(config);
const capabilities = new CapabilityRegistry(skillLoader, scheduler, tokenBudget);
+ let supervisor: SubAgentSupervisor | undefined;
+ if (config.subagents.enabled) {
+ supervisor = new SubAgentSupervisor({
+ agentConfig: config,
+ providers,
+ identity,
+ shortTerm,
+ longTerm,
+ episodic,
+ userMemory,
+ capabilities,
+ tokenBudget,
+ channels,
+ });
+ if (config.subagents.mode === 'manual' && config.subagents.maxConcurrent > 0) {
+ supervisor.setMaxConcurrent(config.subagents.maxConcurrent);
+ }
+ capabilities.setSupervisor(supervisor);
+ }
+
capabilities.setChatCommandContext({
toolNames: () => capabilities.getToolNames(),
skillNames: () => skills.map(s => s.name),
@@ -1126,6 +1192,23 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
config, providers, identity, shortTerm, longTerm, episodic, userMemory, channels, tokenBudget, capabilities, scheduler,
);
+ if (supervisor) {
+ agent.setSupervisor(supervisor);
+ }
+
+ if (config.spotify.clientId && config.spotify.clientSecret) {
+ const spotifyClient = new SpotifyClient(config);
+ capabilities.setSpotifyClient(spotifyClient);
+ capabilities.registerSpotifyTools();
+ agent.setSpotifyClient(spotifyClient);
+
+ if (spotifyClient.isAuthenticated()) {
+ logger.info('Spotify connected (token available)');
+ } else if (!isDaemon) {
+ console.log(chalk.dim(' Spotify: not connected — run /spotify auth to link your account'));
+ }
+ }
+
await agent.birth();
await agent.wake();
diff --git a/src/memory/store.ts b/src/memory/store.ts
index 2c470f07..9abcff94 100644
--- a/src/memory/store.ts
+++ b/src/memory/store.ts
@@ -90,6 +90,14 @@ export class ShortTermMemory {
if (existsSync(filepath)) unlinkSync(filepath);
}
+ clearAll(): void {
+ for (const conversationId of this.conversations.keys()) {
+ const filepath = join(this.dir, `${conversationId}.json`);
+ if (existsSync(filepath)) unlinkSync(filepath);
+ }
+ this.conversations.clear();
+ }
+
private loadFromDisk(conversationId: string): MemoryEntry[] {
const filepath = join(this.dir, `${conversationId}.json`);
if (!existsSync(filepath)) return [];
diff --git a/src/spotify/client.ts b/src/spotify/client.ts
new file mode 100644
index 00000000..7281dde6
--- /dev/null
+++ b/src/spotify/client.ts
@@ -0,0 +1,491 @@
+import { readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { createServer, IncomingMessage, ServerResponse } from 'node:http';
+import { exec } from 'node:child_process';
+import { promisify } from 'node:util';
+import { getMercuryHome, saveConfig } from '../utils/config.js';
+import type { MercuryConfig } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+
+const execAsync = promisify(exec);
+
+const SPOTIFY_AUTH_URL = 'https://accounts.spotify.com/authorize';
+const SPOTIFY_TOKEN_URL = 'https://accounts.spotify.com/api/token';
+const SPOTIFY_API_BASE = 'https://api.spotify.com/v1';
+
+const REQUIRED_SCOPES = [
+ 'user-read-playback-state',
+ 'user-modify-playback-state',
+ 'user-read-currently-playing',
+ 'user-library-read',
+ 'user-library-modify',
+ 'playlist-read-private',
+ 'playlist-modify-private',
+ 'playlist-modify-public',
+ 'user-top-read',
+ 'user-read-recently-played',
+];
+
+export class SpotifyClient {
+ private config: MercuryConfig;
+ private accessToken: string;
+ private refreshToken: string;
+ private expiresAt: number;
+ private deviceId: string;
+ private isPremium: boolean | null = null;
+
+ constructor(config: MercuryConfig) {
+ this.config = config;
+ this.accessToken = config.spotify.accessToken;
+ this.refreshToken = config.spotify.refreshToken;
+ this.expiresAt = config.spotify.expiresAt ? new Date(config.spotify.expiresAt).getTime() : 0;
+ this.deviceId = config.spotify.deviceId;
+ }
+
+ isAuthenticated(): boolean {
+ return !!(this.accessToken || this.refreshToken);
+ }
+
+ async authenticate(): Promise<string> {
+ const clientId = this.config.spotify.clientId;
+ const constClientSecret = this.config.spotify.clientSecret;
+ const redirectUri = this.config.spotify.redirectUri;
+
+ if (!clientId || !constClientSecret) {
+ throw new Error('Spotify Client ID and Secret must be configured. Set SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET.');
+ }
+
+ const scope = REQUIRED_SCOPES.join(' ');
+ const state = Math.random().toString(36).substring(2, 15);
+ const authUrl = `${SPOTIFY_AUTH_URL}?response_type=code&client_id=${clientId}&scope=${encodeURIComponent(scope)}&redirect_uri=${encodeURIComponent(redirectUri)}&state=${state}`;
+
+ return new Promise((resolve, reject) => {
+ const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
+ const url = new URL(req.url || '/', `http://localhost`);
+
+ if (url.pathname === '/' || url.pathname === '/login') {
+ res.writeHead(302, { Location: authUrl });
+ res.end();
+ return;
+ }
+
+ if (url.pathname === '/callback') {
+ const code = url.searchParams.get('code');
+ const error = url.searchParams.get('error');
+ const returnedState = url.searchParams.get('state');
+
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'text/html' });
+ res.end(`<!DOCTYPE html><html><head><title>Mercury — Spotify Auth</title><style>body{font-family:system-ui;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#1a1a2e;color:#eee;text-align:center;}h1{color:#e74c3c;}p{color:#aaa;}</style></head><body><div><h1>Authorization Failed</h1><p>Spotify authorization was denied or cancelled.</p><p>You can close this tab.</p></div></body></html>`);
+ server.close();
+ reject(new Error(`Spotify auth error: ${error}`));
+ return;
+ }
+
+ if (returnedState !== state) {
+ res.writeHead(400, { 'Content-Type': 'text/html' });
+ res.end(`<!DOCTYPE html><html><head><title>Mercury — Spotify Auth</title><style>body{font-family:system-ui;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#1a1a2e;color:#eee;text-align:center;}h1{color:#e74c3c;}p{color:#aaa;}</style></head><body><div><h1>Security Error</h1><p>State mismatch. Please try again.</p></div></body></html>`);
+ server.close();
+ reject(new Error('Spotify auth state mismatch'));
+ return;
+ }
+
+ try {
+ const tokenResponse: any = await this.exchangeCode(code!, redirectUri);
+ this.accessToken = tokenResponse.access_token;
+ this.refreshToken = tokenResponse.refresh_token;
+ this.expiresAt = Date.now() + tokenResponse.expires_in * 1000;
+
+ this.config.spotify.accessToken = this.accessToken;
+ this.config.spotify.refreshToken = this.refreshToken;
+ this.config.spotify.expiresAt = new Date(this.expiresAt).toISOString();
+ this.config.spotify.scopes = REQUIRED_SCOPES;
+ this.config.spotify.enabled = true;
+ saveConfig(this.config);
+
+ res.writeHead(200, { 'Content-Type': 'text/html' });
+ res.end(`<!DOCTYPE html><html><head><title>Mercury — Spotify Connected</title><style>body{font-family:system-ui;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#1a1a2e;color:#eee;text-align:center;}h1{color:#1db954;font-size:2em;}p{color:#aaa;max-width:400px;margin:0 auto;}.logo{font-size:3em;margin-bottom:0.3em;}</style></head><body><div><div class="logo">&#x266B;</div><h1>Mercury x Spotify</h1><p>Your Spotify account is now connected!</p><p>You can close this tab and return to Mercury.</p><p style="margin-top:2em;color:#666;">Try saying: "play some chill music"</p></div></body></html>`);
+ server.close();
+ logger.info('Spotify authentication successful');
+
+ this.checkPremium().then((premium) => {
+ if (!premium) {
+ logger.warn('Spotify account is not Premium — playback control will be unavailable');
+ }
+ }).catch(() => {});
+
+ resolve(this.accessToken);
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'text/html' });
+ res.end(`<!DOCTYPE html><html><head><title>Mercury — Spotify Auth</title><style>body{font-family:system-ui;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#1a1a2e;color:#eee;text-align:center;}h1{color:#e74c3c;}p{color:#aaa;}</style></head><body><div><h1>Token Exchange Failed</h1><p>Could not exchange authorization code for tokens.</p><p>Please run /spotify auth again.</p></div></body></html>`);
+ server.close();
+ reject(err);
+ }
+ } else {
+ res.writeHead(404);
+ res.end('Not found');
+ }
+ });
+
+ const port = new URL(redirectUri).port || '8888';
+ server.listen(parseInt(port, 10), () => {
+ logger.info({ port }, 'Spotify OAuth server listening');
+ const callbackUrl = `http://127.0.0.1:${port}/login`;
+ console.log(`\n ${'─'.repeat(50)}`);
+ console.log(` Spotify Authorization`);
+ console.log(` ${'─'.repeat(50)}`);
+ console.log(` Opening browser for Spotify login...`);
+ console.log(` If browser doesn't open, visit:\n ${callbackUrl}\n`);
+ console.log(` ${'─'.repeat(50)}\n`);
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
+ execAsync(`${cmd} "${callbackUrl}"`).catch(() => {
+ console.log(` Could not auto-open browser. Visit:\n ${callbackUrl}\n`);
+ });
+ });
+
+ server.setTimeout(300000, () => {
+ server.close();
+ reject(new Error('Spotify auth timed out after 5 minutes'));
+ });
+ });
+ }
+
+ getAuthUrl(): string {
+ const clientId = this.config.spotify.clientId;
+ const redirectUri = this.config.spotify.redirectUri;
+ const scope = REQUIRED_SCOPES.join(' ');
+ const state = Math.random().toString(36).substring(2, 15);
+ return `${SPOTIFY_AUTH_URL}?response_type=code&client_id=${clientId}&scope=${encodeURIComponent(scope)}&redirect_uri=${encodeURIComponent(redirectUri)}&state=${state}`;
+ }
+
+ async authenticateWithCode(code: string): Promise<string> {
+ const redirectUri = this.config.spotify.redirectUri;
+ const tokenResponse: any = await this.exchangeCode(code, redirectUri);
+ this.accessToken = tokenResponse.access_token;
+ this.refreshToken = tokenResponse.refresh_token;
+ this.expiresAt = Date.now() + tokenResponse.expires_in * 1000;
+
+ this.config.spotify.accessToken = this.accessToken;
+ this.config.spotify.refreshToken = this.refreshToken;
+ this.config.spotify.expiresAt = new Date(this.expiresAt).toISOString();
+ this.config.spotify.scopes = REQUIRED_SCOPES;
+ this.config.spotify.enabled = true;
+ saveConfig(this.config);
+
+ logger.info('Spotify authentication successful (manual code)');
+
+ this.checkPremium().then((premium) => {
+ if (!premium) {
+ logger.warn('Spotify account is not Premium — playback control will be unavailable');
+ }
+ }).catch(() => {});
+
+ return this.accessToken;
+ }
+
+ private async exchangeCode(code: string, redirectUri: string): Promise<any> {
+ const response = await fetch(SPOTIFY_TOKEN_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'Authorization': 'Basic ' + Buffer.from(`${this.config.spotify.clientId}:${this.config.spotify.clientSecret}`).toString('base64'),
+ },
+ body: new URLSearchParams({
+ grant_type: 'authorization_code',
+ code,
+ redirect_uri: redirectUri,
+ }).toString(),
+ });
+
+ if (!response.ok) {
+ const text = await response.text();
+ throw new Error(`Spotify token exchange failed: ${response.status} ${text}`);
+ }
+
+ return response.json();
+ }
+
+ private async ensureToken(): Promise<string> {
+ if (this.accessToken && Date.now() < this.expiresAt - 60000) {
+ return this.accessToken;
+ }
+
+ if (!this.refreshToken) {
+ throw new Error('Spotify not authenticated. Run /spotify auth to connect.');
+ }
+
+ logger.info('Refreshing Spotify access token');
+ const response = await fetch(SPOTIFY_TOKEN_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'Authorization': 'Basic ' + Buffer.from(`${this.config.spotify.clientId}:${this.config.spotify.clientSecret}`).toString('base64'),
+ },
+ body: new URLSearchParams({
+ grant_type: 'refresh_token',
+ refresh_token: this.refreshToken,
+ }).toString(),
+ });
+
+ if (!response.ok) {
+ if (response.status === 401) {
+ this.accessToken = '';
+ this.refreshToken = '';
+ this.config.spotify.accessToken = '';
+ this.config.spotify.refreshToken = '';
+ saveConfig(this.config);
+ throw new Error('Spotify refresh token expired. Run /spotify auth again.');
+ }
+ const text = await response.text();
+ throw new Error(`Spotify token refresh failed: ${response.status} ${text}`);
+ }
+
+ const data: any = await response.json();
+ this.accessToken = data.access_token;
+ this.expiresAt = Date.now() + data.expires_in * 1000;
+ if (data.refresh_token) {
+ this.refreshToken = data.refresh_token;
+ }
+
+ this.config.spotify.accessToken = this.accessToken;
+ this.config.spotify.refreshToken = this.refreshToken;
+ this.config.spotify.expiresAt = new Date(this.expiresAt).toISOString();
+ saveConfig(this.config);
+
+ return this.accessToken;
+ }
+
+ private async apiRequest(endpoint: string, options: RequestInit = {}): Promise<any> {
+ const token = await this.ensureToken();
+ const url = endpoint.startsWith('http') ? endpoint : `${SPOTIFY_API_BASE}${endpoint}`;
+
+ const response = await fetch(url, {
+ ...options,
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ ...options.headers,
+ },
+ });
+
+ if (response.status === 204) return null;
+ if (response.status === 401) {
+ this.accessToken = '';
+ throw new Error('Spotify token expired. Retrying...');
+ }
+ if (response.status === 403) {
+ const isPlaybackEndpoint = endpoint.includes('/me/player') && !endpoint.includes('/me/player/devices') && !endpoint.includes('/me/player/currently-playing') && !endpoint.includes('/me/player/queue');
+ if (isPlaybackEndpoint) {
+ throw new Error('Spotify Premium is required for playback control (play, pause, skip, volume, etc.). Read-only features like search, playlists, and liked songs work on free accounts.');
+ }
+ const text = await response.text();
+ throw new Error(`Spotify API error 403: ${text.slice(0, 200)}`);
+ }
+ if (!response.ok) {
+ const text = await response.text();
+ throw new Error(`Spotify API error ${response.status}: ${text.slice(0, 200)}`);
+ }
+
+ return response.json();
+ }
+
+ async search(query: string, type: string = 'track', limit: number = 20): Promise<any> {
+ return this.apiRequest(`/search?q=${encodeURIComponent(query)}&type=${type}&limit=${limit}`);
+ }
+
+ async getDevices(): Promise<any> {
+ return this.apiRequest('/me/player/devices');
+ }
+
+ async play(uris?: string[], contextUri?: string, deviceId?: string): Promise<string> {
+ const id = deviceId || this.deviceId;
+ const endpoint = id ? `/me/player/play?device_id=${id}` : '/me/player/play';
+ const body: any = {};
+ if (contextUri) body.context_uri = contextUri;
+ if (uris) body.uris = uris;
+ if (!contextUri && !uris) {
+ // Resume playback
+ }
+
+ await this.apiRequest(endpoint, { method: 'PUT', body: JSON.stringify(body) });
+ return contextUri
+ ? `Playing context: ${contextUri}${id ? ` on device ${id}` : ''}`
+ : uris
+ ? `Playing ${uris.length} track(s)${id ? ` on device ${id}` : ''}`
+ : 'Playback resumed';
+ }
+
+ async pause(deviceId?: string): Promise<string> {
+ const id = deviceId || this.deviceId;
+ const endpoint = id ? `/me/player/pause?device_id=${id}` : '/me/player/pause';
+ await this.apiRequest(endpoint, { method: 'PUT' });
+ return 'Playback paused';
+ }
+
+ async next(deviceId?: string): Promise<string> {
+ const id = deviceId || this.deviceId;
+ const endpoint = id ? `/me/player/next?device_id=${id}` : '/me/player/next';
+ await this.apiRequest(endpoint, { method: 'POST' });
+ return 'Skipped to next track';
+ }
+
+ async previous(deviceId?: string): Promise<string> {
+ const id = deviceId || this.deviceId;
+ const endpoint = id ? `/me/player/previous?device_id=${id}` : '/me/player/previous';
+ await this.apiRequest(endpoint, { method: 'POST' });
+ return 'Skipped to previous track';
+ }
+
+ async seek(positionMs: number, deviceId?: string): Promise<string> {
+ const id = deviceId || this.deviceId;
+ const endpoint = id ? `/me/player/seek?position_ms=${positionMs}&device_id=${id}` : `/me/player/seek?position_ms=${positionMs}`;
+ await this.apiRequest(endpoint, { method: 'PUT' });
+ return `Seeked to ${Math.floor(positionMs / 1000)}s`;
+ }
+
+ async setRepeat(state: string, deviceId?: string): Promise<string> {
+ const id = deviceId || this.deviceId;
+ const endpoint = id ? `/me/player/repeat?state=${state}&device_id=${id}` : `/me/player/repeat?state=${state}`;
+ await this.apiRequest(endpoint, { method: 'PUT' });
+ const labels: Record<string, string> = { off: 'off', track: 'repeat one', context: 'repeat all' };
+ return `Repeat mode: ${labels[state] || state}`;
+ }
+
+ async setShuffle(state: boolean, deviceId?: string): Promise<string> {
+ const id = deviceId || this.deviceId;
+ const endpoint = id ? `/me/player/shuffle?state=${state}&device_id=${id}` : `/me/player/shuffle?state=${state}`;
+ await this.apiRequest(endpoint, { method: 'PUT' });
+ return `Shuffle ${state ? 'on' : 'off'}`;
+ }
+
+ async setVolume(percent: number, deviceId?: string): Promise<string> {
+ const id = deviceId || this.deviceId;
+ const endpoint = id ? `/me/player/volume?volume_percent=${percent}&device_id=${id}` : `/me/player/volume?volume_percent=${percent}`;
+ await this.apiRequest(endpoint, { method: 'PUT' });
+ return `Volume set to ${percent}%`;
+ }
+
+ async addToQueue(uri: string, deviceId?: string): Promise<string> {
+ const id = deviceId || this.deviceId;
+ const endpoint = id ? `/me/player/queue?uri=${encodeURIComponent(uri)}&device_id=${id}` : `/me/player/queue?uri=${encodeURIComponent(uri)}`;
+ await this.apiRequest(endpoint, { method: 'POST' });
+ return 'Added to queue';
+ }
+
+ async getCurrentlyPlaying(): Promise<any> {
+ return this.apiRequest('/me/player/currently-playing');
+ }
+
+ async getPlaybackState(): Promise<any> {
+ return this.apiRequest('/me/player');
+ }
+
+ async getQueue(): Promise<any> {
+ return this.apiRequest('/me/player/queue');
+ }
+
+ async getLikedTracks(limit: number = 50, offset: number = 0): Promise<any> {
+ return this.apiRequest(`/me/tracks?limit=${limit}&offset=${offset}`);
+ }
+
+ async likeTrack(ids: string): Promise<string> {
+ await this.apiRequest('/me/tracks', { method: 'PUT', body: JSON.stringify({ ids: [ids] }) });
+ return 'Track saved to library';
+ }
+
+ async unlikeTrack(ids: string): Promise<string> {
+ await this.apiRequest(`/me/tracks?ids=${ids}`, { method: 'DELETE' });
+ return 'Track removed from library';
+ }
+
+ async getTopTracks(timeRange: string = 'medium_term', limit: number = 20): Promise<any> {
+ return this.apiRequest(`/me/top/tracks?time_range=${timeRange}&limit=${limit}`);
+ }
+
+ async getTopArtists(timeRange: string = 'medium_term', limit: number = 20): Promise<any> {
+ return this.apiRequest(`/me/top/artists?time_range=${timeRange}&limit=${limit}`);
+ }
+
+ async getPlaylists(limit: number = 50): Promise<any> {
+ return this.apiRequest(`/me/playlists?limit=${limit}`);
+ }
+
+ async getPlaylist(playlistId: string): Promise<any> {
+ return this.apiRequest(`/playlists/${playlistId}`);
+ }
+
+ async createPlaylist(name: string, description: string = '', isPublic: boolean = false): Promise<any> {
+ const userId = await this.getMe();
+ return this.apiRequest(`/users/${userId.id}/playlists`, {
+ method: 'POST',
+ body: JSON.stringify({ name, description, public: isPublic }),
+ });
+ }
+
+ async addTracksToPlaylist(playlistId: string, uris: string[]): Promise<any> {
+ return this.apiRequest(`/playlists/${playlistId}/tracks`, {
+ method: 'POST',
+ body: JSON.stringify({ uris }),
+ });
+ }
+
+ async getMe(): Promise<any> {
+ return this.apiRequest('/me');
+ }
+
+ async checkPremium(): Promise<boolean> {
+ if (this.isPremium !== null) return this.isPremium;
+ try {
+ const me = await this.getMe();
+ this.isPremium = me.product === 'premium';
+ return this.isPremium;
+ } catch {
+ return false;
+ }
+ }
+
+ getPremiumStatus(): boolean | null {
+ return this.isPremium;
+ }
+
+ setDevice(deviceId: string): void {
+ this.deviceId = deviceId;
+ this.config.spotify.deviceId = deviceId;
+ saveConfig(this.config);
+ }
+
+ getDeviceId(): string {
+ return this.deviceId;
+ }
+
+ async getNowPlayingText(): Promise<string> {
+ try {
+ const data = await this.getCurrentlyPlaying();
+ if (!data || !data.item) return 'Nothing playing';
+
+ const track = data.item;
+ const artists = track.artists?.map((a: any) => a.name).join(', ') || 'Unknown';
+ const name = track.name || 'Unknown';
+ const progress = data.progress_ms ? Math.floor(data.progress_ms / 1000) : 0;
+ const duration = track.duration_ms ? Math.floor(track.duration_ms / 1000) : 0;
+ const bar = this.formatProgressBar(progress, duration);
+
+ return `${artists} — ${name} ${bar}`;
+ } catch {
+ return 'Could not fetch playback state';
+ }
+ }
+
+ private formatProgressBar(progress: number, duration: number): string {
+ if (!duration) return '';
+ const pct = Math.floor((progress / duration) * 20);
+ const filled = '█'.repeat(pct);
+ const empty = '░'.repeat(20 - pct);
+ return `[${filled}${empty}] ${this.formatTime(progress)}/${this.formatTime(duration)}`;
+ }
+
+ private formatTime(seconds: number): string {
+ const m = Math.floor(seconds / 60);
+ const s = seconds % 60;
+ return `${m}:${s.toString().padStart(2, '0')}`;
+ }
+}
\ No newline at end of file
diff --git a/src/spotify/index.ts b/src/spotify/index.ts
new file mode 100644
index 00000000..a3844863
--- /dev/null
+++ b/src/spotify/index.ts
@@ -0,0 +1,2 @@
+export { SpotifyClient } from './client.js';
+export { formatNowPlaying, formatTime, PLAYER_CONTROLS, handlePlayerAction } from './ui.js';
\ No newline at end of file
diff --git a/src/spotify/ui.ts b/src/spotify/ui.ts
new file mode 100644
index 00000000..183621eb
--- /dev/null
+++ b/src/spotify/ui.ts
@@ -0,0 +1,87 @@
+import type { SpotifyClient } from './client.js';
+
+export function formatNowPlaying(data: any): string {
+ if (!data || !data.item) return 'Nothing playing';
+ const track = data.item;
+ const artists = track.artists?.map((a: any) => a.name).join(', ') || 'Unknown';
+ const name = track.name || 'Unknown';
+ const progress = data.progress_ms ? Math.floor(data.progress_ms / 1000) : 0;
+ const duration = track.duration_ms ? Math.floor(track.duration_ms / 1000) : 0;
+ const pct = duration ? Math.floor((progress / duration) * 20) : 0;
+ const bar = `[${'█'.repeat(pct)}${'░'.repeat(20 - pct)}]`;
+ const status = data.is_playing ? '▶' : '⏸';
+ const shuffle = data.shuffle_state ? '🔀' : '';
+ const repeat: Record<string, string> = { off: '', track: '🔂', context: '🔁' };
+ const repeatIcon = repeat[data.repeat_state] || '';
+ const albumArt = track.album?.images?.[0]?.url;
+ let text = `${status} **${name}** by ${artists}\n`;
+ text += `${bar} ${formatTime(progress)}/${formatTime(duration)}\n`;
+ text += `${shuffle}${repeatIcon}`;
+ if (albumArt) text += ` | Album: ${track.album?.name}`;
+ return text;
+}
+
+export function formatTime(seconds: number): string {
+ const m = Math.floor(seconds / 60);
+ const s = seconds % 60;
+ return `${m}:${s.toString().padStart(2, '0')}`;
+}
+
+export const PLAYER_CONTROLS = [
+ { value: 'play', label: '▶ Play / Resume' },
+ { value: 'pause', label: '⏸ Pause' },
+ { value: 'next', label: '⏭ Next Track' },
+ { value: 'prev', label: '⏮ Previous Track' },
+ { value: 'shuffle', label: '🔀 Toggle Shuffle' },
+ { value: 'repeat', label: '🔁 Cycle Repeat' },
+ { value: 'now', label: '🎵 Now Playing' },
+ { value: 'devices', label: '📱 Devices' },
+ { value: 'search', label: '🔍 Search & Play' },
+ { value: 'volume', label: '🔊 Set Volume' },
+ { value: 'queue', label: '📋 Add to Queue' },
+ { value: 'like', label: '❤️ Like Current Track' },
+ { value: 'exit', label: '✕ Exit Player' },
+];
+
+export async function handlePlayerAction(
+ action: string,
+ spotify: SpotifyClient,
+): Promise<string> {
+ switch (action) {
+ case 'play':
+ return await spotify.play();
+ case 'pause':
+ return await spotify.pause();
+ case 'next':
+ return await spotify.next();
+ case 'prev':
+ return await spotify.previous();
+ case 'shuffle': {
+ const state = await spotify.getPlaybackState();
+ const newState = !(state?.shuffle_state);
+ return await spotify.setShuffle(newState);
+ }
+ case 'repeat': {
+ const state = await spotify.getPlaybackState();
+ const cycle: Record<string, string> = { off: 'track', track: 'context', context: 'off' };
+ const next = cycle[state?.repeat_state || 'off'] || 'off';
+ return await spotify.setRepeat(next);
+ }
+ case 'now':
+ return await spotify.getNowPlayingText();
+ case 'devices': {
+ const data = await spotify.getDevices();
+ if (!data?.devices?.length) return 'No active devices. Open Spotify on a device.';
+ return data.devices.map((d: any) =>
+ `${d.is_active ? '▶' : '○'} ${d.name} (${d.type}) — ${d.id}`
+ ).join('\n');
+ }
+ case 'like': {
+ const data = await spotify.getCurrentlyPlaying();
+ if (!data?.item?.id) return 'Nothing playing to like.';
+ return await spotify.likeTrack(data.item.id);
+ }
+ default:
+ return 'Unknown action';
+ }
+}
\ No newline at end of file
diff --git a/src/types/agent.ts b/src/types/agent.ts
index afd9decf..a5d7b073 100644
--- a/src/types/agent.ts
+++ b/src/types/agent.ts
@@ -6,7 +6,8 @@ export type AgentState =
| 'thinking'
| 'responding'
| 'sleeping'
- | 'awakening';
+ | 'awakening'
+ | 'delegating';
export type AgentMode = 'cli' | 'daemon' | 'hybrid';
@@ -38,4 +39,68 @@ export interface HeartbeatState {
intervalMinutes: number;
tickCount: number;
lastReflection?: string;
+}
+
+export type SubAgentStatus = 'pending' | 'running' | 'paused' | 'completed' | 'failed' | 'halted';
+
+export type SubAgentPriority = 'low' | 'normal' | 'high';
+
+export interface SubAgentConfig {
+ id: string;
+ task: string;
+ workingDirectory?: string;
+ allowedTools?: string[];
+ maxSteps?: number;
+ priority?: SubAgentPriority;
+ sourceChannelId?: string;
+ sourceChannelType?: string;
+}
+
+export interface SubAgentResult {
+ agentId: string;
+ task: string;
+ status: 'completed' | 'failed' | 'halted';
+ output: string;
+ error?: string;
+ filesModified: string[];
+ duration: number;
+ tokenUsage: { input: number; output: number };
+}
+
+export interface TaskBoardEntry {
+ agentId: string;
+ task: string;
+ status: SubAgentStatus;
+ priority: SubAgentPriority;
+ startedAt: number;
+ completedAt?: number;
+ result?: string;
+ error?: string;
+ filesLocked: string[];
+ progress?: string;
+ sourceChannelId?: string;
+ sourceChannelType?: string;
+}
+
+export interface ResourceUsage {
+ cpuCores: number;
+ maxConcurrentAgents: number;
+ activeAgents: number;
+ queuedAgents: number;
+ systemMemoryMB: number;
+ availableMemoryMB: number;
+ tokenBudgetRemaining: number;
+}
+
+export interface FileLock {
+ filePath: string;
+ agentId: string;
+ mode: 'read' | 'write';
+ acquiredAt: number;
+}
+
+export interface SubagentsConfig {
+ enabled: boolean;
+ maxConcurrent: number;
+ mode: 'auto' | 'manual';
}
\ No newline at end of file
diff --git a/src/utils/config.ts b/src/utils/config.ts
index 0fd0ebdb..a219d25c 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -109,6 +109,22 @@ export interface MercuryConfig {
tokens: {
dailyBudget: number;
};
+ subagents: {
+ enabled: boolean;
+ maxConcurrent: number;
+ mode: 'auto' | 'manual';
+ };
+ spotify: {
+ enabled: boolean;
+ clientId: string;
+ clientSecret: string;
+ redirectUri: string;
+ accessToken: string;
+ refreshToken: string;
+ expiresAt: string;
+ scopes: string[];
+ deviceId: string;
+ };
}
function getEnv(key: string, fallback: string = ''): string {
@@ -235,6 +251,22 @@ export function getDefaultConfig(): MercuryConfig {
tokens: {
dailyBudget: getEnvNum('DAILY_TOKEN_BUDGET', 1_000_000),
},
+ subagents: {
+ enabled: getEnvBool('SUBAGENTS_ENABLED', true),
+ maxConcurrent: getEnvNum('SUBAGENTS_MAX_CONCURRENT', 0),
+ mode: (process.env.SUBAGENTS_MODE as 'auto' | 'manual') || 'auto',
+ },
+ spotify: {
+ enabled: getEnvBool('SPOTIFY_ENABLED', false),
+ clientId: getEnv('SPOTIFY_CLIENT_ID'),
+ clientSecret: getEnv('SPOTIFY_CLIENT_SECRET'),
+ redirectUri: getEnv('SPOTIFY_REDIRECT_URI', 'http://127.0.0.1:8888/callback'),
+ accessToken: '',
+ refreshToken: '',
+ expiresAt: '',
+ scopes: [],
+ deviceId: '',
+ },
};
}
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index 877de325..f3e74e86 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -36,6 +36,24 @@ export function getManual(): string {
['list_scheduled_tasks', 'List all scheduled tasks', '—'],
['cancel_scheduled_task', 'Cancel a scheduled task', 'id'],
['budget_status', 'Check token budget', '—'],
+ ['delegate_task', 'Delegate a task to a sub-agent', 'task, workingDirectory?, priority?, allowedTools?'],
+ ['list_agents', 'List active sub-agents', '—'],
+ ['stop_agent', 'Stop a sub-agent (or all)', 'agentId ("a1" or "all")'],
+ ['ask_user', 'Ask user a question with choices', 'question, choices[]'],
+ ['spotify_search', 'Search Spotify for tracks/artists/albums/playlists', 'query, type?, limit?'],
+ ['spotify_play', 'Play a track/album/playlist on Spotify', 'uri?, deviceId?'],
+ ['spotify_pause', 'Pause Spotify playback', 'deviceId?'],
+ ['spotify_next', 'Skip to next track', '—'],
+ ['spotify_previous', 'Skip to previous track', '—'],
+ ['spotify_now_playing', 'Show currently playing track info', '—'],
+ ['spotify_devices', 'List available Spotify devices', '—'],
+ ['spotify_queue', 'Add track to playback queue', 'uri'],
+ ['spotify_like', 'Like (save) a track to library', 'trackId'],
+ ['spotify_volume', 'Set playback volume', 'percent (0-100)'],
+ ['spotify_shuffle', 'Toggle shuffle on/off', 'state (boolean)'],
+ ['spotify_repeat', 'Set repeat mode', 'state (off/track/context)'],
+ ['spotify_top_tracks', 'Get user\'s top tracks', 'timeRange?, limit?'],
+ ['spotify_playlists', 'Get user\'s playlists', '—'],
];
for (const [name, desc, params] of tools) {
@@ -106,6 +124,27 @@ export function getManual(): string {
['/stream', 'Toggle text streaming on/off (Telegram)'],
['/stream on', 'Enable streaming (live text updates)'],
['/stream off', 'Disable streaming (single message)'],
+ ['/agents', 'List all sub-agents and their status'],
+ ['/agents stop <id|all>', 'Stop a sub-agent or all sub-agents'],
+ ['/agents pause <id>', 'Pause a running sub-agent'],
+ ['/agents resume <id>', 'Resume a paused sub-agent'],
+ ['/agents config', 'Show sub-agent resource allocation'],
+ ['/agents set max <n>', 'Set max concurrent sub-agents'],
+ ['/code', 'Show programming mode status'],
+ ['/code plan', 'Switch to plan mode (analyze, present options, no coding)'],
+ ['/code execute', 'Switch to execute mode (implement plan step by step)'],
+ ['/code off', 'Exit programming mode'],
+ ['/code toggle', 'Cycle through: off → plan → execute → off'],
+ ['/halt', 'Emergency: stop all agents + clear queue'],
+ ['/stop', 'Stop all agents + clear queue + release locks + clear task board'],
+ ['/reset', 'Full reset: stop all + clear context (requires confirmation)'],
+ ['/spotify', 'Show Spotify connection status'],
+ ['/spotify auth', 'Connect Spotify (browser or manual code flow)'],
+ ['/spotify code <code>', 'Complete auth with a pasted authorization code (for SSH/Telegram)'],
+ ['/spotify player', 'Interactive music player (CLI only: arrow-key controls, search, queue)'],
+ ['/spotify devices', 'List available Spotify devices'],
+ ['/spotify device <id>', 'Set active Spotify device'],
+ ['/spotify now', 'Show what is currently playing'],
['/unpair', 'Reset all Telegram access for this Mercury instance (admins only)'],
];
diff --git a/src/utils/tokens.ts b/src/utils/tokens.ts
index 1ac78f10..ad943b1b 100644
--- a/src/utils/tokens.ts
+++ b/src/utils/tokens.ts
@@ -19,6 +19,7 @@ export interface TokenLogEntry {
outputTokens: number;
totalTokens: number;
channelType: string;
+ agentId?: string;
}
const TOKEN_FILE = 'token-usage.json';
@@ -35,6 +36,7 @@ export class TokenBudget {
private lastResetDate: string;
private requestLog: TokenLogEntry[] = [];
private forceNext = false;
+ private perAgentUsage: Map<string, number> = new Map();
constructor(private config: MercuryConfig) {
this.dailyBudget = config.tokens.dailyBudget;
@@ -64,6 +66,7 @@ export class TokenBudget {
resetUsage(): void {
this.dailyUsed = 0;
this.requestLog = [];
+ this.perAgentUsage.clear();
this.persist();
logger.info('Token usage reset to zero');
}
@@ -94,9 +97,22 @@ export class TokenBudget {
const logEntry: TokenLogEntry = { ...safeEntry, timestamp: Date.now() };
this.dailyUsed += totalTokens;
this.requestLog.push(logEntry);
+
+ if (entry.agentId) {
+ const agentUsed = this.perAgentUsage.get(entry.agentId) ?? 0;
+ this.perAgentUsage.set(entry.agentId, agentUsed + totalTokens);
+ }
+
this.persist();
}
+ getUsageByAgent(agentId: string): { used: number; percentage: number } {
+ this.resetIfNewDay();
+ const used = this.perAgentUsage.get(agentId) ?? 0;
+ const budget = safeNumber(this.dailyBudget);
+ return { used, percentage: budget > 0 ? (used / budget) * 100 : 0 };
+ }
+
getRemaining(): number {
this.resetIfNewDay();
return Math.max(0, safeNumber(this.dailyBudget) - safeNumber(this.dailyUsed));
@@ -121,6 +137,7 @@ export class TokenBudget {
this.dailyUsed = 0;
this.lastResetDate = today;
this.requestLog = [];
+ this.perAgentUsage.clear();
this.persist();
logger.info('Token budget reset for new day');
}