π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(hetero): introduce the LobeHub CLI to an external agent once per session (#19712)
Arvin Xub0874876cda3
diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.tsindex 49e85cc14e1..fbb38ba6cf1 100644--- a/apps/cli/src/device/agentRun.test.ts+++ b/apps/cli/src/device/agentRun.test.ts@@ -2,7 +2,10 @@ import { EventEmitter } from 'node:events';import { statSync } from 'node:fs';import os from 'node:os';-import { HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV } from '@lobechat/heterogeneous-agents/protocol';+import {+ HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,+ lobeHubCliGuide,+} from '@lobechat/heterogeneous-agents/protocol';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { spawnHeteroAgentRun } from './agentRun';@@ -116,7 +119,12 @@ describe('spawnHeteroAgentRun', () => {child.emit('spawn');await expect(ackPromise).resolves.toEqual({ status: 'accepted' });- expect(child.stdin.write).toHaveBeenCalledWith(JSON.stringify('hi'));+ expect(child.stdin.write).toHaveBeenCalledWith(+ JSON.stringify([+ { text: lobeHubCliGuide, type: 'text' },+ { text: 'hi', type: 'text' },+ ]),+ );expect(child.stdin.end).toHaveBeenCalledTimes(1);});@@ -153,7 +161,12 @@ describe('spawnHeteroAgentRun', () => {child.emit('spawn');await expect(ackPromise).resolves.toEqual({ status: 'accepted' });- expect(child.stdin.write).toHaveBeenCalledWith(JSON.stringify('hi'));+ expect(child.stdin.write).toHaveBeenCalledWith(+ JSON.stringify([+ { text: lobeHubCliGuide, type: 'text' },+ { text: 'hi', type: 'text' },+ ]),+ );});it('rejects when the wrapper process still fails to spawn from the fallback cwd', async () => {@@ -227,6 +240,7 @@ describe('spawnHeteroAgentRun', () => {expect(child.stdin.write).toHaveBeenCalledWith(JSON.stringify([{ text: 'workspace rules', type: 'text' },+ { text: lobeHubCliGuide, type: 'text' },{ text: 'do it', type: 'text' },]),);@@ -254,12 +268,27 @@ describe('spawnHeteroAgentRun', () => {],resumeFallback: [{ text: 'workspace rules\n\nprevious conversation', type: 'text' },+ // Resuming, so the primary prompt above skips the CLI introduction the+ // first turn already delivered β but the fallback starts a fresh+ // session, which has to be told again.+ { text: lobeHubCliGuide, type: 'text' },{ text: 'continue', type: 'text' },],}),);});+ it('skips the CLI introduction when it resumes an existing session', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);++ const ackPromise = spawnHeteroAgentRun({ ...baseParams, resumeSessionId: 'session-1' });+ child.emit('spawn');+ await ackPromise;++ expect(child.stdin.write).toHaveBeenCalledWith(JSON.stringify('hi'));+ });+it('appends image blocks to stdin when imageList is provided', async () => {const child = makeFakeChild();spawnMock.mockReturnValue(child);@@ -274,6 +303,7 @@ describe('spawnHeteroAgentRun', () => {expect(child.stdin.write).toHaveBeenCalledWith(JSON.stringify([+ { text: lobeHubCliGuide, type: 'text' },{ text: 'look at this', type: 'text' },{ source: { id: 'file-1', type: 'url', url: 'https://signed/a.png' }, type: 'image' },]),diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex f8acb597c33..a9260927a9b 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -110,6 +110,7 @@ export function spawnHeteroAgentRun(// coerceJsonPrompt.const stdinPayload = buildHeteroExecStdinPayload({imageList,+ isNewSession: !resumeSessionId,prompt,resumeFallbackSystemContext,systemContext,diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 1136c3676f7..e12adba5f14 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -437,6 +437,13 @@ interface AgentSession {serverOperationToken?: string;sessionId: string;traeAcpSession?: TraeAcpSession;+ /**+ * Set when this turn had to rebuild a garbage-collected Claude Code+ * transcript before resuming it. The rebuild is assembled from persisted+ * chat rows, which never carried the session-scoped prompt context, so the+ * resumed transcript has not seen it even though the session id survives.+ */+ transcriptRebuiltForResume?: boolean;useClaudeCodeSdk?: boolean;useCodexAppServer?: boolean;verifiedModel?: string;@@ -1457,6 +1464,22 @@ export default class HeterogeneousAgentCtr {return path.join(this.app.appStoragePath, FILE_CACHE_DIR);}+ /**+ * Whether this prompt reaches a CLI transcript that has never seen the+ * session-scoped context (the `lh` guide), and therefore has to carry it.+ *+ * Two ways that happens. A client-mode session is created per turn with the+ * previous turn's id in `resumeSessionId`, so its absence is exactly+ * "nothing to continue": the first turn of a topic, or the resume-recovery+ * retry the renderer re-dispatches with `resumeSessionId` cleared after a+ * stale session id. And a transcript this turn rebuilt from persisted chat+ * rows resumes under the original session id while containing none of the+ * context that session was given β the rows never carried it.+ */+ private needsSessionIntroduction(session: AgentSession): boolean {+ return !session.resumeSessionId || session.transcriptRebuiltForResume === true;+ }+/*** Build a Claude Code stream-json user message with text + base64 images.* Semantic context is assembled by the shared prompt engine before the@@ -1466,8 +1489,14 @@ export default class HeterogeneousAgentCtr {prompt: string,imageList: HeterogeneousAgentImageAttachment[] = [],systemContext?: string,+ isNewSession?: boolean,): Promise<string> {- const promptInput = buildHeterogeneousPrompt({ imageList, prompt, systemContext });+ const promptInput = buildHeterogeneousPrompt({+ imageList,+ isNewSession,+ prompt,+ systemContext,+ });const plan = await buildAgentInput('claude-code', promptInput, {cacheDir: this.fileCacheDir,});@@ -1661,11 +1690,16 @@ export default class HeterogeneousAgentCtr {messages: params.resumeReplayMessages,sessionId: session.agentSessionId,});- if (ensured.written)+ if (ensured.written) {+ // The rebuilt transcript is made of persisted chat rows only, so+ // whatever session-scoped context the original session was given is+ // not in it β this turn has to introduce itself again.+ session.transcriptRebuiltForResume = true;logger.info('Rebuilt GC-ed Claude Code transcript for resume:', {path: ensured.path,turns: params.resumeReplayMessages.length,});+ }} catch (error) {// Never block the run on this β worst case CC starts a fresh session.logger.warn('Failed to rebuild Claude Code resume transcript:', error);@@ -1704,6 +1738,7 @@ export default class HeterogeneousAgentCtr {const driver = getHeterogeneousAgentDriver(session.agentType);const promptInput = buildHeterogeneousPrompt({imageList: params.imageList,+ isNewSession: this.needsSessionIntroduction(session),prompt: params.prompt,systemContext: params.systemContext,});@@ -1860,6 +1895,7 @@ export default class HeterogeneousAgentCtr {params.prompt,params.imageList ?? [],params.systemContext,+ this.needsSessionIntroduction(session),);const traceSession = await this.createCliTraceSession({cliArgs: ['sdk-stream', ...session.args],@@ -1958,6 +1994,7 @@ export default class HeterogeneousAgentCtr {const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);const promptInput = buildHeterogeneousPrompt({imageList: params.imageList,+ isNewSession: this.needsSessionIntroduction(session),prompt: params.prompt,systemContext: params.systemContext,});@@ -2150,6 +2187,7 @@ export default class HeterogeneousAgentCtr {const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);const promptInput = buildHeterogeneousPrompt({imageList: params.imageList,+ isNewSession: this.needsSessionIntroduction(session),prompt: params.prompt,systemContext: params.systemContext,});@@ -2259,6 +2297,7 @@ export default class HeterogeneousAgentCtr {const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);const promptInput = buildHeterogeneousPrompt({imageList: params.imageList,+ isNewSession: this.needsSessionIntroduction(session),prompt: params.prompt,systemContext: params.systemContext,});@@ -2333,6 +2372,7 @@ export default class HeterogeneousAgentCtr {const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);const promptInput = buildHeterogeneousPrompt({imageList: params.imageList,+ isNewSession: this.needsSessionIntroduction(session),prompt: params.prompt,systemContext: params.systemContext,});@@ -2440,6 +2480,7 @@ export default class HeterogeneousAgentCtr {const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);const promptInput = buildHeterogeneousPrompt({imageList: params.imageList,+ isNewSession: this.needsSessionIntroduction(session),prompt: params.prompt,systemContext: params.systemContext,});@@ -2584,6 +2625,7 @@ export default class HeterogeneousAgentCtr {const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);const promptInput = buildHeterogeneousPrompt({imageList: params.imageList,+ isNewSession: this.needsSessionIntroduction(session),prompt: params.prompt,systemContext: params.systemContext,});@@ -2699,6 +2741,7 @@ export default class HeterogeneousAgentCtr {// Text + base64 images for the RPC `prompt` command (no `@path` temp files).const promptBlocks = buildHeterogeneousPrompt({imageList: params.imageList,+ isNewSession: this.needsSessionIntroduction(session),prompt: params.prompt,systemContext: params.systemContext,});@@ -3722,6 +3765,7 @@ export default class HeterogeneousAgentCtr {const stdinPayload = buildHeteroExecStdinPayload({imageList,+ isNewSession: !resumeSessionId,prompt,resumeFallbackSystemContext,systemContext,diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 503f23b9eab..96febe2e6cc 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -7,7 +7,10 @@ import { PassThrough } from 'node:stream';import type { CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';-import { HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV } from '@lobechat/heterogeneous-agents/protocol';+import {+ HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,+ lobeHubCliGuide,+} from '@lobechat/heterogeneous-agents/protocol';import { AcpRpcResponseError } from '@lobechat/heterogeneous-agents/spawn';// `electron` is mocked below; this binding is the mock object so tests can// flip `isPackaged` to exercise the packaged-build tracing gate.@@ -16,6 +19,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import HeterogeneousAgentCtr, { redactPromptArgs } from '../HeterogeneousAgentImpl';+/**+ * Every prompt that opens a fresh CLI session leads with the `lh` introduction;+ * a resumed one (`startSession({ resumeSessionId })`) does not.+ */+const cliGuideBlock = { text: lobeHubCliGuide, type: 'text' };+vi.mock('node:os', async () => {const actual = await vi.importActual<typeof os>('node:os');return { ...actual, platform: vi.fn(() => 'linux') };@@ -206,6 +215,10 @@ const {piRpcSessionRunMock: vi.fn(),}));+const { ensureResumeTranscriptMock } = vi.hoisted(() => ({+ ensureResumeTranscriptMock: vi.fn(async () => ({ path: '', written: false })),+}));+vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {const actual = await importOriginal<Record<string, unknown>>();@@ -543,6 +556,7 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {return {...actual,+ ensureClaudeCodeResumeTranscript: ensureResumeTranscriptMock,ClaudeAgentSdkSession: MockClaudeAgentSdkSession,CodexAppServerClient: MockCodexAppServerClient,CodexThreadSession: MockCodexThreadSession,@@ -1252,13 +1266,42 @@ describe('HeterogeneousAgentCtr', () => {const msg = JSON.parse(line);expect(msg).toMatchObject({message: {- content: [{ text: prompt, type: 'text' }],+ content: [cliGuideBlock, { text: prompt, type: 'text' }],role: 'user',},type: 'user',});});+ it('re-introduces the CLI when this turn rebuilt a garbage-collected transcript', async () => {+ // `--resume` keeps working because the transcript was rebuilt, so the+ // session id survives β but the rebuild is made of persisted chat rows,+ // which never carried the introduction the original session was given.+ ensureResumeTranscriptMock.mockResolvedValueOnce({ path: '/tmp/t.jsonl', written: true });++ const { writes } = await runSendPrompt(+ 'carry on',+ { cwd: '/work/dir', resumeSessionId: 'sess-gc' },+ [],+ { resumeReplayMessages: [{ content: 'earlier', role: 'user' }] } as any,+ );++ const msg = JSON.parse(writes[0].trimEnd());+ expect(msg.message.content).toEqual([cliGuideBlock, { text: 'carry on', type: 'text' }]);+ });++ it('does not re-introduce the CLI when the transcript did not need rebuilding', async () => {+ const { writes } = await runSendPrompt(+ 'carry on',+ { cwd: '/work/dir', resumeSessionId: 'sess-live' },+ [],+ { resumeReplayMessages: [{ content: 'earlier', role: 'user' }] } as any,+ );++ const msg = JSON.parse(writes[0].trimEnd());+ expect(msg.message.content).toEqual([{ text: 'carry on', type: 'text' }]);+ });+it('places system context before the user prompt in stream-json content blocks', async () => {const { writes } = await runSendPrompt('user task', {}, [], {systemContext: 'selected code context',@@ -1268,6 +1311,7 @@ describe('HeterogeneousAgentCtr', () => {const msg = JSON.parse(writes[0].trimEnd());expect(msg.message.content).toEqual([{ text: 'selected code context', type: 'text' },+ cliGuideBlock,{ text: 'user task', type: 'text' },]);});@@ -1420,7 +1464,7 @@ describe('HeterogeneousAgentCtr', () => {expect(cliArgs).not.toContain(prompt);expect(writes).toHaveLength(1);const msg = JSON.parse(writes[0].trimEnd());- expect(msg.message.content[0].text).toBe(prompt);+ expect(msg.message.content.at(-1).text).toBe(prompt);});it('falls back to the user Desktop when no cwd is supplied', async () => {@@ -1449,6 +1493,7 @@ describe('HeterogeneousAgentCtr', () => {// Anthropic rejects `{ text: '', type: 'text' }` with// "messages: text content blocks must be non-empty".expect(msg.message.content).toEqual([+ cliGuideBlock,{source: { data: 'UE5HX1RFU1Q=', media_type: 'image/png', type: 'base64' },type: 'image',@@ -1957,6 +2002,7 @@ describe('HeterogeneousAgentCtr', () => {operationId: 'op-grok',prompt: [{ text: 'selected context', type: 'text' },+ cliGuideBlock,{ text: 'implement this', type: 'text' },],sessionId,@@ -2317,7 +2363,7 @@ describe('HeterogeneousAgentCtr', () => {'stream-json','--verbose','--prompt',- 'fresh private prompt',+ `${lobeHubCliGuide}\n\nfresh private prompt`,]);expect(spawnCalls[0].options.env).toEqual(expect.objectContaining({@@ -3099,7 +3145,7 @@ describe('HeterogeneousAgentCtr', () => {);expect(cliArgs).not.toContain('--full-auto');expect(cliArgs).not.toContain('-');- expect(writes).toEqual([prompt]);+ expect(writes).toEqual([`${lobeHubCliGuide}\n\n${prompt}`]);});it('uses Codex app-server lab instead of spawning codex exec', async () => {@@ -3143,7 +3189,7 @@ describe('HeterogeneousAgentCtr', () => {);expect(codexAppServerRunMock).toHaveBeenCalledWith(expect.objectContaining({- input: [{ text: 'stream this', text_elements: [], type: 'text' }],+ input: [{ text: `${lobeHubCliGuide}\n\nstream this`, text_elements: [], type: 'text' }],operationId: 'op-test',}),);@@ -3441,7 +3487,7 @@ describe('HeterogeneousAgentCtr', () => {systemContext: 'selected code context',});- expect(writes).toEqual(['selected code context\n\nuser task']);+ expect(writes).toEqual([`selected code context\n\n${lobeHubCliGuide}\n\nuser task`]);});it('materializes image attachments into local files and forwards them via --image', async () => {@@ -3471,7 +3517,7 @@ describe('HeterogeneousAgentCtr', () => {await expect(Promise.all(imagePaths.map((filePath) => readFile(filePath, 'utf8'))),).resolves.toEqual(['PNG_TEST', 'JPEG_TEST']);- expect(writes).toEqual(['describe these screenshots']);+ expect(writes).toEqual([`${lobeHubCliGuide}\n\ndescribe these screenshots`]);});it('normalizes parameterized image MIME types before choosing the CLI file extension', async () => {@@ -3599,7 +3645,9 @@ describe('HeterogeneousAgentCtr', () => {await expect(readFile(path.join(traceRoot, '.last-live-trace'), 'utf8')).resolves.toBe(`${traceDir}\n`,);- await expect(readFile(path.join(traceDir, 'stdin.txt'), 'utf8')).resolves.toBe(prompt);+ await expect(readFile(path.join(traceDir, 'stdin.txt'), 'utf8')).resolves.toBe(+ `${lobeHubCliGuide}\n\n${prompt}`,+ );await expect(readFile(path.join(traceDir, 'stdout.jsonl'), 'utf8')).resolves.toBe(rawLine);await expect(readFile(path.join(traceDir, 'stderr.log'), 'utf8')).resolves.toBe('');await expect(readFile(path.join(traceDir, 'exit.json'), 'utf8')).resolves.toContain(@@ -3613,7 +3661,7 @@ describe('HeterogeneousAgentCtr', () => {command: 'codex',cwd: appStoragePath,sessionId,- stdinBytes: Buffer.byteLength(prompt),+ stdinBytes: Buffer.byteLength(`${lobeHubCliGuide}\n\n${prompt}`),stdoutFile: 'stdout.jsonl',});expect(meta.args).not.toContain('-');@@ -4648,6 +4696,9 @@ describe('HeterogeneousAgentCtr', () => {],resumeFallback: [{ text: 'workspace rules\n\nprevious conversation', type: 'text' },+ // Native resume failed, so the retry opens a session that has never+ // seen the introduction the first turn delivered.+ cliGuideBlock,{ text: 'inspect the repository', type: 'text' },],}),diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.tsindex 34656f40f44..0c3d2d79e48 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts@@ -1,7 +1,15 @@+import { lobeHubCliGuide } from '@lobechat/heterogeneous-agents/protocol';import { beforeEach, describe, expect, it, vi } from 'vitest';import { spawnHeteroSandbox } from '../sandboxRunner';+/** The prompt rides into the sandbox base64-encoded β decode it back out. */+const decodeStdinPayload = (command: string): string => {+ const encoded = command.match(/^echo '([^']+)' \| base64 -d/)?.[1];+ if (!encoded) throw new Error(`No base64 stdin payload in command: ${command}`);+ return Buffer.from(encoded, 'base64').toString('utf8');+};+const { mockCallTool } = vi.hoisted(() => ({mockCallTool: vi.fn().mockResolvedValue({ success: true }),}));@@ -62,6 +70,41 @@ describe('spawnHeteroSandbox', () => {expect(command).not.toContain('"$(touch /tmp/pwned)"');});+ it('introduces the LobeHub CLI to a run that starts a new session', async () => {+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ assistantMessageId: 'msg-1',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ const payload = JSON.parse(decodeStdinPayload(mockCallTool.mock.calls[0][1].command));+ expect(payload).toEqual([+ { text: lobeHubCliGuide, type: 'text' },+ { text: 'hi', type: 'text' },+ ]);+ });++ it('does not repeat the CLI introduction on a resumed session', async () => {+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ assistantMessageId: 'msg-1',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ resumeSessionId: 'session-1',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(JSON.parse(decodeStdinPayload(mockCallTool.mock.calls[0][1].command))).toBe('hi');+ });+it('injects LOBEHUB_WORKSPACE_ID when the topic belongs to a workspace', async () => {await spawnHeteroSandbox({agentType: 'claude-code',diff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.tsindex f2fd1369c5a..e6aca1684e6 100644--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts@@ -187,6 +187,7 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<void// changes required.const stdinPayload = buildHeteroExecStdinPayload({imageList: params.imageList,+ isNewSession: !resumeSessionId,prompt,resumeFallbackSystemContext: params.resumeFallbackSystemContext,systemContext: params.systemContext,diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.tsindex 52999c55528..f4d9b764d23 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import { buildHeteroExecStdinPayload } from './execStdinPayload';+import { lobeHubCliGuide } from './lobeHubCliGuide';describe('buildHeteroExecStdinPayload', () => {it('returns a plain JSON string when no systemContext or images', () => {@@ -63,6 +64,9 @@ describe('buildHeteroExecStdinPayload', () => {text: 'workspace rules\n\n<previous_conversation>history</previous_conversation>',type: 'text',},+ // The fallback exists because native resume failed: the CLI is about to+ // start a brand-new session that has never been told about `lh`.+ { text: lobeHubCliGuide, type: 'text' },{ text: 'continue', type: 'text' },{ source: { id: 'file-1', type: 'url', url: 'https://x/a.png' }, type: 'image' },],@@ -72,6 +76,23 @@ describe('buildHeteroExecStdinPayload', () => {expect(parsed.content[0].text).not.toContain('<previous_conversation>');});+ it('introduces the LobeHub CLI when the run opens a new session', () => {+ const payload = buildHeteroExecStdinPayload({ isNewSession: true, prompt: 'hello' });++ expect(JSON.parse(payload)).toEqual([+ { text: lobeHubCliGuide, type: 'text' },+ { text: 'hello', type: 'text' },+ ]);+ });++ it('leaves the CLI introduction out of a resumed session', () => {+ const payload = buildHeteroExecStdinPayload({ isNewSession: false, prompt: 'hello' });++ // The first turn's copy is still in the CLI's native transcript β repeating+ // it every turn would stack duplicates for the life of the conversation.+ expect(payload).toBe(JSON.stringify('hello'));+ });+it('treats an empty imageList like no images', () => {const payload = buildHeteroExecStdinPayload({ imageList: [], prompt: 'hello' });expect(payload).toBe(JSON.stringify('hello'));diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.tsindex a7b0db1770c..f0ecf1f0398 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts@@ -27,21 +27,34 @@ export interface HeteroExecImageRef {* compatible `{ content, resumeFallback }` envelope: old CLIs unwrap `content`* and run the primary prompt, while new CLIs reserve `resumeFallback` for a* retry after native resume fails.+ *+ * `isNewSession` is the caller's own `!resumeSessionId`. The fallback prompt is+ * always a new session by definition β it exists precisely because native+ * resume failed and the CLI is starting the agent from scratch β so it carries+ * session-scoped context regardless of what the primary attempt got.*/export const buildHeteroExecStdinPayload = (params: {imageList?: HeteroExecImageRef[];+ isNewSession?: boolean;prompt: string;resumeFallbackSystemContext?: string;systemContext?: string;}): string => {- const { imageList = [], prompt, resumeFallbackSystemContext, systemContext } = params;- const blocks = buildHeterogeneousPrompt({ imageList, prompt, systemContext });+ const {+ imageList = [],+ isNewSession,+ prompt,+ resumeFallbackSystemContext,+ systemContext,+ } = params;+ const blocks = buildHeterogeneousPrompt({ imageList, isNewSession, prompt, systemContext });if (resumeFallbackSystemContext !== undefined) {return JSON.stringify({content: blocks,resumeFallback: buildHeterogeneousPrompt({imageList,+ isNewSession: true,prompt,systemContext: resumeFallbackSystemContext,}),diff --git a/packages/heterogeneous-agents/src/protocol/index.ts b/packages/heterogeneous-agents/src/protocol/index.tsindex f44bb5411d8..341873c5f05 100644--- a/packages/heterogeneous-agents/src/protocol/index.ts+++ b/packages/heterogeneous-agents/src/protocol/index.ts@@ -12,6 +12,7 @@ export type {HeterogeneousAgentCancellationSignal,} from './cancellation';export { buildHeteroExecStdinPayload, type HeteroExecImageRef } from './execStdinPayload';+export { lobeHubCliGuide } from './lobeHubCliGuide';export const HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV = 'LOBEHUB_HETERO_EXEC_INHERIT_PROCESS_GROUP';export {buildHeterogeneousPrompt,diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.tsnew file mode 100644index 00000000000..9b47420f295--- /dev/null+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts@@ -0,0 +1,48 @@+/**+ * What an external CLI agent (Claude Code, Codex, Kimiβ¦) is told about `lh`,+ * the LobeHub CLI, at the start of a session.+ *+ * Those agents reach LobeHub the same way a human operator does β by running+ * `lh` in their own shell β but nothing in their native context mentions that+ * the binary exists, is already authenticated, or that the conversation they+ * are answering inside is addressable. So they fall back to what they can see:+ * the working directory. This block closes that gap once per session.+ *+ * Deliberately a capability map, not a manual. Exact flags come from+ * `lh man <command>`, which renders the installed CLI's own command tree and+ * therefore cannot drift from the version actually on this machine; a+ * hand-copied flag list here would. The homogeneous runtime gets the same+ * material as a loadable skill (`@lobechat/builtin-skills`'s `lobehub` skill)+ * β hetero agents have no skill loader, hence the inlined summary.+ *+ * Two things it deliberately does NOT promise, because they are not true on+ * every transport:+ *+ * - **Credentials.** The cloud sandbox is handed a user-scoped JWT, and a+ * desktop client-mode run inherits the machine's own `lh login`. But the+ * device-dispatch paths (desktop gateway, `lh connect`) put the run's narrow+ * `hetero-operation` token in `LOBEHUB_JWT`, and `oidcAuth` rejects that+ * token on every user-scoped endpoint β so `lh doc`/`lh kb`/β¦ would 401+ * while the CLI prefers it over the saved login. Until the nested CLI gets+ * its own user credential there, the guide states the fallback the agent can+ * apply itself rather than claiming it is signed in. That fallback is phrased+ * as "clear the variable", not `env -u`: devices run Windows too, and+ * `pickAuthSource` only tests `LOBEHUB_JWT` for truthiness, so an empty value+ * falls through to the stored login in every shell.+ * - **`LOBEHUB_AGENT_ID`.** Only the desktop client-mode path sets it+ * (`buildLobeHubSessionEnv`); `lh hetero exec` re-exports just the operation+ * and topic ids, and the `lh connect` daemon strips any ambient agent id so a+ * dispatched run cannot inherit its launcher's identity.+ */+export const lobeHubCliGuide = [+ '## LobeHub CLI (`lh`)',+ '',+ "You are running inside a LobeHub conversation, on a machine where the `lh` CLI is already installed and the run normally carries the user's credentials in its environment β never install it, and never run `lh login`.",+ '',+ '- **You already know where you are.** `LOBEHUB_TOPIC_ID` (this conversation) and `LOBEHUB_OPERATION_ID` (this run) are in your environment, and `LOBEHUB_AGENT_ID` (you) is too whenever the run carries one. They are ordinary environment variables, so every sub-shell, script or tool you spawn inherits them. Pass them straight to commands rather than listing agents or topics to find yourself; if the one you need is empty, say so instead of guessing an id.',+ '- **Look commands up, do not guess them.** `lh man <command>` (e.g. `lh man doc create`) prints the manual for the CLI actually installed here, including exactly which flags that command takes. Many commands offer `--json` for structured output, but not all of them β the manual is what says so, and an invented flag just fails the call.',+ '- **What it reaches:** `lh kb` knowledge bases Β· `lh doc` documents Β· `lh file` files Β· `lh artifact` artifacts Β· `lh topic` / `lh message` past conversations Β· `lh agent` agents Β· `lh task` / `lh project` work Β· `lh search` local resources and the web Β· `lh gen` text/image/video/TTS/ASR generation Β· `lh memory` user memory Β· `lh notify` notifications to the user Β· `lh model` / `lh provider` / `lh plugin` / `lh skill` platform configuration Β· `lh bot` chat-platform bots.',+ '- **When to use it:** whenever the user asks for something that lives in LobeHub rather than in this working directory β saving a document, recalling an earlier conversation, generating an image, or changing your own agent configuration. Say what you did and where it landed.',+ "- **If a command comes back with an authentication or permission error**, clear `LOBEHUB_JWT` and retry it once β some runs carry a narrow token scoped to this conversation, which shadows the machine's own login. An empty value is enough, so use whichever form your shell takes: `LOBEHUB_JWT= lh β¦` (sh/bash/zsh), `$env:LOBEHUB_JWT=''; lh β¦` (PowerShell), `set LOBEHUB_JWT=` then `lh β¦` (cmd). If it still fails, tell the user what you were trying to do β do not work around it.",+ '- **Leave these alone:** `lh hetero` and `lh connect` run the infrastructure that is executing you. And never change the persistent workspace scope with `lh workspace use` β it silently rewrites the target of every later command in this session.',+].join('\n');diff --git a/packages/heterogeneous-agents/src/protocol/promptEngine.test.ts b/packages/heterogeneous-agents/src/protocol/promptEngine.test.tsindex c2f8e94ef36..751f53bcdad 100644--- a/packages/heterogeneous-agents/src/protocol/promptEngine.test.ts+++ b/packages/heterogeneous-agents/src/protocol/promptEngine.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';+import { lobeHubCliGuide } from './lobeHubCliGuide';import { buildHeterogeneousPrompt, HeterogeneousPromptEngine } from './promptEngine';describe('HeterogeneousPromptEngine', () => {@@ -33,6 +34,39 @@ describe('HeterogeneousPromptEngine', () => {]);});+ it('introduces the LobeHub CLI once, when the session is new', () => {+ const blocks = buildHeterogeneousPrompt({+ isNewSession: true,+ prompt: 'Draft a doc',+ systemContext: 'Workspace context',+ });++ expect(blocks).toEqual([+ { text: 'Workspace context', type: 'text' },+ { text: lobeHubCliGuide, type: 'text' },+ { text: 'Draft a doc', type: 'text' },+ ]);+ });++ it('omits the LobeHub CLI introduction on a resumed session', () => {+ expect(buildHeterogeneousPrompt({ isNewSession: false, prompt: 'Draft a doc' })).toEqual([+ { text: 'Draft a doc', type: 'text' },+ ]);+ });++ it('tells a new session both how to reach the platform and how to read a referenced topic', () => {+ const blocks = buildHeterogeneousPrompt({+ isNewSession: true,+ prompt: '<refer_topic name="Previous" id="topic-ref" />\nSummarize it',+ });++ expect(blocks.map((block) => block.type === 'text' && block.text)).toEqual([+ lobeHubCliGuide,+ expect.stringContaining('`lh topic view <topic-id>`'),+ '<refer_topic name="Previous" id="topic-ref" />\nSummarize it',+ ]);+ });+it('recognizes markdown-escaped topic tags', () => {const blocks = buildHeterogeneousPrompt({prompt: '\\<refer\\_topic name="Previous" id="topic-ref" />',diff --git a/packages/heterogeneous-agents/src/protocol/promptEngine.ts b/packages/heterogeneous-agents/src/protocol/promptEngine.tsindex 07e02ed1aa9..9b65ced305a 100644--- a/packages/heterogeneous-agents/src/protocol/promptEngine.ts+++ b/packages/heterogeneous-agents/src/protocol/promptEngine.ts@@ -1,7 +1,28 @@+import { lobeHubCliGuide } from './lobeHubCliGuide';import type { AgentContentBlock, AgentImageBlock } from './types';export interface HeterogeneousPromptEngineInput {imageList?: HeterogeneousPromptImage[];+ /**+ * Whether this prompt opens a fresh agent session rather than continuing one+ * the CLI resumes natively. Dispatch sites derive it from their own resume+ * state (`!resumeSessionId`) β the engine cannot see it.+ *+ * Session-scoped context (the `lh` guide) is attached only when true: these+ * blocks are prepended to a USER message, so on a resumed session every+ * earlier turn's copy is still in the CLI's transcript. Re-sending it each+ * turn would stack duplicates for the whole life of the conversation.+ *+ * Rollout consequence, accepted deliberately: a conversation that already had+ * a CLI session before this shipped resumes into a transcript that never saw+ * the guide, and keeps resuming without it. Delivering it there needs+ * per-session "has this been delivered" state rather than this flag. The gap+ * self-heals whenever the native session does not survive β transcript GC+ * (30 days), a changed cwd, a recycled sandbox β because every one of those+ * falls back to a fresh session, and the resume-fallback prompt always+ * carries the guide.+ */+ isNewSession?: boolean;prompt: string;systemContext?: string;}@@ -28,7 +49,16 @@ const topicReferenceGuidanceProvider: HeterogeneousPromptContextProvider = {name: 'TopicReferenceGuidanceProvider',};-const defaultContextProviders = [topicReferenceGuidanceProvider];+/**+ * Teach the agent that the LobeHub platform is reachable from its own shell.+ * Session-scoped: see `isNewSession`.+ */+const lobeHubCliProvider: HeterogeneousPromptContextProvider = {+ getContext: ({ isNewSession }) => (isNewSession ? lobeHubCliGuide : undefined),+ name: 'LobeHubCliProvider',+};++const defaultContextProviders = [lobeHubCliProvider, topicReferenceGuidanceProvider];/*** Builds the semantic prompt shared by every heterogeneous-agent transport.