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): load Pi CLI guidance as a native skill (#21833)

AmAzing-7df018e172fb
diff --git a/apps/cli/src/commands/hetero.pi.test.ts b/apps/cli/src/commands/hetero.pi.test.ts
new file mode 100644
index 00000000000..f5be27a7aac
--- /dev/null
+++ b/apps/cli/src/commands/hetero.pi.test.ts
@@ -0,0 +1,105 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { PassThrough } from 'node:stream';
+
+import { buildHeterogeneousPrompt } from '@lobechat/heterogeneous-agents/protocol';
+import type * as HeteroRpc from '@lobechat/heterogeneous-agents/rpc';
+import { Command } from 'commander';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { registerHeteroCommand } from './hetero';
+
+const { createHandle, finish, ingest } = vi.hoisted(() => ({
+ createHandle: vi.fn(),
+ finish: vi.fn().mockResolvedValue({ ack: true }),
+ ingest: vi.fn().mockResolvedValue({ ack: true }),
+}));
+
+vi.mock('@lobechat/heterogeneous-agents/rpc', async (importOriginal) => ({
+ ...(await importOriginal<typeof HeteroRpc>()),
+ createPiRpcAgentHandle: createHandle,
+}));
+vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({
+ resolveHeteroSpawnCommand: async () => ({ command: 'pi' }),
+}));
+vi.mock('../api/client', () => ({
+ getTrpcClient: async () => ({
+ aiAgent: { heteroFinish: { mutate: finish }, heteroIngest: { mutate: ingest } },
+ }),
+}));
+vi.mock('../utils/OperationTokenRenewal', () => ({
+ createOperationTokenRenewal: () => ({ active: true, stop: vi.fn() }),
+}));
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+});
+
+describe('Pi dispatched prompt delivery', () => {
+ it.each([false, true])(
+ 'loads a native skill without including the guide in user text (resume: %s)',
+ async (resumed) => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'lh-pi-dispatch-'));
+ const inputPath = path.join(dir, 'input.json');
+ const stderr = new PassThrough();
+ stderr.end();
+ createHandle.mockResolvedValue({
+ events: (async function* () {})(),
+ exit: Promise.resolve({ code: 0, signal: null }),
+ kill: vi.fn(),
+ pid: undefined,
+ stderr,
+ });
+ const exit = vi.spyOn(process, 'exit').mockImplementation(() => {
+ throw new Error('test process exit');
+ });
+ vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+
+ try {
+ await writeFile(
+ inputPath,
+ JSON.stringify(
+ buildHeterogeneousPrompt({
+ isNewSession: !resumed,
+ prompt: 'Read the local file',
+ systemContext: 'Selected source text',
+ }),
+ ),
+ );
+ const program = new Command();
+ program.exitOverride();
+ registerHeteroCommand(program);
+ await expect(
+ program.parseAsync(
+ [
+ 'hetero',
+ 'exec',
+ '--type',
+ 'pi',
+ '--input-json',
+ inputPath,
+ '--topic',
+ 'tpc_pi_dispatch',
+ '--operation-id',
+ 'op-pi-dispatch',
+ ...(resumed ? ['--resume', 'pi-native-session'] : []),
+ ],
+ { from: 'user' },
+ ),
+ ).rejects.toThrow('test process exit');
+
+ expect(exit).toHaveBeenCalledWith(0);
+ expect(createHandle).toHaveBeenCalledOnce();
+ const launch = createHandle.mock.calls[0][0];
+ expect(launch.args).toEqual(['--skill', expect.any(String)]);
+ expect(await readFile(launch.args[1], 'utf8')).toContain('# LobeHub CLI (`lh`)');
+ expect(launch.prompt).toEqual({ text: 'Selected source text\n\nRead the local file' });
+ expect(launch.resumeSessionId).toBe(resumed ? 'pi-native-session' : undefined);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ },
+ );
+});
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 166468a2117..90d1e0a4953 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -6,6 +6,7 @@ import { PassThrough } from 'node:stream';
import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import { createAdapter, HETEROGENEOUS_AGENT_CONFIGS } from '@lobechat/heterogeneous-agents';
import { HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV } from '@lobechat/heterogeneous-agents/protocol';
+import type * as HeteroRpc from '@lobechat/heterogeneous-agents/rpc';
import type * as HeteroSpawn from '@lobechat/heterogeneous-agents/spawn';
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -45,10 +46,9 @@ vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({
resolveHeteroSpawnCommand: mockResolveHeteroSpawnCommand,
}));
-vi.mock('@lobechat/heterogeneous-agents/rpc', () => ({
+vi.mock('@lobechat/heterogeneous-agents/rpc', async (importOriginal) => ({
+ ...(await importOriginal<typeof HeteroRpc>()),
createPiRpcAgentHandle: mockCreatePiRpcAgentHandle,
- toPiRpcPrompt: (input: unknown) =>
- Promise.resolve({ text: typeof input === 'string' ? input : JSON.stringify(input) }),
}));
vi.mock('../api/client', () => ({
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index ed30723203e..bcef6e9dff5 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -18,7 +18,7 @@ import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolv
import {
createPiRpcAgentHandle,
type PiRpcStartupControl,
- toPiRpcPrompt,
+ preparePiRpcInput,
} from '@lobechat/heterogeneous-agents/rpc';
import type {
AgentContentBlock,
@@ -91,11 +91,8 @@ const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';
const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';
/**
- * Runtime selection registry for `lh hetero exec` β€” the CLI counterpart of
- * the desktop controller's `runtimeDispatchers`. Long-lived bidirectional
- * runtimes (pi RPC) register a spawn factory here; every other agent uses the
- * generic one-shot `spawnAgent`. A future agent adopting an RPC mode only
- * adds one entry β€” no dispatch edit.
+ * Runtime factories for `lh hetero exec`. Pi uses RPC; other agents fall
+ * through to the generic one-shot `spawnAgent`.
*/
const spawnRuntimeRegistry: Partial<
Record<
@@ -111,7 +108,10 @@ const spawnRuntimeRegistry: Partial<
> = {
pi: async (spawnOpts, lifecycle) =>
createPiRpcAgentHandle({
- args: spawnOpts.extraArgs ?? [],
+ ...(await preparePiRpcInput(spawnOpts.prompt, {
+ args: spawnOpts.extraArgs ?? [],
+ lobeHubContext: !!spawnOpts.env?.LOBEHUB_TOPIC_ID,
+ })),
commandPath: spawnOpts.command!,
cwd: spawnOpts.cwd ?? process.cwd(),
detached: spawnOpts.detached,
@@ -119,7 +119,6 @@ const spawnRuntimeRegistry: Partial<
operationId: spawnOpts.operationId,
onRawStdout: lifecycle?.onRawStdout,
onStartupControl: lifecycle?.onStartupControl,
- prompt: await toPiRpcPrompt(spawnOpts.prompt),
resumeSessionId: spawnOpts.resumeSessionId,
uploadImage: spawnOpts.uploadImage,
}),
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index fda55c21ef4..89db565c256 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -59,9 +59,9 @@ import {
} from '@lobechat/heterogeneous-agents/quota-sampler';
import { isLoginShellTimeoutStatus } from '@lobechat/heterogeneous-agents/resolveCliCommand';
import {
- type PiRpcImage,
PiRpcSession,
type PiRpcSessionCallbacks,
+ preparePiRpcInput,
} from '@lobechat/heterogeneous-agents/rpc';
import type {
AgentStreamEvent,
@@ -97,7 +97,6 @@ import {
isCursorAcpSessionNotFoundError,
isDevinAcpSessionNotFoundError,
isDroidAcpSessionNotFoundError,
- normalizeImage,
prepareClaudeCodeLobeHubCli,
readClaudeCodeSessionCost,
readCodexSessionModel,
@@ -2767,32 +2766,14 @@ export default class HeterogeneousAgentCtr {
prompt: params.prompt,
systemContext: params.systemContext,
});
- const text: string[] = [];
- const images: PiRpcImage[] = [];
- for (const block of promptBlocks) {
- if (block.type === 'text') {
- if (block.text) text.push(block.text);
- continue;
- }
- try {
- const image = await normalizeImage(block.source, { cacheDir: this.fileCacheDir });
- images.push({
- data: image.buffer.toString('base64'),
- mimeType: image.mediaType,
- type: 'image',
- });
- } catch (error) {
- // A broken attachment must not silently drop the image from the
- // prompt β€” surface it like the Codex/Grok paths do.
- throw new Error(
- `Failed to attach image(s) to Pi RPC prompt: ${this.getErrorMessage(error) || 'Unknown error'}`,
- { cause: error },
- );
- }
- }
+ const input = await preparePiRpcInput(promptBlocks, {
+ args: session.args,
+ cacheDir: this.fileCacheDir,
+ lobeHubContext: true,
+ });
const traceSession = await this.createCliTraceSession({
- cliArgs: ['--mode', 'rpc', ...session.args],
+ cliArgs: ['--mode', 'rpc', ...input.args],
cwd,
imageList: params.imageList ?? [],
session,
@@ -2824,7 +2805,7 @@ export default class HeterogeneousAgentCtr {
const spawnFingerprint = [
commandPath,
cwd,
- JSON.stringify(session.args ?? []),
+ JSON.stringify(input.args),
JSON.stringify(
Object.entries(spawnEnv)
.filter(([key]) => key !== 'LOBEHUB_OPERATION_ID')
@@ -2836,7 +2817,7 @@ export default class HeterogeneousAgentCtr {
const rpcSession =
pooledSession ??
new PiRpcSession({
- args: session.args,
+ args: input.args,
commandPath,
cwd,
env: spawnEnv,
@@ -2859,10 +2840,7 @@ export default class HeterogeneousAgentCtr {
});
try {
- const { aborted } = await rpcSession.run({
- text: text.join('\n\n'),
- ...(images.length > 0 ? { images } : {}),
- });
+ const { aborted } = await rpcSession.run(input.prompt);
if (session.piRpcSession === rpcSession) session.piRpcSession = undefined;
// Hand the process to the pool for the next turn (native id known now).
// A fresh process without a native id cannot be keyed β€” recycle it.
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index b291ab9f5d0..efc11be68ce 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -549,7 +549,7 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
};
});
-vi.mock('@lobechat/heterogeneous-agents/rpc', () => {
+vi.mock('@lobechat/heterogeneous-agents/rpc', async (importOriginal) => {
class MockPiRpcSession {
isReusable = true;
constructor(private readonly options: any) {
@@ -568,10 +568,9 @@ vi.mock('@lobechat/heterogeneous-agents/rpc', () => {
piRpcSessionRebindMock(callbacks);
}
- async run() {
- if (piRpcSessionRunMock.getMockImplementation()) {
- return piRpcSessionRunMock(this.options);
- }
+ async run(prompt: { text: string }) {
+ const result = piRpcSessionRunMock(this.options, prompt);
+ if (result) return result;
const now = Date.now();
this.options.onSessionId('pi_sess_1');
await this.options.onEvents([
@@ -586,7 +585,7 @@ vi.mock('@lobechat/heterogeneous-agents/rpc', () => {
}
}
- return { PiRpcSession: MockPiRpcSession };
+ return { ...(await importOriginal<object>()), PiRpcSession: MockPiRpcSession };
});
const { consumeCodexRateLimitResetCreditMock, fetchCodexQuotaMock } = vi.hoisted(() => ({
@@ -4583,7 +4582,7 @@ describe('HeterogeneousAgentCtr', () => {
expect(piRpcSessionConstructMock).toHaveBeenCalledWith(
expect.objectContaining({
- args: ['--provider', 'anthropic'],
+ args: ['--skill', expect.stringContaining('SKILL.md'), '--provider', 'anthropic'],
commandPath: 'pi',
operationId: 'op-pi',
resumeSessionId: 'prev_sess',
@@ -4689,8 +4688,8 @@ describe('HeterogeneousAgentCtr', () => {
await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId: first.sessionId });
await ctr.stopSession({ sessionId: first.sessionId });
- // Turn 2: resumes with the native id captured on turn 1 β†’ the pool
- // returns the SAME PiRpcSession instead of constructing a new one.
+ expect(piRpcSessionRunMock.mock.calls[0][1]).toEqual({ text: 'first' });
+ // Resume must reuse the same process and keep the next user turn clean.
const second = await ctr.startSession({
agentType: 'pi',
command: 'pi',
@@ -4701,6 +4700,7 @@ describe('HeterogeneousAgentCtr', () => {
await ctr.stopSession({ sessionId: second.sessionId });
expect(piRpcSessionConstructMock).toHaveBeenCalledTimes(1);
+ expect(piRpcSessionRunMock.mock.calls[1][1]).toEqual({ text: 'second' });
expect(piRpcSessionConstructMock.mock.calls[0][0].shellOperationId).toBe('op-1');
expect(piRpcSessionRebindMock.mock.calls[0][0].shellOperationId).toBe('op-2');
expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', {
diff --git a/packages/heterogeneous-agents/src/rpc/index.ts b/packages/heterogeneous-agents/src/rpc/index.ts
index a1c95a1aaa7..96c0338f346 100644
--- a/packages/heterogeneous-agents/src/rpc/index.ts
+++ b/packages/heterogeneous-agents/src/rpc/index.ts
@@ -38,4 +38,5 @@ export {
type PiRpcSessionCallbacks,
type PiRpcSessionOptions,
} from './piRpcSession';
+export { preparePiRpcInput } from './preparePiRpcInput';
export { RpcStdioClient, RpcStdioConnectionError } from './rpcStdioClient';
diff --git a/packages/heterogeneous-agents/src/rpc/preparePiRpcInput.test.ts b/packages/heterogeneous-agents/src/rpc/preparePiRpcInput.test.ts
new file mode 100644
index 00000000000..0f7cc23b8dd
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/preparePiRpcInput.test.ts
@@ -0,0 +1,103 @@
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { buildHeterogeneousPrompt } from '../protocol';
+import { lobeHubCliGuide, lobeHubCliSkillBody } from '../protocol/lobeHubCliGuide';
+import * as cliPlugin from '../spawn/lobeHubCliPlugin';
+import { preparePiRpcInput } from './preparePiRpcInput';
+
+const options = { args: ['--model', 'test-model'], lobeHubContext: true };
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('preparePiRpcInput', () => {
+ it('delivers the guide as a native skill, not as the first user message', async () => {
+ const input = buildHeterogeneousPrompt({ isNewSession: true, prompt: 'δ½ ε₯½' });
+ const result = await preparePiRpcInput(input, options);
+
+ expect(result.prompt).toEqual({ text: 'δ½ ε₯½' });
+ expect(result.args).toEqual(['--skill', expect.any(String), ...options.args]);
+ const skill = await readFile(result.args[1], 'utf8');
+ expect(path.basename(result.args[1])).toBe('SKILL.md');
+ expect(skill).toContain(lobeHubCliSkillBody);
+ expect(skill).toContain('Not needed for ordinary work on local files or other tools.');
+ expect(input.some((block) => block.type === 'text' && block.text === lobeHubCliGuide)).toBe(
+ true,
+ );
+ });
+
+ it('loads the same skill on resume and when discovery is disabled', async () => {
+ const first = await preparePiRpcInput(
+ buildHeterogeneousPrompt({ isNewSession: true, prompt: 'first' }),
+ options,
+ );
+ const resumed = await preparePiRpcInput(
+ buildHeterogeneousPrompt({ isNewSession: false, prompt: 'next' }),
+ { ...options, args: ['--no-skills'] },
+ );
+
+ expect(resumed.args).toEqual(['--skill', first.args[1], '--no-skills']);
+ expect(resumed.prompt).toEqual({ text: 'next' });
+ });
+
+ it('preserves system context, referenced topics and image content', async () => {
+ const blocks = buildHeterogeneousPrompt({
+ isNewSession: true,
+ prompt: '<refer_topic id="tpc_test" /> Summarize this',
+ systemContext: 'Selected source text',
+ });
+ const result = await preparePiRpcInput(
+ [
+ ...blocks,
+ { type: 'image', source: { type: 'base64', data: 'aGVsbG8=', mediaType: 'image/png' } },
+ ],
+ options,
+ );
+
+ expect(result.prompt.text).toContain('Selected source text');
+ expect(result.prompt.text).toContain('lh topic view');
+ expect(result.prompt.text).toContain('<refer_topic id="tpc_test" /> Summarize this');
+ expect(result.prompt.text).not.toContain(lobeHubCliGuide);
+ expect(result.prompt.images).toEqual([
+ { data: 'aGVsbG8=', mimeType: 'image/png', type: 'image' },
+ ]);
+ });
+
+ it('leaves ordinary terminal runs and user-authored guide text untouched', async () => {
+ const resolve = vi.spyOn(cliPlugin, 'resolveLobeHubCliPluginDir');
+ const standalone = await preparePiRpcInput('hello', {
+ args: options.args,
+ lobeHubContext: false,
+ });
+ expect(standalone).toEqual({ args: options.args, prompt: { text: 'hello' } });
+ expect(resolve).not.toHaveBeenCalled();
+
+ for (const input of [lobeHubCliGuide, [{ type: 'text' as const, text: lobeHubCliGuide }]]) {
+ expect((await preparePiRpcInput(input, options)).prompt.text).toBe(lobeHubCliGuide);
+ }
+ });
+
+ it.each([true, false])(
+ 'fails explicitly without a safe skill directory (new session: %s)',
+ async (isNewSession) => {
+ vi.spyOn(cliPlugin, 'resolveLobeHubCliPluginDir').mockResolvedValue(undefined);
+ await expect(
+ preparePiRpcInput(buildHeterogeneousPrompt({ isNewSession, prompt: 'work' }), options),
+ ).rejects.toThrow('Cannot prepare the LobeHub skill for Pi');
+ },
+ );
+
+ it('fails on unreadable attachments instead of silently dropping them', async () => {
+ await expect(
+ preparePiRpcInput(
+ [
+ { type: 'text', text: 'describe this' },
+ { type: 'image', source: { type: 'path', path: '/nonexistent-pi-test-image.png' } },
+ ],
+ options,
+ ),
+ ).rejects.toThrow();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/rpc/preparePiRpcInput.ts b/packages/heterogeneous-agents/src/rpc/preparePiRpcInput.ts
new file mode 100644
index 00000000000..fe9bfcba60e
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/preparePiRpcInput.ts
@@ -0,0 +1,42 @@
+import path from 'node:path';
+
+import type { AgentPromptInput } from '../protocol';
+import {
+ LOBEHUB_CLI_SKILL_NAME,
+ omitLobeHubCliGuide,
+ resolveLobeHubCliPluginDir,
+} from '../spawn/lobeHubCliPlugin';
+import { toPiRpcPrompt } from './piRpcAgentHandle';
+
+export interface PreparePiRpcInputOptions {
+ args: string[];
+ cacheDir?: string;
+ lobeHubContext: boolean;
+}
+
+/** Prepare both launch arguments and prompt before either host flattens away context tags. */
+export const preparePiRpcInput = async (
+ input: AgentPromptInput,
+ options: PreparePiRpcInputOptions,
+) => {
+ let args = options.args;
+ let prompt = input;
+
+ if (options.lobeHubContext) {
+ // Reuse the private, content-addressed portable SKILL.md. Pi loads only
+ // that file, not the accompanying Claude Code plugin manifest.
+ const pluginDir = await resolveLobeHubCliPluginDir();
+ if (!pluginDir) {
+ throw new Error(
+ 'Cannot prepare the LobeHub skill for Pi. Check access to the temporary and user cache directories, then retry.',
+ );
+ }
+ const skillPath = path.join(pluginDir, 'skills', LOBEHUB_CLI_SKILL_NAME, 'SKILL.md');
+ // Explicit skills also load with --no-skills, including on resume. The
+ // content-addressed path must stay in the desktop pool's spawn fingerprint.
+ args = ['--skill', skillPath, ...args];
+ prompt = omitLobeHubCliGuide(input);
+ }
+
+ return { args, prompt: await toPiRpcPrompt(prompt, options) };
+};