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.

πŸ› fix(hetero-agent): read Hermes session id from stderr (#18027)

AmAzing-6ed937b96453
diff --git a/apps/cli/src/tools/__tests__/heteroTask.test.ts b/apps/cli/src/tools/__tests__/heteroTask.test.ts
index 44b8299c268..f25b760832b 100644
--- a/apps/cli/src/tools/__tests__/heteroTask.test.ts
+++ b/apps/cli/src/tools/__tests__/heteroTask.test.ts
@@ -8,12 +8,27 @@ import { runHeteroTask } from '../heteroTask';
const spawnMock = vi.hoisted(() => vi.fn());
const execFileSyncMock = vi.hoisted(() => vi.fn());
+const fsState = vi.hoisted(() => ({ content: undefined as string | undefined }));
+const notifyMutateMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
vi.mock('node:child_process', () => ({
execFileSync: execFileSyncMock,
spawn: spawnMock,
}));
+vi.mock('node:fs', () => ({
+ default: {
+ mkdirSync: vi.fn(),
+ readFileSync: vi.fn(() => {
+ if (fsState.content === undefined) throw new Error('File not found');
+ return fsState.content;
+ }),
+ writeFileSync: vi.fn((_path: string, content: string) => {
+ fsState.content = content;
+ }),
+ },
+}));
+
// task registry β€” use real implementation backed by a temporary in-memory map
const taskStore: Record<string, any> = {};
vi.mock('../../daemon/taskRegistry', () => ({
@@ -30,7 +45,7 @@ vi.mock('../../daemon/taskRegistry', () => ({
vi.mock('../../api/client', () => ({
getTrpcClient: vi.fn().mockResolvedValue({
agentNotify: {
- notify: { mutate: vi.fn().mockResolvedValue(undefined) },
+ notify: { mutate: notifyMutateMock },
},
}),
}));
@@ -43,6 +58,25 @@ vi.mock('../../utils/logger', () => ({
// ─── Helpers ───
+function resetTrpcClientMock() {
+ notifyMutateMock.mockResolvedValue(undefined);
+ getTrpcClientMock.mockImplementation(
+ () =>
+ Promise.resolve({
+ agentNotify: { notify: { mutate: notifyMutateMock } },
+ }) as ReturnType<typeof getTrpcClient>,
+ );
+}
+
+function makeMockStream() {
+ const listeners: Array<(chunk: Buffer) => void> = [];
+
+ return {
+ on: vi.fn((_event: string, cb: (chunk: Buffer) => void) => listeners.push(cb)),
+ _emit: (content: string) => listeners.forEach((cb) => cb(Buffer.from(content))),
+ };
+}
+
function makeMockChild(pid = 9999) {
const listeners: Record<string, Array<(...a: any[]) => void>> = {};
return {
@@ -50,6 +84,8 @@ function makeMockChild(pid = 9999) {
(listeners[event] ??= []).push(cb);
}),
pid,
+ stderr: makeMockStream(),
+ stdout: makeMockStream(),
unref: vi.fn(),
_emit: (event: string, ...args: any[]) => listeners[event]?.forEach((cb) => cb(...args)),
};
@@ -63,6 +99,7 @@ describe('runHeteroTask (openclaw)', () => {
// Clear task store
for (const key of Object.keys(taskStore)) delete taskStore[key];
execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
+ resetTrpcClientMock();
});
afterEach(() => {
@@ -304,3 +341,122 @@ describe('runHeteroTask (openclaw)', () => {
}
});
});
+
+describe('runHeteroTask (hermes)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ fsState.content = undefined;
+ for (const key of Object.keys(taskStore)) delete taskStore[key];
+ execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
+ resetTrpcClientMock();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('relays stdout intact and saves the final session id from stderr', async () => {
+ const child = makeMockChild();
+ spawnMock.mockReturnValue(child);
+
+ await runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-hermes-1',
+ prompt: 'hello',
+ taskId: 'task-hermes-1',
+ topicId: 'topic-hermes',
+ });
+
+ const [, , spawnOptions] = spawnMock.mock.calls[0] as [string, string[], { stdio: string[] }];
+ expect(spawnOptions.stdio).toEqual(['ignore', 'pipe', 'pipe']);
+
+ child.stdout._emit('session_id: part of the final answer\nHello from Hermes\n');
+ child.stderr._emit(
+ 'Resuming session metadata...\r\nsession_id: session-before-compaction\r\n' +
+ 'Context compacted\r\nsession_id: session-continuation\r\n',
+ );
+ child._emit('close', 0, null);
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(notifyMutateMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'session_id: part of the final answer\nHello from Hermes',
+ topicId: 'topic-hermes',
+ }),
+ );
+ expect(JSON.parse(fsState.content!)).toEqual({
+ 'topic-hermes': 'session-continuation',
+ });
+ });
+
+ it('resumes the saved session and replaces it with a continuation id', async () => {
+ const firstChild = makeMockChild(1001);
+ const secondChild = makeMockChild(1002);
+ const thirdChild = makeMockChild(1003);
+ spawnMock
+ .mockReturnValueOnce(firstChild)
+ .mockReturnValueOnce(secondChild)
+ .mockReturnValueOnce(thirdChild);
+
+ await runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-1',
+ prompt: 'remember this',
+ taskId: 'task-1',
+ topicId: 'topic-multi-turn',
+ });
+ firstChild.stderr._emit('session_id: session-a\n');
+ firstChild._emit('close', 0, null);
+
+ await runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-2',
+ prompt: 'what did I say?',
+ taskId: 'task-2',
+ topicId: 'topic-multi-turn',
+ });
+ expect(spawnMock.mock.calls[1][1]).toEqual([
+ 'chat',
+ '--query',
+ 'what did I say?',
+ '--quiet',
+ '--accept-hooks',
+ '--resume',
+ 'session-a',
+ ]);
+
+ secondChild.stderr._emit('session_id: session-continuation\n');
+ secondChild._emit('close', 0, null);
+
+ await runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-3',
+ prompt: 'continue',
+ taskId: 'task-3',
+ topicId: 'topic-multi-turn',
+ });
+ expect(spawnMock.mock.calls[2][1]).toContain('session-continuation');
+ });
+
+ it('still relays a successful response when stderr has no session id', async () => {
+ const child = makeMockChild();
+ spawnMock.mockReturnValue(child);
+
+ await runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-no-session',
+ prompt: 'hello',
+ taskId: 'task-no-session',
+ topicId: 'topic-no-session',
+ });
+ child.stdout._emit('Successful response\n');
+ child.stderr._emit('Provider diagnostic only\n');
+ child._emit('close', 0, null);
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(notifyMutateMock).toHaveBeenCalledWith(
+ expect.objectContaining({ content: 'Successful response' }),
+ );
+ expect(fsState.content).toBeUndefined();
+ });
+});
diff --git a/apps/cli/src/tools/heteroTask.ts b/apps/cli/src/tools/heteroTask.ts
index 5fe66fb732f..af2aed0c53e 100644
--- a/apps/cli/src/tools/heteroTask.ts
+++ b/apps/cli/src/tools/heteroTask.ts
@@ -16,6 +16,15 @@ import { log } from '../utils/logger';
const LOBEHUB_DIR_NAME = process.env.LOBEHUB_CLI_HOME || '.lobehub';
const HERMES_SESSIONS_FILE = path.join(os.homedir(), LOBEHUB_DIR_NAME, 'hermes-sessions.json');
+function parseHermesSessionId(stderr: string): string | undefined {
+ for (const line of stderr.split(/\r?\n/).reverse()) {
+ const match = line.match(/^session_id:\s*(\S+)\s*$/);
+ if (match) return match[1];
+ }
+
+ return undefined;
+}
+
function getHermesSessionId(topicId: string): string | undefined {
try {
const data = JSON.parse(fs.readFileSync(HERMES_SESSIONS_FILE, 'utf8')) as Record<
@@ -280,13 +289,13 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
hermesArgs.push('--resume', existingSessionId);
}
- // Hermes prints "session_id: <id>\n<response>" to stdout in --quiet mode.
- // We capture stdout, parse both fields on exit, and relay the response via notify.
+ // Hermes keeps stdout response-only in --quiet mode and prints the final
+ // session_id to stderr so callers can resume the session on the next turn.
const child = spawn('hermes', hermesArgs, {
cwd: workDir,
detached: true,
env: childEnv,
- stdio: ['ignore', 'pipe', 'ignore'],
+ stdio: ['ignore', 'pipe', 'pipe'],
});
const pid = child.pid;
@@ -305,10 +314,14 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
});
log.info(`Hermes task started: taskId=${taskId} pid=${pid}`);
+ let stderr = '';
let stdout = '';
child.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString();
});
+ child.stderr.on('data', (chunk: Buffer) => {
+ stderr += chunk.toString();
+ });
child.on('close', (code, signal) => {
removeTask(taskId);
@@ -329,10 +342,10 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<string
return;
}
- // Parse "session_id: <id>" from the first line, response from the rest.
- const sessionIdMatch = stdout.match(/^session_id:\s*(\S+)/m);
- const sessionId = sessionIdMatch?.[1];
- const response = stdout.replace(/^session_id:[^\n]*\n?/, '').trim();
+ // Diagnostics may precede the final ID, and context compaction can rotate
+ // it, so persist the last complete session_id line emitted this turn.
+ const sessionId = parseHermesSessionId(stderr);
+ const response = stdout.trim();
if (sessionId) saveHermesSessionId(topicId, sessionId);
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 4a1fa96369a..df2c790fa60 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -45,6 +45,15 @@ const logger = createLogger('controllers:GatewayConnectionCtr');
// package deps β€” importing one risks the @lobechat/types stub runtime leak.
const BrowserIdentifier = 'lobe-browser';
+function parseHermesSessionId(stderr: string): string | undefined {
+ for (const line of stderr.split(/\r?\n/).reverse()) {
+ const match = line.match(/^session_id:\s*(\S+)\s*$/);
+ if (match) return match[1];
+ }
+
+ return undefined;
+}
+
/**
* Inject the lh-notify protocol into the first turn of a new hetero-agent session.
* Tells the agent binary how to push results back to the LobeHub chat UI via `lh notify`.
@@ -981,7 +990,8 @@ export default class GatewayConnectionCtr extends ControllerModule {
hermesArgs.push('--resume', existingSessionId);
}
- // Hermes prints "session_id: <id>\n<response>" to stdout in --quiet mode.
+ // Hermes keeps stdout response-only in --quiet mode and prints the final
+ // session_id to stderr so callers can resume the session on the next turn.
const child =
process.platform === 'win32'
? execa(commandStatus.path, hermesArgs, {
@@ -989,7 +999,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
detached: true,
env: childEnv,
reject: false,
- stderr: 'ignore',
+ stderr: 'pipe',
stdin: 'ignore',
stdout: 'pipe',
})
@@ -997,7 +1007,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
cwd: workDir,
detached: true,
env: childEnv,
- stdio: ['ignore', 'pipe', 'ignore'],
+ stdio: ['ignore', 'pipe', 'pipe'],
});
const pid = child.pid;
@@ -1013,10 +1023,14 @@ export default class GatewayConnectionCtr extends ControllerModule {
workspaceId,
});
+ let stderr = '';
let stdout = '';
child.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString();
});
+ child.stderr.on('data', (chunk: Buffer) => {
+ stderr += chunk.toString();
+ });
child.on('close', (code, signal) => {
// Keep any pending process-group escalation; see openclaw close handler.
@@ -1047,10 +1061,10 @@ export default class GatewayConnectionCtr extends ControllerModule {
return;
}
- // Parse "session_id: <id>" from the first line, response from the rest.
- const sessionIdMatch = stdout.match(/^session_id:\s*(\S+)/m);
- const sessionId = sessionIdMatch?.[1];
- const response = stdout.replace(/^session_id:[^\n]*\n?/, '').trim();
+ // Diagnostics may precede the final ID, and context compaction can rotate
+ // it, so persist the last complete session_id line emitted this turn.
+ const sessionId = parseHermesSessionId(stderr);
+ const response = stdout.trim();
if (sessionId) this.hermesSessionMap.set(topicId, sessionId);
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index 40618b104e8..54afd08d38c 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -984,6 +984,15 @@ describe('GatewayConnectionCtr', () => {
// ─── runHeteroTask ───
describe('runHeteroTask', () => {
+ function makeMockStream() {
+ const listeners: Array<(chunk: Buffer) => void> = [];
+
+ return {
+ on: vi.fn((_event: string, cb: (chunk: Buffer) => void) => listeners.push(cb)),
+ _emit: (content: string) => listeners.forEach((cb) => cb(Buffer.from(content))),
+ };
+ }
+
/** Creates a minimal mock child process returned by spawn(). */
function makeMockChild(pid = 9999) {
const listeners: Record<string, Array<(...a: any[]) => void>> = {};
@@ -993,6 +1002,8 @@ describe('GatewayConnectionCtr', () => {
listeners[event].push(cb);
}),
pid,
+ stderr: makeMockStream(),
+ stdout: makeMockStream(),
unref: vi.fn(),
_emit: (event: string, ...args: any[]) => listeners[event]?.forEach((cb) => cb(...args)),
};
@@ -1267,6 +1278,127 @@ describe('GatewayConnectionCtr', () => {
killSpy.mockRestore();
});
+
+ describe('hermes', () => {
+ beforeEach(() => {
+ resolveRemotePlatformCommandMock.mockResolvedValue({
+ available: true,
+ path: '/resolved/bin/hermes',
+ resolvedPathEnv: '/resolved/bin:/usr/bin',
+ version: '0.20.0',
+ });
+ });
+
+ it('relays stdout intact and saves the final session id from stderr', async () => {
+ const child = makeMockChild();
+ const notifySpy = vi.spyOn(ctr as any, 'sendNotify').mockResolvedValue(undefined);
+ spawnMock.mockReturnValue(child);
+
+ await (ctr as any).runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-hermes-1',
+ prompt: 'hello',
+ taskId: 'task-hermes-1',
+ topicId: 'topic-hermes',
+ });
+
+ const [command, , spawnOptions] = spawnMock.mock.calls[0] as [
+ string,
+ string[],
+ { stdio: string[] },
+ ];
+ expect(command).toBe('/resolved/bin/hermes');
+ expect(spawnOptions.stdio).toEqual(['ignore', 'pipe', 'pipe']);
+
+ child.stdout._emit('session_id: part of the final answer\nHello from Hermes\n');
+ child.stderr._emit(
+ 'Restored working directory: /repo\r\nsession_id: session-before-compaction\r\n' +
+ 'Context compacted\r\nsession_id: session-continuation\r\n',
+ );
+ child._emit('close', 0, null);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(notifySpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'session_id: part of the final answer\nHello from Hermes',
+ topicId: 'topic-hermes',
+ }),
+ );
+ expect((ctr as any).hermesSessionMap.get('topic-hermes')).toBe('session-continuation');
+ });
+
+ it('resumes the saved session and replaces it with a continuation id', async () => {
+ const firstChild = makeMockChild(1001);
+ const secondChild = makeMockChild(1002);
+ const thirdChild = makeMockChild(1003);
+ spawnMock
+ .mockReturnValueOnce(firstChild)
+ .mockReturnValueOnce(secondChild)
+ .mockReturnValueOnce(thirdChild);
+
+ await (ctr as any).runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-1',
+ prompt: 'remember this',
+ taskId: 'task-1',
+ topicId: 'topic-multi-turn',
+ });
+ firstChild.stderr._emit('session_id: session-a\n');
+ firstChild._emit('close', 0, null);
+
+ await (ctr as any).runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-2',
+ prompt: 'what did I say?',
+ taskId: 'task-2',
+ topicId: 'topic-multi-turn',
+ });
+ expect(spawnMock.mock.calls[1][1]).toEqual([
+ 'chat',
+ '--query',
+ 'what did I say?',
+ '--quiet',
+ '--accept-hooks',
+ '--resume',
+ 'session-a',
+ ]);
+
+ secondChild.stderr._emit('session_id: session-continuation\n');
+ secondChild._emit('close', 0, null);
+
+ await (ctr as any).runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-3',
+ prompt: 'continue',
+ taskId: 'task-3',
+ topicId: 'topic-multi-turn',
+ });
+ expect(spawnMock.mock.calls[2][1]).toContain('session-continuation');
+ });
+
+ it('still relays a successful response when stderr has no session id', async () => {
+ const child = makeMockChild();
+ const notifySpy = vi.spyOn(ctr as any, 'sendNotify').mockResolvedValue(undefined);
+ spawnMock.mockReturnValue(child);
+
+ await (ctr as any).runHeteroTask({
+ agentType: 'hermes',
+ operationId: 'op-no-session',
+ prompt: 'hello',
+ taskId: 'task-no-session',
+ topicId: 'topic-no-session',
+ });
+ child.stdout._emit('Successful response\n');
+ child.stderr._emit('Provider diagnostic only\n');
+ child._emit('close', 0, null);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(notifySpy).toHaveBeenCalledWith(
+ expect.objectContaining({ content: 'Successful response' }),
+ );
+ expect((ctr as any).hermesSessionMap.has('topic-no-session')).toBe(false);
+ });
+ });
});
// ─── Platform Capability Probing ───