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: non-blocking sub-agents, channel-aware notifications, fast-path commands, and multi-agent visibility

Salman Qureshi7ddb524c7d5f
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index dcbf83c3..be88b519 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -227,7 +227,7 @@ export class CapabilityRegistry {
logger.info('Web fetch tool registered');
if (this.supervisor) {
- this.tools.delegate_task = createDelegateTaskTool(this.supervisor);
+ this.tools.delegate_task = createDelegateTaskTool(this.supervisor, this);
this.tools.list_agents = createListAgentsTool(this.supervisor);
this.tools.stop_agent = createStopAgentTool(this.supervisor);
logger.info('Sub-agent tools registered');
diff --git a/src/capabilities/subagents/delegate-task.ts b/src/capabilities/subagents/delegate-task.ts
index 78739a95..6aeec3d8 100644
--- a/src/capabilities/subagents/delegate-task.ts
+++ b/src/capabilities/subagents/delegate-task.ts
@@ -2,11 +2,12 @@ import { tool } from 'ai';
import { z } from 'zod';
import { zodSchema } from 'ai';
import type { SubAgentSupervisor } from '../../core/supervisor.js';
+import type { CapabilityRegistry } from '../registry.js';
import { logger } from '../../utils/logger.js';
-export function createDelegateTaskTool(supervisor: SubAgentSupervisor) {
+export function createDelegateTaskTool(supervisor: SubAgentSupervisor, capabilities: CapabilityRegistry) {
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.',
+ description: 'Delegate a task to a sub-agent worker. Use this for complex, multi-step tasks that can run in parallel. The sub-agent works independently — you will be notified when it completes. 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)'),
@@ -17,21 +18,24 @@ export function createDelegateTaskTool(supervisor: SubAgentSupervisor) {
try {
logger.info({ task: task.slice(0, 50) }, 'Delegating task to sub-agent');
+ const { channelId, channelType } = capabilities.getChannelContext();
+
const agentId = await supervisor.spawn({
task,
workingDirectory,
priority: priority || 'normal',
allowedTools,
- sourceChannelId: undefined,
- sourceChannelType: undefined,
+ sourceChannelId: channelId,
+ sourceChannelType: channelType,
});
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.`;
+ let response = `🤖 Multi-agent mode activated.\n\n`;
+ response += `**Agent ${agentId}** is now working on: "${task.slice(0, 80)}${task.length > 80 ? '...' : ''}"\n`;
+ response += `Active agents: ${resourceInfo.activeAgents}/${resourceInfo.maxConcurrentAgents}\n\n`;
+ response += `You can continue chatting while the agent works. I'll notify you when it's done.\n`;
+ response += `Use /agents to check status.`;
return response;
} catch (err: any) {
diff --git a/src/core/agent.ts b/src/core/agent.ts
index b9286aad..345721ff 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -301,10 +301,120 @@ export class Agent {
private enqueueMessage(msg: ChannelMessage): void {
logger.info({ from: msg.channelType, content: msg.content.slice(0, 50) }, 'Message enqueued');
+
+ const trimmed = msg.content.trim();
+ if (this.processing && trimmed.startsWith('/')) {
+ this.handleFastPathCommand(msg).catch((err) => {
+ logger.error({ err, content: trimmed.slice(0, 50) }, 'Fast-path command failed');
+ });
+ return;
+ }
+
this.messageQueue.push(msg);
this.processQueue();
}
+ private async handleFastPathCommand(msg: ChannelMessage): Promise<void> {
+ const trimmed = msg.content.trim();
+ const channel = this.channels.getChannelForMessage(msg);
+ if (!channel) return;
+
+ const activeAgents = this.supervisor ? this.supervisor.getActiveAgents() : [];
+ const hasActiveAgents = activeAgents.length > 0;
+ const busyPrefix = hasActiveAgents ? '' : '';
+
+ if (trimmed === '/agents' || trimmed === '/status') {
+ if (this.supervisor) {
+ const agents = this.supervisor.getActiveAgents();
+ if (agents.length === 0) {
+ await channel.send('No active sub-agents.', msg.channelId);
+ } else {
+ let text = '**Sub-Agents:**\n\n';
+ for (const a of agents) {
+ const icon = a.status === 'running' ? '🔄' : a.status === 'pending' ? '⏳' : a.status === 'completed' ? '✅' : '❌';
+ text += `${icon} **${a.id}**: ${a.task.slice(0, 60)}${a.task.length > 60 ? '...' : ''} — ${a.status}${a.progress ? ` (${a.progress})` : ''}\n`;
+ }
+ await channel.send(text, msg.channelId);
+ }
+ } else {
+ await channel.send('Sub-agents not enabled.', msg.channelId);
+ }
+ return;
+ }
+
+ if (trimmed === '/halt' || trimmed === '/stop') {
+ if (this.supervisor) {
+ await this.supervisor.haltAll();
+ if (trimmed === '/stop') {
+ this.supervisor.clearTaskBoard();
+ }
+ await channel.send(trimmed === '/halt' ? 'All sub-agents halted.' : 'All agents stopped, locks released, task board cleared.', msg.channelId);
+ }
+ return;
+ }
+
+ if (trimmed === '/help') {
+ await channel.send('Agent is busy. Available: /agents, /halt, /stop, /spotify, /code, /memory', msg.channelId);
+ return;
+ }
+
+ if (trimmed.startsWith('/spotify')) {
+ await this.handleFastPathSpotify(trimmed, msg, channel);
+ return;
+ }
+
+ if (trimmed.startsWith('/code')) {
+ await this.handleFastPathCode(trimmed, msg, channel);
+ return;
+ }
+
+ if (trimmed === '/memory') {
+ await channel.send('Agent is busy. Memory management will be available after current task completes.', msg.channelId);
+ return;
+ }
+
+ if (hasActiveAgents) {
+ const agentList = activeAgents.map(a => `**${a.id}**: ${a.task.slice(0, 40)}`).join(', ');
+ await channel.send(`I'm busy working on sub-agent tasks (${agentList}). Your message has been queued — I'll respond once I'm free. Use /agents to check status.`, msg.channelId);
+ } else {
+ await channel.send("I'm busy processing. Your message has been queued — I'll respond once I'm free.", msg.channelId);
+ }
+
+ this.messageQueue.push(msg);
+ }
+
+ private async handleFastPathSpotify(trimmed: string, msg: ChannelMessage, channel: any): Promise<void> {
+ if (!this.spotifyClient) {
+ await channel.send('Spotify is not connected.', msg.channelId);
+ return;
+ }
+ const rawArgs = trimmed.slice('/spotify'.length).trim().toLowerCase();
+ if (!rawArgs || rawArgs === 'status') {
+ const auth = this.spotifyClient.isAuthenticated() ? 'Connected' : 'Not connected';
+ await channel.send(`Spotify: **${auth}**\nDevice: ${this.spotifyClient.getDeviceId() || 'none selected'}`, msg.channelId);
+ return;
+ }
+ if (rawArgs === 'now' || rawArgs === 'playing' || rawArgs === 'np') {
+ try {
+ const text = await this.spotifyClient.getNowPlayingText();
+ await channel.send(text, msg.channelId);
+ } catch (err: any) {
+ await channel.send(`Failed: ${err.message}`, msg.channelId);
+ }
+ return;
+ }
+ await channel.send('Agent is busy. Full Spotify controls will be available after current task completes.', msg.channelId);
+ }
+
+ private async handleFastPathCode(trimmed: string, msg: ChannelMessage, channel: any): Promise<void> {
+ const rawArgs = trimmed.slice('/code'.length).trim().toLowerCase();
+ if (rawArgs === 'status') {
+ await channel.send(this.programmingMode.getStatusText(), msg.channelId);
+ return;
+ }
+ await channel.send('Agent is busy. Programming mode changes will be available after current task completes.', msg.channelId);
+ }
+
private async processQueue(): Promise<void> {
if (this.processing) return;
if (this.messageQueue.length === 0) return;
@@ -355,6 +465,18 @@ export class Agent {
this.lifecycle.transition('thinking');
const startTime = Date.now();
+ if (this.supervisor && msg.channelType !== 'internal') {
+ const activeAgents = this.supervisor.getActiveAgents();
+ const runningAgents = activeAgents.filter(a => a.status === 'running');
+ if (runningAgents.length > 0) {
+ const channel = this.channels.getChannelForMessage(msg);
+ if (channel) {
+ const agentLines = runningAgents.map(a => ` 🔄 ${a.id}: ${a.task.slice(0, 45)}${a.task.length > 45 ? '...' : ''}`);
+ await channel.send(`**Multi-agent mode** — ${runningAgents.length} agent${runningAgents.length > 1 ? 's' : ''} active:\n${agentLines.join('\n')}`, msg.channelId).catch(() => {});
+ }
+ }
+ }
+
const isInternal = msg.channelType === 'internal';
const isScheduled = msg.senderId === 'system' && msg.channelType !== 'internal';
if (isInternal || isScheduled) {
diff --git a/src/core/supervisor.ts b/src/core/supervisor.ts
index ee7d64d1..4e7aad72 100644
--- a/src/core/supervisor.ts
+++ b/src/core/supervisor.ts
@@ -130,11 +130,11 @@ export class SubAgentSupervisor {
sourceChannelType: config.sourceChannelType,
});
- await this.startAgent(fullConfig);
+ this.startAgentInBackground(fullConfig);
return id;
}
- private async startAgent(config: SubAgentConfig): Promise<void> {
+ private startAgentInBackground(config: SubAgentConfig): void {
const subAgent = new SubAgent(config, {
agentConfig: this.agentConfig,
providers: this.providers,
@@ -153,18 +153,20 @@ export class SubAgentSupervisor {
subAgent.setProgressCallback((agentId, progress) => {
this.taskBoard.update(agentId, { progress });
- });
- subAgent.setCompletionCallback(async (result: SubAgentResult) => {
- await this.onAgentComplete(config.id, result);
+ const entry = this.taskBoard.get(agentId);
+ if (entry) {
+ const channelType = entry.sourceChannelType || 'cli';
+ const channelId = entry.sourceChannelId || 'cli';
+ this.notify(channelType, channelId, `🔄 Agent ${agentId}: ${progress}`).catch(() => {});
+ }
});
logger.info({ agentId: config.id, task: config.task.slice(0, 60) }, 'Starting sub-agent');
- try {
- const result = await subAgent.run();
+ subAgent.run().then(async (result) => {
await this.onAgentComplete(config.id, result);
- } catch (err) {
+ }).catch(async (err) => {
logger.error({ agentId: config.id, err }, 'Sub-agent threw unexpected error');
this.taskBoard.update(config.id, {
status: 'failed',
@@ -172,7 +174,11 @@ export class SubAgentSupervisor {
error: String(err),
progress: 'Failed unexpectedly',
});
- }
+ this.activeAgents.delete(config.id);
+ this.fileLockManager.releaseAll(config.id);
+ this.pausedAgents.delete(config.id);
+ await this.processWaitQueue();
+ });
}
private async onAgentComplete(agentId: string, result: SubAgentResult): Promise<void> {
@@ -188,11 +194,13 @@ export class SubAgentSupervisor {
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 ? '...' : ''}`);
+ const duration = result.duration ? `${(result.duration / 1000).toFixed(1)}s` : 'unknown';
+ const output = result.output.length > 500 ? result.output.slice(0, 500) + '...' : result.output;
+ await this.notify(channelType, channelId, `✅ **Agent ${agentId}** completed (${duration}): "${entry.task.slice(0, 40)}"\n\n${output}\n\nType a message to continue.`);
} else if (result.status === 'halted') {
- await this.notify(channelType, channelId, `⛔ Agent ${agentId} halted: "${entry.task.slice(0, 40)}"`);
+ 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.notify(channelType, channelId, `❌ **Agent ${agentId}** failed: "${entry.task.slice(0, 40)}"\nError: ${result.error || 'unknown'}`);
}
}
@@ -206,7 +214,7 @@ export class SubAgentSupervisor {
const nextConfig = this.waitQueue.shift()!;
this.taskBoard.update(nextConfig.id, { status: 'running', progress: 'Starting...' });
- await this.startAgent(nextConfig);
+ this.startAgentInBackground(nextConfig);
}
}