Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(cli): integrate OpenClaw/Hermes hetero-agent dispatch with persistent sessions and notify protocol (#15022)

LiJiane87eb8c0339a
diff --git a/apps/cli/src/commands/notify.ts b/apps/cli/src/commands/notify.ts
index ac38c9d6927..a16b51fa88c 100644
--- a/apps/cli/src/commands/notify.ts
+++ b/apps/cli/src/commands/notify.ts
@@ -12,16 +12,38 @@ export function registerNotifyCommand(program: Command) {
.requiredOption('-c, --content <content>', 'Message content')
.option('--agent-id <agentId>', 'Agent ID (overrides topic default)')
.option('--thread-id <threadId>', 'Thread ID for threaded conversations')
+ .option(
+ '--role <role>',
+ 'Message role: user (default, triggers agent reply) | assistant (writes directly as agent message)',
+ 'user',
+ )
+ .option(
+ '--message-id <messageId>',
+ 'When --role assistant: update an existing message instead of creating a new one (keeps a single bubble)',
+ )
+ .option(
+ '--continue',
+ 'When --role assistant: trigger a follow-up agent turn after writing the message',
+ )
.option('--json', 'Output JSON')
.action(
async (options: {
agentId?: string;
content: string;
+ continue?: boolean;
json?: boolean;
+ messageId?: string;
+ role?: 'assistant' | 'user';
threadId?: string;
topic: string;
}) => {
- log.debug('notify: topic=%s, agentId=%s', options.topic, options.agentId);
+ log.debug(
+ 'notify: topic=%s, agentId=%s, role=%s, messageId=%s',
+ options.topic,
+ options.agentId,
+ options.role,
+ options.messageId,
+ );
const client = await getTrpcClient();
@@ -29,6 +51,9 @@ export function registerNotifyCommand(program: Command) {
const result = await client.agentNotify.notify.mutate({
agentId: options.agentId,
content: options.content,
+ continue: options.continue,
+ messageId: options.messageId,
+ role: options.role,
threadId: options.threadId,
topicId: options.topic,
});
diff --git a/apps/cli/src/daemon/taskRegistry.ts b/apps/cli/src/daemon/taskRegistry.ts
new file mode 100644
index 00000000000..a3ffcc1b17b
--- /dev/null
+++ b/apps/cli/src/daemon/taskRegistry.ts
@@ -0,0 +1,51 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+export interface TaskEntry {
+ agentId?: string;
+ agentType: 'hermes' | 'openclaw';
+ operationId: string;
+ pid: number;
+ startedAt: string;
+ taskId: string;
+ topicId: string;
+}
+
+function getRegistryPath(): string {
+ return path.join(os.homedir(), '.lobehub', 'task-registry.json');
+}
+
+function readRegistry(): Record<string, TaskEntry> {
+ try {
+ return JSON.parse(fs.readFileSync(getRegistryPath(), 'utf8')) as Record<string, TaskEntry>;
+ } catch {
+ return {};
+ }
+}
+
+function writeRegistry(entries: Record<string, TaskEntry>): void {
+ const dir = path.dirname(getRegistryPath());
+ fs.mkdirSync(dir, { mode: 0o700, recursive: true });
+ fs.writeFileSync(getRegistryPath(), JSON.stringify(entries, null, 2), { mode: 0o600 });
+}
+
+export function saveTask(entry: TaskEntry): void {
+ const registry = readRegistry();
+ registry[entry.taskId] = entry;
+ writeRegistry(registry);
+}
+
+export function getTask(taskId: string): TaskEntry | undefined {
+ return readRegistry()[taskId];
+}
+
+export function removeTask(taskId: string): void {
+ const registry = readRegistry();
+ delete registry[taskId];
+ writeRegistry(registry);
+}
+
+export function listTasks(): TaskEntry[] {
+ return Object.values(readRegistry());
+}
diff --git a/apps/cli/src/tools/heteroTask.ts b/apps/cli/src/tools/heteroTask.ts
new file mode 100644
index 00000000000..1fab60cba43
--- /dev/null
+++ b/apps/cli/src/tools/heteroTask.ts
@@ -0,0 +1,286 @@
+import { execFileSync, spawn } from 'node:child_process';
+
+import { getTrpcClient } from '../api/client';
+import { getTask, removeTask, saveTask } from '../daemon/taskRegistry';
+import { log } from '../utils/logger';
+
+const DEFAULT_HERMES_PORT = 3456;
+
+/** Resolve the absolute path to the `lh` binary to avoid PATH issues in child processes. */
+function resolveLhPath(): string {
+ try {
+ return execFileSync('which', ['lh'], { encoding: 'utf8' }).trim();
+ } catch {
+ return 'lh';
+ }
+}
+
+/**
+ * Check whether an openclaw session already exists for the given topicId.
+ * The session key format is `agent:<agentId>:explicit:<sessionId>`.
+ * Returns false on any error so that callers default to injecting the full protocol.
+ */
+function openclawSessionExists(agentId: string, topicId: string): boolean {
+ try {
+ const raw = execFileSync('openclaw', ['sessions', '--agent', agentId, '--json'], {
+ encoding: 'utf8',
+ });
+ const data = JSON.parse(raw) as { sessions?: Array<{ key: string }> };
+ const expectedKey = `agent:${agentId}:explicit:${topicId}`;
+ return data.sessions?.some((s) => s.key === expectedKey) ?? false;
+ } catch {
+ return false;
+ }
+}
+
+export interface RunHeteroTaskParams {
+ agentId?: string;
+ agentType: 'hermes' | 'openclaw';
+ cwd?: string;
+ operationId: string;
+ prompt: string;
+ taskId: string;
+ topicId: string;
+}
+
+export interface CancelHeteroTaskParams {
+ signal?: 'SIGINT' | 'SIGKILL' | 'SIGTERM';
+ taskId: string;
+}
+
+function getHermesPort(): number {
+ const env = process.env.HERMES_GATEWAY_PORT;
+ if (env) {
+ const parsed = Number.parseInt(env, 10);
+ if (!Number.isNaN(parsed)) return parsed;
+ }
+ return DEFAULT_HERMES_PORT;
+}
+
+async function isHermesGatewayRunning(port: number): Promise<boolean> {
+ try {
+ const res = await fetch(`http://localhost:${port}/health`);
+ return res.ok;
+ } catch {
+ return false;
+ }
+}
+
+async function startHermesGateway(port: number): Promise<void> {
+ const child = spawn('hermes', ['gateway', 'start'], {
+ detached: true,
+ env: { ...process.env },
+ stdio: 'ignore',
+ });
+ child.unref();
+
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ await new Promise<void>((r) => setTimeout(r, 500));
+ if (await isHermesGatewayRunning(port)) return;
+ }
+ throw new Error(`Hermes gateway did not start within 10s on port ${port}`);
+}
+
+async function sendAutoNotify(
+ topicId: string,
+ taskId: string,
+ text: string,
+ agentId?: string,
+): Promise<void> {
+ try {
+ const client = await getTrpcClient();
+ await client.agentNotify.notify.mutate({
+ agentId,
+ content: text,
+ role: 'assistant',
+ topicId,
+ });
+ } catch (err) {
+ log.error('Failed to send auto-notify:', err instanceof Error ? err.message : String(err));
+ }
+}
+
+/**
+ * Build the notify protocol injected into the first message of a new hetero-agent session.
+ * Tells the agent how to push updates back to the LobeHub user via `lh notify`.
+ */
+function buildNotifyProtocol(lhPath: string, topicId: string): string {
+ return (
+ `## Context: This task was dispatched by LobeHub\n\n` +
+ `This conversation / task was sent to you by the **LobeHub platform** on behalf of a user. You are running as a background agent; the user is waiting for your response inside the LobeHub chat interface.\n\n` +
+ `**When to call notify**: any time you have something meaningful to tell the user β€” a key finding, a decision you made, a result, a question, or your final answer. Think of it as speaking directly to the user in the chat window.\n\n` +
+ `**What to hide**: internal work details such as tool call sequences, file reads, intermediate command output, retries, or low-level reasoning steps. The user cares about outcomes and insights, not your step-by-step mechanics.\n\n` +
+ `## Sending messages back to the user\n\n` +
+ `Use the \`${lhPath} notify\` command. All your updates appear as a **single message bubble** in the UI β€” create it once and update it in place.\n\n` +
+ `**Step 1 β€” Open the bubble on your first meaningful update** (captures the messageId):\n` +
+ `\`\`\`\n` +
+ `MSG_ID=$(${lhPath} notify --topic ${topicId} --role assistant --content "Starting..." --json | grep -o '"messageId":"[^"]*"' | cut -d'"' -f4)\n` +
+ `\`\`\`\n\n` +
+ `**Step 2 β€” Update the same bubble as you make progress**:\n` +
+ `\`\`\`\n` +
+ `${lhPath} notify --topic ${topicId} --role assistant --message-id "$MSG_ID" --content "Still working..."\n` +
+ `\`\`\`\n\n` +
+ `**Step 3 β€” Replace with your complete, final response when done**:\n` +
+ `\`\`\`\n` +
+ `${lhPath} notify --topic ${topicId} --role assistant --message-id "$MSG_ID" --content "<your full response here>"\n` +
+ `\`\`\`\n\n` +
+ `Rules:\n` +
+ `- Always use \`--json\` on the first call and capture \`messageId\` from the output.\n` +
+ `- Always pass \`--message-id\` on every subsequent call so updates overwrite the same bubble.\n` +
+ `- Write what matters to the user β€” not implementation steps or internal tool calls.\n` +
+ `- Call notify at least once when the task is done, even if there were no intermediate updates.`
+ );
+}
+
+export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string> {
+ const { agentId, agentType, cwd, operationId, prompt, taskId, topicId } = params;
+ const workDir = cwd || process.cwd();
+ const lhPath = resolveLhPath();
+
+ if (agentType === 'openclaw') {
+ // openclaw agent --local runs the agent in-process and stays alive until
+ // the agent finishes β€” giving us a real long-lived PID we can kill to cancel.
+ // Requires the `openclaw` binary to be on PATH with Node >=22.19.
+ const openclawAgent = process.env.OPENCLAW_AGENT_ID ?? 'main';
+
+ // Only inject the protocol on the first turn of this session. On subsequent
+ // turns openclaw already has the instructions in its conversation history.
+ const isNewSession = !openclawSessionExists(openclawAgent, topicId);
+ const enrichedPrompt = isNewSession
+ ? `${prompt}\n\n${buildNotifyProtocol(lhPath, topicId)}`
+ : prompt;
+ const child = spawn(
+ 'openclaw',
+ [
+ 'agent',
+ '--agent',
+ openclawAgent,
+ '--session-id',
+ topicId,
+ '--message',
+ enrichedPrompt,
+ '--local',
+ ],
+ {
+ cwd: workDir,
+ detached: true,
+ env: { ...process.env },
+ stdio: 'ignore',
+ },
+ );
+
+ const pid = child.pid;
+ if (pid === undefined) {
+ throw new Error('Failed to get PID for openclaw process');
+ }
+ child.unref();
+
+ saveTask({
+ agentId,
+ agentType,
+ operationId,
+ pid,
+ startedAt: new Date().toISOString(),
+ taskId,
+ topicId,
+ });
+ log.info(`OpenClaw task started: taskId=${taskId} pid=${pid} agent=${openclawAgent}`);
+
+ // Auto-notify on abnormal exit (signal or non-zero code); normal completion
+ // is reported by openclaw itself via `lh notify` (injected into the prompt).
+ child.on('close', (code, signal) => {
+ removeTask(taskId);
+ if (code !== 0 || signal !== null) {
+ const text = signal
+ ? `Task cancelled (signal: ${signal})`
+ : `Task failed (exit code: ${code})`;
+ void sendAutoNotify(topicId, taskId, text, agentId);
+ }
+ });
+
+ return JSON.stringify({ pid, taskId });
+ }
+
+ if (agentType === 'hermes') {
+ const port = getHermesPort();
+
+ if (!(await isHermesGatewayRunning(port))) {
+ log.info(`Hermes gateway not running on port ${port}, starting...`);
+ await startHermesGateway(port);
+ }
+
+ const res = await fetch(`http://localhost:${port}/message`, {
+ body: JSON.stringify({ content: prompt, operationId }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+
+ if (!res.ok) {
+ throw new Error(`Hermes gateway returned ${res.status}: ${await res.text()}`);
+ }
+
+ // pid is 0 for Hermes β€” the gateway is long-lived and cancellation uses
+ // the HTTP /stop API rather than direct signal delivery.
+ saveTask({
+ agentId,
+ agentType,
+ operationId,
+ pid: 0,
+ startedAt: new Date().toISOString(),
+ taskId,
+ topicId,
+ });
+ log.info(`Hermes task dispatched: taskId=${taskId} operationId=${operationId}`);
+
+ return JSON.stringify({ operationId, taskId });
+ }
+
+ throw new Error(`Unsupported agentType: ${agentType as string}`);
+}
+
+export async function cancelHeteroTask(params: CancelHeteroTaskParams): Promise<string> {
+ const { signal = 'SIGINT', taskId } = params;
+ const entry = getTask(taskId);
+
+ if (!entry) {
+ return JSON.stringify({ message: `No task found with taskId: ${taskId}`, success: false });
+ }
+
+ if (entry.agentType === 'hermes') {
+ const port = getHermesPort();
+ try {
+ await fetch(`http://localhost:${port}/stop`, {
+ body: JSON.stringify({ operationId: entry.operationId }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+ } catch (err) {
+ log.warn(
+ `Failed to send /stop to Hermes gateway: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ removeTask(taskId);
+ await sendAutoNotify(entry.topicId, taskId, 'Task cancelled', entry.agentId);
+ return JSON.stringify({ taskId });
+ }
+
+ // OpenClaw: kill by PID and let the child's close handler send the notify.
+ try {
+ process.kill(entry.pid, signal);
+ } catch (err) {
+ // Process already exited β€” exit handler won't fire; clean up manually.
+ log.warn(
+ `Failed to send ${signal} to pid ${entry.pid}: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ removeTask(taskId);
+ await sendAutoNotify(
+ entry.topicId,
+ taskId,
+ 'Task already completed or cancelled',
+ entry.agentId,
+ );
+ }
+
+ return JSON.stringify({ pid: entry.pid, signal, taskId });
+}
diff --git a/apps/cli/src/tools/index.ts b/apps/cli/src/tools/index.ts
index c20089dd0cd..c05c0e4184d 100644
--- a/apps/cli/src/tools/index.ts
+++ b/apps/cli/src/tools/index.ts
@@ -8,9 +8,11 @@ import {
searchLocalFiles,
writeLocalFile,
} from './file';
+import { cancelHeteroTask, runHeteroTask } from './heteroTask';
import { getCommandOutput, killCommand, runCommand } from './shell';
const methodMap: Record<string, (args: any) => Promise<unknown>> = {
+ cancelHeteroTask,
editFile: editLocalFile,
getCommandOutput,
globFiles: globLocalFiles,
@@ -19,6 +21,7 @@ const methodMap: Record<string, (args: any) => Promise<unknown>> = {
listFiles: listLocalFiles,
readFile: readLocalFile,
runCommand,
+ runHeteroTask,
searchFiles: searchLocalFiles,
writeFile: writeLocalFile,
diff --git a/src/server/routers/lambda/agentNotify.ts b/src/server/routers/lambda/agentNotify.ts
index b96c7a7eec8..1a5e3dabc75 100644
--- a/src/server/routers/lambda/agentNotify.ts
+++ b/src/server/routers/lambda/agentNotify.ts
@@ -3,6 +3,7 @@ import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { z } from 'zod';
+import { MessageModel } from '@/database/models/message';
import { TopicModel } from '@/database/models/topic';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -16,6 +17,7 @@ const agentNotifyProcedure = authedProcedure.use(serverDatabase).use(async (opts
return opts.next({
ctx: {
aiAgentService: new AiAgentService(ctx.serverDB, ctx.userId),
+ messageModel: new MessageModel(ctx.serverDB, ctx.userId),
topicModel: new TopicModel(ctx.serverDB, ctx.userId),
},
});
@@ -26,6 +28,24 @@ const NotifySchema = z.object({
agentId: z.string().optional(),
/** Message content from the external agent */
content: z.string(),
+ /**
+ * When role is 'assistant': whether to trigger a new agent turn after writing
+ * the assistant message. Defaults to false.
+ */
+ continue: z.boolean().optional(),
+ /**
+ * When role is 'assistant': update an existing message instead of creating a
+ * new one. The caller is responsible for passing the messageId returned by the
+ * first notify call. Subsequent calls with this id will overwrite the content
+ * in-place, keeping a single bubble in the UI.
+ */
+ messageId: z.string().optional(),
+ /**
+ * Role of the message to write:
+ * - 'user' (default): write as user message and trigger the agent to reply
+ * - 'assistant': write directly as assistant message without an extra LLM call
+ */
+ role: z.enum(['assistant', 'user']).optional(),
/** Thread ID for threaded conversations */
threadId: z.string().optional(),
/** Topic ID to send the message to */
@@ -35,12 +55,32 @@ const NotifySchema = z.object({
export const agentNotifyRouter = router({
/**
* Receive a callback message from an external agent (e.g. Claude Code),
- * write it into a topic, and trigger the agent loop to process it.
+ * write it into a topic, and optionally trigger the agent loop.
+ *
+ * role='user' (default): content becomes a user message β†’ agent replies
+ * role='assistant': content is written directly as an assistant message
+ * continue=true: also trigger a new agent turn after writing
*/
notify: agentNotifyProcedure.input(NotifySchema).mutation(async ({ input, ctx }) => {
- const { topicId, content, agentId: inputAgentId, threadId } = input;
+ const {
+ topicId,
+ content,
+ agentId: inputAgentId,
+ threadId,
+ role = 'user',
+ continue: shouldContinue = false,
+ messageId,
+ } = input;
- log('notify: topicId=%s, agentId=%s, content=%s', topicId, inputAgentId, content.slice(0, 80));
+ log(
+ 'notify: topicId=%s, agentId=%s, role=%s, continue=%s, messageId=%s, content=%s',
+ topicId,
+ inputAgentId,
+ role,
+ shouldContinue,
+ messageId,
+ content.slice(0, 80),
+ );
// 1. Verify the topic exists and get its agentId
const topic = await ctx.topicModel.findById(topicId);
@@ -59,7 +99,66 @@ export const agentNotifyRouter = router({
});
}
- // 2. Trigger the agent loop (execAgent handles message creation internally)
+ // 2a. Assistant mode: write message directly without triggering LLM
+ if (role === 'assistant') {
+ try {
+ // Update existing message if messageId provided (single-bubble progress updates)
+ if (messageId) {
+ await ctx.messageModel.update(messageId, { content });
+ if (shouldContinue) {
+ const result = await ctx.aiAgentService.execAgent({
+ agentId,
+ appContext: { threadId, topicId },
+ parentMessageId: messageId,
+ prompt: '',
+ resume: true,
+ trigger: RequestTrigger.Notify,
+ });
+ return { messageId, operationId: result.operationId, topicId };
+ }
+ return { messageId, operationId: undefined, topicId };
+ }
+
+ const msg = await ctx.messageModel.create({
+ agentId,
+ content,
+ role: 'assistant',
+ threadId: threadId ?? undefined,
+ topicId,
+ });
+
+ // Optionally trigger a follow-up agent turn.
+ // Use resume=true + parentMessageId so execAgent skips creating an
+ // empty user message (effectiveResume=true bypasses that branch).
+ if (shouldContinue) {
+ const result = await ctx.aiAgentService.execAgent({
+ agentId,
+ appContext: { threadId, topicId },
+ parentMessageId: msg.id,
+ prompt: '',
+ resume: true,
+ trigger: RequestTrigger.Notify,
+ });
+
+ return {
+ messageId: msg.id,
+ operationId: result.operationId,
+ topicId,
+ };
+ }
+
+ return { messageId: msg.id, operationId: undefined, topicId };
+ } catch (error: any) {
+ if (error instanceof TRPCError) throw error;
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Failed to write assistant message: ${error.message}`,
+ });
+ }
+ }
+
+ // 2b. User mode (default): trigger the agent loop
try {
const result = await ctx.aiAgentService.execAgent({
agentId,