🤯 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): allow scoped operation-token topic reads (#21793)
AmAzing-d2aaee6b7d40
diff --git a/apps/cli/src/api/client.test.ts b/apps/cli/src/api/client.test.tsindex 92ac55659f5..75fee27dad6 100644--- a/apps/cli/src/api/client.test.ts+++ b/apps/cli/src/api/client.test.ts@@ -1,3 +1,4 @@+import type { Operation } from '@trpc/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as RefreshModule from '../auth/refresh';@@ -20,9 +21,9 @@ vi.mock('../settings', () => ({resolveServerUrl: () => 'https://app.lobehub.com',}));-const headersOfLastLink = () => {+const headersOfLastLink = (opts?: { op: Operation }) => {const { headers } = mockHttpLink.mock.calls.at(-1)![0] as any;- return typeof headers === 'function' ? headers() : headers;+ return typeof headers === 'function' ? headers(opts) : headers;};describe('api/client workspace scoping', () => {@@ -141,4 +142,47 @@ describe('api/client workspace scoping', () => {expect(scoped).toBe(scopedAgain);expect(scoped).not.toBe(personal);});++ it.each(['getTrpcClient', 'getToolsTrpcClient'] as const)(+ '%s preserves per-request fallback credentials and the run workspace',+ async (clientFactory) => {+ process.env.LOBEHUB_JWT = `e30.${Buffer.from(+ JSON.stringify({ purpose: 'hetero-operation', sub: 'user-1' }),+ ).toString('base64url')}.s`;+ process.env.LOBEHUB_WORKSPACE_ID = 'workspace-1';+ const clients = await import('./client');+ await clients[clientFactory]();++ expect(+ await headersOfLastLink({+ op: {+ context: { storedLogin: 'same-user-login' },+ id: 1,+ input: undefined,+ path: 'doc.list',+ type: 'query',+ },+ }),+ ).toEqual({ 'Oidc-Auth': 'same-user-login', 'X-Workspace-Id': 'workspace-1' });+ expect(await headersOfLastLink()).toEqual({+ 'Oidc-Auth': process.env.LOBEHUB_JWT,+ 'X-Workspace-Id': 'workspace-1',+ });+ },+ );++ // Only a device run's operation token is refused on user-scoped routes, so+ // only its clients get the stored-login fallback (see operationTokenFallback).+ it.each([+ ['an operation token', { purpose: 'hetero-operation', sub: 'user-1' }, 2],+ ['a user-scoped token', { purpose: 'cli-sandbox', sub: 'user-1' }, 1],+ ])('builds the fallback link only for %s', async (_label, payload, linkCount) => {+ process.env.LOBEHUB_JWT = `e30.${Buffer.from(JSON.stringify(payload)).toString('base64url')}.s`;+ const { getTrpcClient } = await import('./client');+ await getTrpcClient();++ const { links } = (mockCreateTRPCClient.mock.calls.at(-1) as any[])[0];+ expect(links).toHaveLength(linkCount);+ expect(await headersOfLastLink()).toMatchObject({ 'Oidc-Auth': process.env.LOBEHUB_JWT });+ });});diff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.tsindex 870c76ed908..e3204368326 100644--- a/apps/cli/src/api/client.ts+++ b/apps/cli/src/api/client.ts@@ -1,3 +1,4 @@+import type { Operation } from '@trpc/client';import { createTRPCClient, httpLink } from '@trpc/client';import superjson from 'superjson';@@ -11,6 +12,11 @@ import { CLI_PRIMARY_BIN } from '../constants/identity';import { cliPackageName } from '../pkg';import { resolveServerUrl } from '../settings';import { log } from '../utils/logger';+import {+ isOperationToken,+ operationTokenFallbackLink,+ operationTokenHeaders,+} from './operationTokenFallback';import { resolveWorkspaceId, withWorkspaceHeader } from './workspace';export type TrpcClient = ReturnType<typeof createTRPCClient<LambdaRouter>>;@@ -20,8 +26,14 @@ const PERSONAL_KEY = '__personal__';const _clients = new Map<string, TrpcClient>();const _toolsClients = new Map<string, ToolsTrpcClient>();+type AuthHeaders = (opts?: {+ op?: Operation;+}) => Record<string, string> | Promise<Record<string, string>>;+async function getAuthAndServer(): Promise<{- headers: () => Record<string, string> | Promise<Record<string, string>>;+ headers: AuthHeaders;+ /** Set when the credential is a run's operation token; see `operationTokenFallback`. */+ operationToken?: () => string;serverUrl: string;}> {// Precedence lives in `pickAuthSource`, shared with `resolveToken` and@@ -32,12 +44,14 @@ async function getAuthAndServer(): Promise<{if (source.kind === 'env-jwt') {const serverUrl = resolveServerUrl();- return {- // Read per request: `hetero exec` renews its operation token in place, and- // its clients live for the whole run.- headers: () => ({ 'Oidc-Auth': process.env.LOBEHUB_JWT || source.token! }),- serverUrl,- };+ // Read per request: `hetero exec` renews its operation token in place, and+ // its clients live for the whole run.+ const envToken = () => process.env.LOBEHUB_JWT || source.token!;+ if (isOperationToken(source.token)) {+ return { headers: operationTokenHeaders(envToken), operationToken: envToken, serverUrl };+ }++ return { headers: () => ({ 'Oidc-Auth': envToken() }), serverUrl };}if (source.kind === 'env-api-key') {@@ -82,11 +96,12 @@ export async function getTrpcClient(workspaceId?: string): Promise<TrpcClient> {const cached = _clients.get(cacheKey);if (cached) return cached;- const { headers, serverUrl } = await getAuthAndServer();+ const { headers, operationToken, serverUrl } = await getAuthAndServer();const client = createTRPCClient<LambdaRouter>({links: [+ ...(operationToken ? [operationTokenFallbackLink<LambdaRouter>(operationToken)] : []),httpLink({- headers: async () => withWorkspaceHeader(await headers(), wsId),+ headers: async (opts) => withWorkspaceHeader(await headers(opts), wsId),transformer: superjson,url: `${serverUrl}/trpc/lambda`,}),@@ -156,11 +171,12 @@ export async function getToolsTrpcClient(workspaceId?: string): Promise<ToolsTrpconst cached = _toolsClients.get(cacheKey);if (cached) return cached;- const { headers, serverUrl } = await getAuthAndServer();+ const { headers, operationToken, serverUrl } = await getAuthAndServer();const client = createTRPCClient<ToolsRouter>({links: [+ ...(operationToken ? [operationTokenFallbackLink<ToolsRouter>(operationToken)] : []),httpLink({- headers: async () => withWorkspaceHeader(await headers(), wsId),+ headers: async (opts) => withWorkspaceHeader(await headers(opts), wsId),transformer: superjson,url: `${serverUrl}/trpc/tools`,}),diff --git a/apps/cli/src/api/operationTokenFallback.test.ts b/apps/cli/src/api/operationTokenFallback.test.tsnew file mode 100644index 00000000000..a61504e4b15--- /dev/null+++ b/apps/cli/src/api/operationTokenFallback.test.ts@@ -0,0 +1,158 @@+import type { Operation, TRPCLink } from '@trpc/client';+import { createTRPCClient, TRPCClientError } from '@trpc/client';+import type { AnyRouter } from '@trpc/server';+import { observable } from '@trpc/server/observable';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as RefreshModule from '../auth/refresh';+import type { TokenLookup } from '../auth/refresh';+import { describeTokenLookup, getValidToken } from '../auth/refresh';+import { log } from '../utils/logger';+import {+ isOperationToken,+ OPERATION_TOKEN_REFUSAL,+ operationTokenFallbackLink,+ operationTokenHeaders,+} from './operationTokenFallback';++vi.mock('../auth/refresh', async (importOriginal) => ({+ ...(await importOriginal<typeof RefreshModule>()),+ getValidToken: vi.fn(),+}));+vi.mock('../utils/logger', () => ({ log: { debug: vi.fn(), warn: vi.fn() } }));++const jwt = (payload: Record<string, unknown>) =>+ `e30.${Buffer.from(JSON.stringify(payload)).toString('base64url')}.sig`;++const operationToken = jwt({ purpose: 'hetero-operation', sub: 'user-1' });+const storedLogin = (sub: string) =>+ vi.mocked(getValidToken).mockResolvedValue({+ credentials: { accessToken: jwt({ sub }) },+ status: 'ok',+ });++const trpcError = (message: string, code: string) =>+ new TRPCClientError(message, {+ result: { error: { code: -32_001, data: { code }, message } },+ } as any);++/**+ * A terminating link standing in for `httpLink`: it resolves the request's+ * headers the same way, then answers with whatever the server would.+ */+const serverLink =+ (respond: (authorization: string) => unknown): TRPCLink<AnyRouter> =>+ () =>+ ({ op }) =>+ observable((observer) => {+ const headers = operationTokenHeaders(() => operationToken)({ op: op as Operation });+ const outcome = respond(headers['Oidc-Auth']);+ if (outcome instanceof Error) observer.error(outcome as TRPCClientError<AnyRouter>);+ else {+ observer.next({ result: { data: outcome, type: 'data' } } as any);+ observer.complete();+ }+ });++const query = (respond: (authorization: string) => unknown) => {+ const client = createTRPCClient<AnyRouter>({+ links: [operationTokenFallbackLink(() => operationToken), serverLink(respond)],+ }) as any;+ return client.doc.list.query();+};++/** Refuses the operation token the way `oidcAuth` does; accepts anything else. */+const userScopedRoute = vi.fn((authorization: string) =>+ authorization === operationToken+ ? trpcError(OPERATION_TOKEN_REFUSAL, 'UNAUTHORIZED')+ : `served for ${authorization}`,+);++describe('operation token fallback', () => {+ beforeEach(() => {+ vi.mocked(getValidToken).mockReset();+ vi.mocked(log.warn).mockClear();+ userScopedRoute.mockClear();+ });++ it('recognises only server-minted operation tokens', () => {+ expect(isOperationToken(operationToken)).toBe(true);+ expect(isOperationToken(jwt({ purpose: 'cli-sandbox', sub: 'user-1' }))).toBe(false);+ expect(isOperationToken('not-a-jwt')).toBe(false);+ });++ it("retries a user-scoped request with the machine's login of the same account", async () => {+ storedLogin('user-1');++ await expect(query(userScopedRoute)).resolves.toBe(`served for ${jwt({ sub: 'user-1' })}`);+ expect(userScopedRoute).toHaveBeenCalledTimes(2);+ });++ it('keeps the operation token on endpoints that accept it', async () => {+ storedLogin('user-1');++ await expect(query(() => 'ingested')).resolves.toBe('ingested');+ expect(getValidToken).not.toHaveBeenCalled();+ });++ /**+ * A workspace device is reachable by every member, so the login saved on it+ * can be another member's. Borrowing it would act on that person's data.+ */+ it("never borrows another account's login, and says why", async () => {+ storedLogin('device-owner');++ await expect(query(userScopedRoute)).rejects.toThrow(OPERATION_TOKEN_REFUSAL);+ expect(userScopedRoute).toHaveBeenCalledTimes(1);+ expect(log.warn).toHaveBeenCalledWith(+ expect.stringContaining('no stored login of the same account'),+ );+ });++ it('fails as before when the machine has no login', async () => {+ vi.mocked(getValidToken).mockResolvedValue({ status: 'no-login' });++ await expect(query(userScopedRoute)).rejects.toThrow(OPERATION_TOKEN_REFUSAL);+ expect(userScopedRoute).toHaveBeenCalledTimes(1);+ });++ it.each([+ { detail: 'HTTP 502', status: 'unavailable' },+ { detail: 'invalid_client', status: 'refused' },+ { detail: 'invalid_grant', status: 'spent' },+ ] satisfies TokenLookup[])(+ 'explains a $status refresh failure without retrying',+ async (result) => {+ vi.mocked(getValidToken).mockResolvedValue(result);+ const report = describeTokenLookup(result)!;++ await expect(query(userScopedRoute)).rejects.toThrow(OPERATION_TOKEN_REFUSAL);+ expect(userScopedRoute).toHaveBeenCalledTimes(1);+ expect(log.warn).toHaveBeenCalledWith(`${report.detail} ${report.fix}`);+ expect(log.warn).not.toHaveBeenCalledWith(+ expect.stringContaining('no stored login of the same account'),+ );+ },+ );++ it('reports unexpected credential lookup errors instead of claiming there is no login', async () => {+ vi.mocked(getValidToken).mockRejectedValue(new Error('credential store unavailable'));++ await expect(query(userScopedRoute)).rejects.toThrow(OPERATION_TOKEN_REFUSAL);+ expect(userScopedRoute).toHaveBeenCalledTimes(1);+ expect(log.warn).toHaveBeenCalledWith(+ expect.stringContaining('Could not look up the stored login'),+ );+ expect(log.warn).not.toHaveBeenCalledWith(+ expect.stringContaining('no stored login of the same account'),+ );+ });++ it('does not retry other authentication errors', async () => {+ storedLogin('user-1');+ const expiredToken = vi.fn(() => trpcError('jwt expired', 'UNAUTHORIZED'));++ await expect(query(expiredToken)).rejects.toThrow('jwt expired');+ expect(expiredToken).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/cli/src/api/operationTokenFallback.ts b/apps/cli/src/api/operationTokenFallback.tsnew file mode 100644index 00000000000..75f56d341cf--- /dev/null+++ b/apps/cli/src/api/operationTokenFallback.ts@@ -0,0 +1,133 @@+import type { Operation, TRPCLink } from '@trpc/client';+import { isTRPCClientError } from '@trpc/client';+import type { AnyRouter } from '@trpc/server';+import { observable } from '@trpc/server/observable';++import { describeTokenLookup, getValidToken } from '../auth/refresh';+import { parseJwtPayload } from '../auth/source';+import { log } from '../utils/logger';++/**+ * Device-dispatched runs (desktop gateway, `lh connect`) carry the run's narrow+ * `hetero-operation` token in `LOBEHUB_JWT`. It is accepted by the operation+ * endpoints (`heteroIngest`, `goal.*Operation`, …) and refused by every+ * user-scoped one, while it still outranks the machine's stored login. So an+ * agent's `lh doc` / `lh kb` / … failed until the agent itself cleared the+ * variable — an instruction the `lh` guide had to teach, and one an agent then+ * applied to errors it did not fit.+ *+ * The refusal is a fixed `oidcAuth` answer, so the client recognises exactly it+ * and re-sends that one request with the stored login — but only when that+ * login is the same account the operation token was minted for. A workspace+ * device is reachable by every member, so the machine's login can belong to+ * someone other than the member whose run this is; borrowing it would read and+ * write that person's data. Everything else is unchanged: operation endpoints+ * keep the operation token, and the workspace header stays the run's own scope+ * (`LOBEHUB_WORKSPACE_ID` or personal) — which the manual fallback did not do,+ * since an empty `LOBEHUB_JWT` re-enables the terminal's persisted+ * `lh workspace use` scope.+ *+ * Reads with an operation-authenticated route need neither: `lh topic view`+ * tries `topic.getTopicTranscriptOperation` first (`commands/topic/readTranscript`).+ */++/** `oidcAuth`'s message when an operation token reaches a user-scoped route. */+export const OPERATION_TOKEN_REFUSAL = 'hetero-operation tokens are not accepted on this endpoint';++/** Operation-context key carrying the stored login on the request the link re-sends. */+const STORED_LOGIN = 'storedLogin';++export const isOperationToken = (token: string | undefined): boolean =>+ !!token && parseJwtPayload(token)?.purpose === 'hetero-operation';++const subjectOf = (token: string) => {+ const sub = parseJwtPayload(token)?.sub;+ return typeof sub === 'string' && sub ? sub : undefined;+};++export const isOperationTokenRefusal = (error: unknown): boolean =>+ isTRPCClientError(error) &&+ error.data?.code === 'UNAUTHORIZED' &&+ error.message === OPERATION_TOKEN_REFUSAL;++/**+ * The stored login, when it is usable and belongs to the operation token's own+ * account.+ */+const storedLoginFor = async (+ operationToken: string,+): Promise<{ token: string } | { warning: string }> => {+ const result = await getValidToken();+ if (result.status === 'ok') {+ const owner = subjectOf(operationToken);+ const stored = result.credentials.accessToken;+ if (owner && subjectOf(stored) === owner) return { token: stored };+ }++ const report = describeTokenLookup(result);+ return {+ warning: report+ ? `${report.detail} ${report.fix}`+ : "LOBEHUB_JWT is this run's operation token, which this endpoint refuses, and this machine has no stored login of the same account to use instead.",+ };+};++/**+ * Re-send a request whose operation token was refused, once, with the stored+ * login of the same account. Without one, say why instead of re-sending a+ * request that can only be refused again.+ */+export const operationTokenFallbackLink =+ <TRouter extends AnyRouter>(operationToken: () => string): TRPCLink<TRouter> =>+ () =>+ ({ next, op }) =>+ observable((observer) => {+ let closed = false;+ let subscription = next(op).subscribe({+ complete: () => observer.complete(),+ error: (error) => {+ if (op.context[STORED_LOGIN] || !isOperationTokenRefusal(error)) {+ observer.error(error);+ return;+ }+ void storedLoginFor(operationToken())+ .then((lookup) => {+ if (closed) return;+ if ('warning' in lookup) {+ log.warn(lookup.warning);+ observer.error(error);+ return;+ }+ log.debug(`${op.path}: operation token refused, retrying with the stored login`);+ subscription = next({+ ...op,+ context: { ...op.context, [STORED_LOGIN]: lookup.token },+ }).subscribe(observer);+ })+ .catch((lookupError: unknown) => {+ if (closed) return;+ log.warn(+ `Could not look up the stored login: ${lookupError instanceof Error ? lookupError.message : String(lookupError)}`,+ );+ observer.error(error);+ });+ },+ next: (value) => observer.next(value),+ });++ return () => {+ closed = true;+ subscription.unsubscribe();+ };+ });++/**+ * Auth headers for a client holding an operation token: the token itself, or+ * the stored login `operationTokenFallbackLink` attached to a re-sent request.+ */+export const operationTokenHeaders =+ (operationToken: () => string) =>+ (opts?: { op?: Operation }): Record<string, string> => {+ const stored = opts?.op?.context[STORED_LOGIN];+ return { 'Oidc-Auth': typeof stored === 'string' ? stored : operationToken() };+ };diff --git a/apps/cli/src/auth/envJwt.ts b/apps/cli/src/auth/envJwt.tsindex 2072f2f12fa..a8d8282f5dc 100644--- a/apps/cli/src/auth/envJwt.ts+++ b/apps/cli/src/auth/envJwt.ts@@ -19,8 +19,8 @@ export const JWT_FILE_ENV = 'LOBEHUB_JWT_FILE';* file is rewritten when the operation token renews, so the env copy goes* stale.* - A `LOBEHUB_JWT` that is defined but empty (`LOBEHUB_JWT= lh …`) is an- * explicit opt-out: the file is ignored, so the agent's "clear LOBEHUB_JWT- * and retry with the machine's login" fallback keeps working.+ * explicit opt-out: the file is ignored, so clearing the variable still means+ * "use this machine's login" (older `lh` guides taught agents to do so).* - A missing, unreadable or empty file behaves as if no file were configured.*/export const hydrateJwtFromFile = (env: NodeJS.ProcessEnv = process.env): void => {diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex ec225be15df..ed30723203e 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -1261,14 +1261,14 @@ const exec = async (options: ExecOptions): Promise<void> => {agentType: options.type,askUserBridge: askBridge,command: resolvedCommand.command,+ commandVersion: resolvedCommand.version,cwd: options.cwd || process.cwd(),detached: process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] !== '1',env: commandEnv,extraArgs,- // Device and sandbox executions are observed through the same gateway- // stream as native server agents. Ask Claude Code for content-block- // deltas so the current conversation receives text while the process is- // running instead of seeing only the terminal assistant snapshot.+ // Device and sandbox executions are observed through the same gateway stream as native+ // server agents. Ask Claude Code for content-block deltas so the current conversation+ // receives text while the process is running, not only the terminal assistant snapshot.includePartialMessages: options.type === 'claude-code',initialModel:options.type === 'droid' || options.type === 'devin' || options.type === 'trae'diff --git a/apps/cli/src/commands/topic/readTranscript.test.ts b/apps/cli/src/commands/topic/readTranscript.test.tsnew file mode 100644index 00000000000..d72e20b1236--- /dev/null+++ b/apps/cli/src/commands/topic/readTranscript.test.ts@@ -0,0 +1,113 @@+import { TRPCClientError } from '@trpc/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { OPERATION_TOKEN_REFUSAL } from '../../api/operationTokenFallback';+import { readTopicTranscript } from './readTranscript';++const jwt = (payload: Record<string, unknown>) =>+ `e30.${Buffer.from(JSON.stringify(payload)).toString('base64url')}.sig`;++const trpcError = (message: string, code: string) =>+ new TRPCClientError(message, {+ result: { error: { code: -32_000, data: { code }, message } },+ } as any);++const query = { includeMessages: true, limit: 50, offset: 0, topicId: 'tpc_named0001' };+const transcript = { items: [], topic: { id: 'tpc_named0001' }, total: 0 };++const fakeClient = () => {+ const operationRoute = vi.fn();+ const userRoute = vi.fn();+ const client = {+ topic: {+ getTopicTranscript: { query: userRoute },+ getTopicTranscriptOperation: { query: operationRoute },+ },+ } as any;+ return { client, operationRoute, userRoute };+};++describe('readTopicTranscript', () => {+ const originalJwt = process.env.LOBEHUB_JWT;++ beforeEach(() => {+ process.env.LOBEHUB_JWT = jwt({ purpose: 'hetero-operation', sub: 'user-1' });+ });++ afterEach(() => {+ if (originalJwt === undefined) delete process.env.LOBEHUB_JWT;+ else process.env.LOBEHUB_JWT = originalJwt;+ });++ it("reads through the run's own operation route", async () => {+ const { client, operationRoute, userRoute } = fakeClient();+ operationRoute.mockResolvedValue(transcript);++ await expect(readTopicTranscript(client, query)).resolves.toBe(transcript);+ expect(operationRoute).toHaveBeenCalledWith(query);+ expect(userRoute).not.toHaveBeenCalled();+ });++ it('keeps an ordinary login on the ordinary route', async () => {+ process.env.LOBEHUB_JWT = jwt({ purpose: 'cli-sandbox', sub: 'user-1' });+ const { client, operationRoute, userRoute } = fakeClient();+ userRoute.mockResolvedValue(transcript);++ await expect(readTopicTranscript(client, query)).resolves.toBe(transcript);+ expect(operationRoute).not.toHaveBeenCalled();+ });++ it('sends an explicit --workspace to the ordinary route', async () => {+ const { client, operationRoute, userRoute } = fakeClient();+ userRoute.mockResolvedValue(transcript);++ await readTopicTranscript(client, query, 'ws-other');++ expect(operationRoute).not.toHaveBeenCalled();+ expect(userRoute).toHaveBeenCalledWith(query);+ });++ it('falls back to the ordinary route on a server without the operation route', async () => {+ const { client, operationRoute, userRoute } = fakeClient();+ operationRoute.mockRejectedValue(+ trpcError('No procedure found on path "topic.getTopicTranscriptOperation"', 'NOT_FOUND'),+ );+ userRoute.mockResolvedValue(transcript);++ await expect(readTopicTranscript(client, query)).resolves.toBe(transcript);+ });++ it('lets a same-account login read a topic outside the run’s boundary', async () => {+ const { client, operationRoute, userRoute } = fakeClient();+ operationRoute.mockRejectedValue(trpcError('outside this run', 'FORBIDDEN'));+ userRoute.mockResolvedValue(transcript);++ await expect(readTopicTranscript(client, query)).resolves.toBe(transcript);+ });++ it("explains the boundary when the ordinary route only repeats the token's refusal", async () => {+ const { client, operationRoute, userRoute } = fakeClient();+ operationRoute.mockRejectedValue(trpcError('outside this run', 'FORBIDDEN'));+ userRoute.mockRejectedValue(trpcError(OPERATION_TOKEN_REFUSAL, 'UNAUTHORIZED'));++ await expect(readTopicTranscript(client, query)).rejects.toThrow('outside this run');+ });++ it('reports a missing topic without retrying elsewhere', async () => {+ const { client, operationRoute, userRoute } = fakeClient();+ operationRoute.mockRejectedValue(trpcError('Topic not found: tpc_named0001', 'NOT_FOUND'));++ await expect(readTopicTranscript(client, query)).rejects.toThrow('Topic not found');+ expect(userRoute).not.toHaveBeenCalled();+ });++ it("shows the ordinary route's refusal when the server has no operation route", async () => {+ const { client, operationRoute, userRoute } = fakeClient();+ operationRoute.mockRejectedValue(+ trpcError('No procedure found on path "topic.getTopicTranscriptOperation"', 'NOT_FOUND'),+ );+ userRoute.mockRejectedValue(trpcError(OPERATION_TOKEN_REFUSAL, 'UNAUTHORIZED'));++ await expect(readTopicTranscript(client, query)).rejects.toThrow(OPERATION_TOKEN_REFUSAL);+ });+});diff --git a/apps/cli/src/commands/topic/readTranscript.ts b/apps/cli/src/commands/topic/readTranscript.tsnew file mode 100644index 00000000000..3cb920062d8--- /dev/null+++ b/apps/cli/src/commands/topic/readTranscript.ts@@ -0,0 +1,55 @@+import { isTRPCClientError } from '@trpc/client';++import type { TrpcClient } from '../../api/client';+import { isOperationToken, isOperationTokenRefusal } from '../../api/operationTokenFallback';++export interface TranscriptQuery {+ includeMessages: boolean;+ limit: number;+ offset: number;+ topicId: string;+}++/** A server that predates the operation route answers this for the unknown path. */+const isMissingProcedure = (error: unknown) =>+ isTRPCClientError(error) && error.message.startsWith('No procedure found on path');++/**+ * Read a topic the way `lh topic view` shows it.+ *+ * A device-dispatched run holds an operation token, which the ordinary route+ * refuses. It reads through `topic.getTopicTranscriptOperation` instead, as the+ * run's own principal, limited to its own conversation and the ones the user+ * names in it. When that route cannot serve the read — a server without it, a+ * topic outside that boundary, a run that already ended — the ordinary route is+ * tried, which on a machine logged in as the same account still answers (see+ * `operationTokenFallback`). If the ordinary route only repeats the operation+ * token refusal, the operation route's own answer is the one worth showing.+ *+ * `--workspace` names a scope the run's token was not minted for, so it always+ * takes the ordinary route.+ */+export const readTopicTranscript = async (+ client: TrpcClient,+ query: TranscriptQuery,+ explicitWorkspace?: string,+) => {+ if (explicitWorkspace || !isOperationToken(process.env.LOBEHUB_JWT)) {+ return client.topic.getTopicTranscript.query(query);+ }++ try {+ return await client.topic.getTopicTranscriptOperation.query(query);+ } catch (operationError) {+ const notFound = isTRPCClientError(operationError) && operationError.data?.code === 'NOT_FOUND';+ if (notFound && !isMissingProcedure(operationError)) throw operationError;++ try {+ return await client.topic.getTopicTranscript.query(query);+ } catch (userRouteError) {+ throw isOperationTokenRefusal(userRouteError) && !isMissingProcedure(operationError)+ ? operationError+ : userRouteError;+ }+ }+};diff --git a/apps/cli/src/commands/topic/view.ts b/apps/cli/src/commands/topic/view.tsindex 824b4927698..0752e1df8e1 100644--- a/apps/cli/src/commands/topic/view.ts+++ b/apps/cli/src/commands/topic/view.ts@@ -4,6 +4,7 @@ import pc from 'picocolors';import { getTrpcClient } from '../../api/client';import { timeAgo } from '../../utils/format';import { log } from '../../utils/logger';+import { readTopicTranscript } from './readTranscript';const DEFAULT_LIMIT = 50;const MAX_LIMIT = 500;@@ -278,12 +279,11 @@ export function registerTopicViewCommand(topic: Command) {? resolvePagination(options): { from: 1, limit: DEFAULT_LIMIT, offset: 0 };const client = await getTrpcClient(options.workspace);- const result = await client.topic.getTopicTranscript.query({- includeMessages,- limit: pagination.limit,- offset: pagination.offset,- topicId: id,- });+ const result = await readTopicTranscript(+ client,+ { includeMessages, limit: pagination.limit, offset: pagination.offset, topicId: id },+ options.workspace,+ );const messages = result.items as TranscriptMessage[];const topicDetail = result.topic as TopicDetail;diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.tsindex 5ed7a136589..cea153fcc20 100644--- a/apps/cli/src/device/agentRun.test.ts+++ b/apps/cli/src/device/agentRun.test.ts@@ -4,7 +4,7 @@ import os from 'node:os';import {HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,- lobeHubCliGuide,+ lobeHubCliGuideBlock,} from '@lobechat/heterogeneous-agents/protocol';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -145,10 +145,7 @@ describe('spawnHeteroAgentRun', () => {await expect(ackPromise).resolves.toEqual({ status: 'accepted' });expect(child.stdin.write).toHaveBeenCalledWith(- JSON.stringify([- { text: lobeHubCliGuide, type: 'text' },- { text: 'hi', type: 'text' },- ]),+ JSON.stringify([lobeHubCliGuideBlock, { text: 'hi', type: 'text' }]),);expect(child.stdin.end).toHaveBeenCalledTimes(1);});@@ -191,10 +188,7 @@ describe('spawnHeteroAgentRun', () => {await expect(ackPromise).resolves.toEqual({ status: 'accepted' });expect(child.stdin.write).toHaveBeenCalledWith(- JSON.stringify([- { text: lobeHubCliGuide, type: 'text' },- { text: 'hi', type: 'text' },- ]),+ JSON.stringify([lobeHubCliGuideBlock, { text: 'hi', type: 'text' }]),);});@@ -269,7 +263,7 @@ describe('spawnHeteroAgentRun', () => {expect(child.stdin.write).toHaveBeenCalledWith(JSON.stringify([{ text: 'workspace rules', type: 'text' },- { text: lobeHubCliGuide, type: 'text' },+ lobeHubCliGuideBlock,{ text: 'do it', type: 'text' },]),);@@ -300,7 +294,7 @@ describe('spawnHeteroAgentRun', () => {// 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' },+ lobeHubCliGuideBlock,{ text: 'continue', type: 'text' },],}),@@ -332,7 +326,7 @@ describe('spawnHeteroAgentRun', () => {expect(child.stdin.write).toHaveBeenCalledWith(JSON.stringify([- { text: lobeHubCliGuide, type: 'text' },+ lobeHubCliGuideBlock,{ text: 'look at this', type: 'text' },{ source: { id: 'file-1', type: 'url', url: 'https://signed/a.png' }, type: 'image' },]),diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 621c607c910..fda55c21ef4 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -98,6 +98,7 @@ import {isDevinAcpSessionNotFoundError,isDroidAcpSessionNotFoundError,normalizeImage,+ prepareClaudeCodeLobeHubCli,readClaudeCodeSessionCost,readCodexSessionModel,resolveCliSpawnPlan,@@ -1020,6 +1021,7 @@ export default class HeterogeneousAgentCtr {// spawn() can't (login-shell PATH, app-bundled Codex CLI, …).const useResolvedPath = Boolean(status?.path) && !command.includes(path.sep);session.resolvedCommandPath = useResolvedPath ? status!.path : undefined;+ session.cliVersion = status?.version;// Carry the login-shell PATH the detector resolved through, so a// `#!/usr/bin/env node` shim spawned by absolute path still finds `node`.session.resolvedCommandSearchPath = useResolvedPath ? status!.resolvedPathEnv : undefined;@@ -1507,27 +1509,22 @@ export default class HeterogeneousAgentCtr {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- * provider-specific serializer runs.- */- private async buildStreamJsonInput(- prompt: string,- imageList: HeterogeneousAgentImageAttachment[] = [],- systemContext?: string,- isNewSession?: boolean,- ): Promise<string> {- const promptInput = buildHeterogeneousPrompt({- imageList,- isNewSession,- prompt,- systemContext,- });- const plan = await buildAgentInput('claude-code', promptInput, {+ /** The SDK's stream-json user message, and the arguments carrying the `lh` guide out of it. */+ private async buildStreamJsonInput(params: SendPromptParams, session: AgentSession) {+ const lobeHubCli = await prepareClaudeCodeLobeHubCli(+ buildHeterogeneousPrompt({+ imageList: params.imageList ?? [],+ isNewSession: this.needsSessionIntroduction(session),+ prompt: params.prompt,+ systemContext: params.systemContext,+ }),+ session.args,+ { resumed: Boolean(session.agentSessionId), version: session.cliVersion },+ );+ const plan = await buildAgentInput('claude-code', lobeHubCli.prompt, {cacheDir: this.fileCacheDir,});- return plan.stdin;+ return { args: lobeHubCli.args, stdin: plan.stdin };}// ─── IPC methods ───@@ -1796,6 +1793,7 @@ export default class HeterogeneousAgentCtr {});spawnPlan = await driver.buildSpawnPlan({args: session.args,+ cliVersion: session.cliVersion,helpers: {buildAgentInput: async (agentType, input) => {try {@@ -2051,21 +2049,16 @@ export default class HeterogeneousAgentCtr {const cwd = session.cwd || electronApp.getPath('desktop');const spawnEnv = this.buildSessionSpawnEnv(session);const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);- const stdinPayload = await this.buildStreamJsonInput(- params.prompt,- params.imageList ?? [],- params.systemContext,- this.needsSessionIntroduction(session),- );+ const input = await this.buildStreamJsonInput(params, session);const traceSession = await this.createCliTraceSession({cliArgs: ['sdk-stream', ...session.args],cwd,imageList: params.imageList ?? [],session,- stdinPayload,+ stdinPayload: input.stdin,});- void this.writeCliTraceFile(traceSession, 'stdin.txt', stdinPayload);+ void this.writeCliTraceFile(traceSession, 'stdin.txt', input.stdin);if (session.cancelledByUs) {await this.completeCancelledSessionBeforeLaunch(session);@@ -2076,7 +2069,7 @@ export default class HeterogeneousAgentCtr {// executable it launches) exists.const startedAt = new Date().toISOString();const sdkSession = new ClaudeAgentSdkSession({- args: session.args,+ args: [...session.args, ...input.args],commandPath,configDir: spawnEnv.CLAUDE_CONFIG_DIR ?? session.hostedProviderBinding?.profileDir,cwd,@@ -2112,7 +2105,7 @@ export default class HeterogeneousAgentCtr {operationId: params.operationId,resumeSessionId: session.agentSessionId,sessionId: session.sessionId,- stdinPayload,+ stdinPayload: input.stdin,uploadImage: this.uploadResultImage,});diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 205ced3e47e..b291ab9f5d0 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -10,6 +10,7 @@ import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipimport {HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,lobeHubCliGuide,+ lobeHubCliGuideBlock,} from '@lobechat/heterogeneous-agents/protocol';import type * as spawnModule from '@lobechat/heterogeneous-agents/spawn';import { AcpRpcResponseError } from '@lobechat/heterogeneous-agents/spawn';@@ -22,8 +23,8 @@ import type * as heteroCliProcessModule from '../../utils/heteroCliProcess';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.+ * A fresh CLI session's serialized prompt leads with the `lh` introduction (Claude+ * Code loads it as a skill instead); a resumed one (`startSession({ resumeSessionId })`) does not.*/const cliGuideBlock = { text: lobeHubCliGuide, type: 'text' };@@ -1511,6 +1512,7 @@ describe('HeterogeneousAgentCtr', () => {const ctr = new HeterogeneousAgentCtr({appStoragePath,+ binaryManager: { detect: async () => ({ available: true, version: '2.1.301' }) },storeManager: { get: vi.fn() },} as any);const { sessionId } = await ctr.startSession({@@ -1541,24 +1543,22 @@ describe('HeterogeneousAgentCtr', () => {const line = writes[0].trimEnd();expect(line.endsWith('\n') || writes[0].endsWith('\n')).toBe(true);const msg = JSON.parse(line);+ expect(cliArgs).toContain('--plugin-dir');expect(msg).toMatchObject({- message: {- content: [cliGuideBlock, { text: prompt, type: 'text' }],- role: 'user',- },+ message: { content: [{ 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.+ // `--resume` keeps working because the transcript was rebuilt, but it is+ // made of persisted chat rows, which never carried the introduction. Skills+ // are disabled here, so the guide cannot ride along as one.ensureResumeTranscriptMock.mockResolvedValueOnce({ path: '/tmp/t.jsonl', written: true });const { writes } = await runSendPrompt('carry on',- { cwd: '/work/dir', resumeSessionId: 'sess-gc' },+ { args: ['--disable-slash-commands'], cwd: '/work/dir', resumeSessionId: 'sess-gc' },[],{ resumeReplayMessages: [{ content: 'earlier', role: 'user' }] } as any,);@@ -1588,7 +1588,6 @@ 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' },]);});@@ -1832,7 +1831,6 @@ 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',@@ -5075,7 +5073,7 @@ describe('HeterogeneousAgentCtr', () => {{ 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,+ lobeHubCliGuideBlock,{ text: 'inspect the repository', type: 'text' },],}),diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.tsindex 3f21785445c..07c8f377827 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts@@ -100,6 +100,8 @@ export interface AgentSession {* intentional, not agent failures.*/cancelledByUs?: boolean;+ /** CLI version spawn preflight detected; decides how Claude Code gets the `lh` guide. */+ cliVersion?: string;codexAppServerFallback?: boolean;command: string;cursorAcpSession?: CursorAcpSession;diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.tsindex 4f8c1c327be..ac1a2bb5bb3 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts@@ -1,4 +1,5 @@-import { describe, expect, it } from 'vitest';+import { buildHeterogeneousPrompt, lobeHubCliGuide } from '@lobechat/heterogeneous-agents/protocol';+import { describe, expect, it, vi } from 'vitest';import type {HeterogeneousAgentBuildPlanHelpers,@@ -39,6 +40,37 @@ describe('claudeCodeDriver', () => {expect(plan.operationTokenEnvKey).toBe('ANTHROPIC_AUTH_TOKEN');expect(plan.env.ANTHROPIC_AUTH_TOKEN).toBeUndefined();});+ const planWithGuide = async (cliVersion?: string) => {+ const buildAgentInput = vi.fn(stubHelpers.buildAgentInput);+ const { args } = await claudeCodeDriver.buildSpawnPlan(+ buildParams({+ cliVersion,+ helpers: { buildAgentInput },+ promptInput: buildHeterogeneousPrompt({ isNewSession: true, prompt: 'fix the test' }),+ }),+ );+ return { args, sentBlocks: buildAgentInput.mock.calls[0][1] as Array<{ text: string }> };+ };++ it("loads the `lh` guide as a skill instead of sending it in the user's turn", async () => {+ const { args, sentBlocks } = await planWithGuide('2.1.301');++ expect(args).toContain('--plugin-dir');+ expect(sentBlocks).toEqual([{ text: 'fix the test', type: 'text' }]);+ });++ // Regression: a Claude Code without plugin skills rejects `--plugin-dir` and+ // never starts, so an old or undetected build keeps the in-message guide.+ it.each(['1.2.3', '2.0.19', undefined])(+ 'keeps the guide in the prompt for Claude Code %s',+ async (cliVersion) => {+ const { args, sentBlocks } = await planWithGuide(cliVersion);++ expect(args).not.toContain('--plugin-dir');+ expect(sentBlocks.map((block) => block.text)).toEqual([lobeHubCliGuide, 'fix the test']);+ },+ );+it('omits --mcp-config when mcpConfigPath is undefined', async () => {const { args } = await claudeCodeDriver.buildSpawnPlan(buildParams());expect(args).not.toContain('--mcp-config');diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.tsindex b921b754334..bff453c4dd6 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts@@ -1,6 +1,7 @@import {buildClaudeCodeDirectEnv,CLAUDE_CODE_BASE_ARGS,+ prepareClaudeCodeLobeHubCli,sanitizeClaudeCodeDirectArgs,sanitizeClaudeCodeDirectEnv,} from '@lobechat/heterogeneous-agents/spawn';@@ -22,12 +23,18 @@ const DESKTOP_CLAUDE_CODE_ARGS = [export const claudeCodeDriver: HeterogeneousAgentDriver = {async buildSpawnPlan({args,+ cliVersion,helpers,mcpConfigPath,promptInput,resumeSessionId,}: HeterogeneousAgentBuildPlanParams) {- const { stdin: stdinPayload } = await helpers.buildAgentInput('claude-code', promptInput);+ // The `lh` guide rides along as a skill, not as text in the user's turn.+ const lobeHubCli = await prepareClaudeCodeLobeHubCli(promptInput, args, {+ resumed: Boolean(resumeSessionId),+ version: cliVersion,+ });+ const { stdin: stdinPayload } = await helpers.buildAgentInput('claude-code', lobeHubCli.prompt);return {args: [@@ -37,6 +44,7 @@ export const claudeCodeDriver: HeterogeneousAgentDriver = {// does not accept inline JSON for `--mcp-config`....(mcpConfigPath ? ['--mcp-config', mcpConfigPath] : []),...(resumeSessionId ? ['--resume', resumeSessionId] : []),+ ...lobeHubCli.args,...args,],stdinPayload,diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts b/apps/desktop/src/main/modules/heterogeneousAgent/types.tsindex c5b62daffeb..439ea443d30 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/types.ts@@ -27,6 +27,8 @@ export interface HeterogeneousAgentBuildPlanHelpers {export interface HeterogeneousAgentBuildPlanParams {args: string[];+ /** CLI version spawn preflight detected, when known. */+ cliVersion?: string;helpers: HeterogeneousAgentBuildPlanHelpers;/*** Optional path to an MCP config JSON written by the controller (e.g. fordiff --git a/apps/server/src/routers/lambda/__tests__/integration/topic.operationRead.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/topic.operationRead.integration.test.tsnew file mode 100644index 00000000000..8912f42f31c--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/integration/topic.operationRead.integration.test.ts@@ -0,0 +1,270 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { messages, topics, users, workspaces } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { and, eq, inArray, isNotNull } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { MessageModel } from '@/database/models/message';+import { ThreadModel } from '@/database/models/thread';+import { TopicModel } from '@/database/models/topic';+import {+ __resetOperationStatesForTesting,+ HeterogeneousPersistenceHandler,+} from '@/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler';+import { HeteroOperationPrincipalError } from '@/server/services/heterogeneousAgent/operationPrincipal';++import { topicRouter } from '../../topic';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return testDB;+ }),+}));++// Re-authorization against the operation row, membership and RBAC has its own+// suite; here it stands in for "the token's run is live", so everything after it+// — the conversation boundary and the topic read — runs for real.+const mockResolve = vi.fn();+vi.mock('@/server/services/heterogeneousAgent/operationPrincipal', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ resolveActiveHeteroOperationPrincipal: (...args: unknown[]) => mockResolve(...args),+}));++const runUser = 'op-read-run-user';+const workspace = 'op-read-workspace';+const conversation = 'tpc_opReadConvo1';++/** A real `hetero-operation` claim set, classified by the real middleware. */+const operationClaims = {+ aud: 'urn:lobehub:hetero-operation',+ capabilities: ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read'],+ exp: Math.floor(Date.now() / 1000) + 3600,+ iat: Math.floor(Date.now() / 1000),+ iss: 'urn:lobehub:internal',+ jti: 'jti-op-read',+ operation_id: 'op_read_1',+ purpose: 'hetero-operation',+ sub: runUser,+ workspace_id: workspace,+};++const callerWith = (oidcAuth: Record<string, unknown>, workspaceId?: string) =>+ topicRouter.createCaller({+ jwtPayload: { userId: runUser },+ oidcAuth,+ userId: runUser,+ workspaceId,+ } as never);++describe('topic.getTopicTranscriptOperation', () => {+ beforeEach(async () => {+ testDB = await getTestDB();+ vi.clearAllMocks();+ __resetOperationStatesForTesting();+ mockResolve.mockResolvedValue({+ operationId: 'op_read_1',+ topicId: conversation,+ userId: runUser,+ workspaceId: workspace,+ });++ await testDB.insert(users).values({ id: runUser });+ await testDB.insert(workspaces).values({+ id: workspace,+ name: workspace,+ primaryOwnerId: runUser,+ slug: workspace,+ });+ await testDB.insert(topics).values([+ { id: conversation, title: 'This run', userId: runUser, workspaceId: workspace },+ { id: 'tpc_opReadNamed1', title: 'Referenced', userId: runUser, workspaceId: workspace },+ { id: 'tpc_opReadOther1', title: 'Never named', userId: runUser, workspaceId: workspace },+ ]);+ await testDB.insert(messages).values([+ {+ content: '参考这个对话,tpc_opReadNamed1,clone 3 个项目到当前目录',+ id: 'op-read-ask',+ role: 'user',+ topicId: conversation,+ userId: runUser,+ workspaceId: workspace,+ },+ {+ content: 'clone lobehub, lobehub-market and lobehub-cloud',+ id: 'op-read-named-body',+ role: 'user',+ topicId: 'tpc_opReadNamed1',+ userId: runUser,+ workspaceId: workspace,+ },+ ]);+ });++ afterEach(async () => {+ __resetOperationStatesForTesting();+ await testDB.delete(users).where(inArray(users.id, [runUser]));+ await testDB.delete(workspaces).where(inArray(workspaces.id, [workspace]));+ });++ it('refuses an ordinary user session — this is not a wider read', async () => {+ await expect(+ callerWith({ sub: runUser }).getTopicTranscriptOperation({ topicId: 'tpc_opReadNamed1' }),+ ).rejects.toThrow('An operation-bound token is required');+ });++ it("reads a conversation the user named, as the run's own principal", async () => {+ const result = await callerWith(operationClaims).getTopicTranscriptOperation({+ topicId: 'tpc_opReadNamed1',+ });++ expect(mockResolve).toHaveBeenCalledWith(+ expect.objectContaining({ capability: 'hetero:ingest', operationId: 'op_read_1' }),+ );+ expect(result.topic).toMatchObject({ id: 'tpc_opReadNamed1', title: 'Referenced' });+ expect(result.items).toEqual([+ expect.objectContaining({ content: 'clone lobehub, lobehub-market and lobehub-cloud' }),+ ]);+ });++ it('reads the run’s own conversation', async () => {+ const result = await callerWith(operationClaims).getTopicTranscriptOperation({+ includeMessages: false,+ topicId: conversation,+ });++ expect(result.topic).toMatchObject({ id: conversation });+ });++ it("takes the scope from the operation, not from the request's workspace header", async () => {+ const result = await callerWith(+ operationClaims,+ 'some-other-workspace',+ ).getTopicTranscriptOperation({ topicId: 'tpc_opReadNamed1' });++ expect(result.topic).toMatchObject({ id: 'tpc_opReadNamed1' });+ });++ /**+ * The user could read this topic with their own session; the run's token may+ * not, because nothing in the run's conversation points at it.+ */+ it('refuses a topic the conversation never names, before looking it up', async () => {+ await expect(+ callerWith(operationClaims).getTopicTranscriptOperation({ topicId: 'tpc_opReadOther1' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ callerWith(operationClaims).getTopicTranscriptOperation({ topicId: 'tpc_doesNotExist' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it('does not grant topic access from an ingested subagent prompt', async () => {+ const topicId = 'tpc_opReadOther1';+ const caller = callerWith(operationClaims);+ await expect(caller.getTopicTranscriptOperation({ topicId })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });++ const topicModel = new TopicModel(testDB, runUser, workspace);+ await testDB.insert(messages).values({+ content: '',+ id: 'op-read-assistant',+ parentId: 'op-read-ask',+ role: 'assistant',+ topicId: conversation,+ userId: runUser,+ workspaceId: workspace,+ });+ await topicModel.updateMetadata(conversation, {+ runningOperation: {+ assistantMessageId: 'op-read-assistant',+ operationId: operationClaims.operation_id,+ startedAt: new Date().toISOString(),+ type: 'execAgent',+ },+ });+ const handler = new HeterogeneousPersistenceHandler({+ messageModel: new MessageModel(testDB, runUser, workspace),+ threadModel: new ThreadModel(testDB, runUser, workspace),+ topicModel,+ userId: runUser,+ workspaceId: workspace,+ });+ await handler.ingest({+ events: [+ {+ data: {+ chunkType: 'text',+ content: 'Starting the delegated task',+ subagent: {+ parentToolCallId: 'op-read-subagent-call',+ spawnMetadata: { prompt: `Read ${topicId}`, subagentType: 'Explore' },+ subagentMessageId: 'op-read-subagent-message',+ },+ },+ operationId: operationClaims.operation_id,+ stepIndex: 0,+ timestamp: Date.now(),+ type: 'stream_chunk',+ },+ ],+ operationId: operationClaims.operation_id,+ topicId: conversation,+ });++ // Prove the real ingest persistence path wrote the synthetic user message.+ expect(+ await testDB+ .select({ content: messages.content })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, conversation),+ eq(messages.role, 'user'),+ isNotNull(messages.threadId),+ ),+ ),+ ).toEqual([{ content: `Read ${topicId}` }]);+ await expect(caller.getTopicTranscriptOperation({ topicId })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });++ // A real user reference in the main conversation can still grant access.+ await testDB.insert(messages).values({+ content: `Please read ${topicId}`,+ id: 'op-read-user-authorizes',+ role: 'user',+ topicId: conversation,+ userId: runUser,+ workspaceId: workspace,+ });+ await expect(caller.getTopicTranscriptOperation({ topicId })).resolves.toMatchObject({+ topic: { id: topicId },+ });+ });++ it('refuses an operation that has no conversation', async () => {+ mockResolve.mockResolvedValue({+ operationId: 'op_read_1',+ userId: runUser,+ workspaceId: workspace,+ });++ await expect(+ callerWith(operationClaims).getTopicTranscriptOperation({ topicId: 'tpc_opReadNamed1' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it.each([+ [401, 'UNAUTHORIZED'],+ [403, 'FORBIDDEN'],+ [409, 'CONFLICT'],+ ] as const)('maps a %i principal refusal to %s', async (status, code) => {+ mockResolve.mockRejectedValue(new HeteroOperationPrincipalError('refused', status));++ await expect(+ callerWith(operationClaims).getTopicTranscriptOperation({ topicId: 'tpc_opReadNamed1' }),+ ).rejects.toMatchObject({ code, message: 'refused' });+ });+});diff --git a/apps/server/src/routers/lambda/topic/index.procedures.test.ts b/apps/server/src/routers/lambda/topic/index.procedures.test.tsindex dcb127a9408..3616a48f747 100644--- a/apps/server/src/routers/lambda/topic/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/topic/index.procedures.test.ts@@ -45,6 +45,7 @@ function expected(): Array<['getTopicContext', 'query', 12],['getTopicDetail', 'query', 12],['getTopicTranscript', 'query', 12],+ ['getTopicTranscriptOperation', 'query', 9],['getTopics', 'query', 12],['hasTopicFiles', 'query', 13],['hasTopics', 'query', 11],diff --git a/apps/server/src/routers/lambda/topic/index.ts b/apps/server/src/routers/lambda/topic/index.tsindex a92d958609a..748e886424f 100644--- a/apps/server/src/routers/lambda/topic/index.ts+++ b/apps/server/src/routers/lambda/topic/index.ts@@ -1,6 +1,7 @@import { mergeRouters } from '@/libs/trpc/lambda';import { createRouter } from './create';+import { operationReadRouter } from './operationReads';import { queryRouter } from './queries';import { removeRouter } from './remove';import { shareRouter } from './share';@@ -12,6 +13,7 @@ export const topicRouter = mergeRouters(createRouter,removeRouter,shareRouter,+ operationReadRouter,);export type TopicRouter = typeof topicRouter;diff --git a/apps/server/src/routers/lambda/topic/operationReads.ts b/apps/server/src/routers/lambda/topic/operationReads.tsnew file mode 100644index 00000000000..5c020e1dfb2--- /dev/null+++ b/apps/server/src/routers/lambda/topic/operationReads.ts@@ -0,0 +1,92 @@+import { TRPCError } from '@trpc/server';++import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import {+ HeteroOperationPrincipalError,+ resolveActiveHeteroOperationPrincipal,+} from '@/server/services/heterogeneousAgent/operationPrincipal';+import { TopicReferenceService } from '@/server/services/topicReference';++import { readTopicTranscript, topicTranscriptInput } from './transcript';++/**+ * The topic read a device-dispatched run needs, under its own identity.+ *+ * Those runs hold a `hetero-operation` JWT, which `oidcAuth` refuses on the+ * ordinary route, so `lh topic view` failed whenever the user pointed the agent+ * at an earlier conversation — the most common thing a run asks LobeHub for.+ * The workaround was the machine's stored login, which on a shared workspace+ * device belongs to whoever enrolled it, not to the member whose run this is.+ * This route answers with the run's own principal instead.+ *+ * Scope is the operation's principal AND its conversation: a token reads its own+ * conversation and the conversations a user message in it names (a bare id or a+ * `<refer_topic>` tag). A leaked token therefore reaches what the user pointed+ * this run at — not every topic of the workspace whose id it learns. Anything+ * else is refused before the topic is looked up, so the refusal says nothing+ * about whether it exists.+ *+ * The capability is `hetero:ingest`, as for the Goal operation reads: every run+ * token carries it, and a new capability would make pods that predate it reject+ * the whole token — ingest included — during a rolling deploy.+ * `allowTerminalOperation` stays unset: the token reads only while its run runs.+ */+const topicOperationReadProcedure = heteroAuthedProcedure.use(serverDatabase).use(async (opts) => {+ if (opts.ctx.heteroAuthKind !== 'operation' || !opts.ctx.heteroOperation) {+ throw new TRPCError({+ code: 'UNAUTHORIZED',+ message: 'An operation-bound token is required',+ });+ }+ let principal;+ try {+ principal = await resolveActiveHeteroOperationPrincipal({+ capability: 'hetero:ingest',+ claims: opts.ctx.heteroOperation,+ db: opts.ctx.serverDB,+ operationId: opts.ctx.heteroOperation.operation_id,+ });+ } catch (error) {+ if (!(error instanceof HeteroOperationPrincipalError)) throw error;+ throw new TRPCError({+ cause: error,+ code: error.status === 401 ? 'UNAUTHORIZED' : error.status === 409 ? 'CONFLICT' : 'FORBIDDEN',+ message: error.message,+ });+ }+ return opts.next({+ ctx: {+ topicReference: new TopicReferenceService(+ opts.ctx.serverDB,+ principal.userId,+ principal.workspaceId,+ ),+ operationTopicId: principal.topicId,+ userId: principal.userId,+ workspaceId: principal.workspaceId,+ },+ });+});++export const operationReadRouter = router({+ getTopicTranscriptOperation: topicOperationReadProcedure+ .input(topicTranscriptInput)+ .query(async ({ ctx, input }) => {+ const reachable =+ !!ctx.operationTopicId &&+ (await ctx.topicReference.isNamedInConversation(ctx.operationTopicId, input.topicId));+ if (!reachable) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message:+ "This run can read its own conversation and the ones the user names in it; this topic isn't one of them.",+ });+ }++ return readTopicTranscript(+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },+ input,+ );+ }),+});diff --git a/apps/server/src/routers/lambda/topic/queries.ts b/apps/server/src/routers/lambda/topic/queries.tsindex ed4d6248a76..3f5e56b7c04 100644--- a/apps/server/src/routers/lambda/topic/queries.ts+++ b/apps/server/src/routers/lambda/topic/queries.ts@@ -10,7 +10,6 @@ import { and, eq, inArray } from 'drizzle-orm';import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';-import { MessageModel } from '@/database/models/message';import { agents, chatGroups } from '@/database/schemas';import { notTrashed } from '@/database/utils/softDelete';import { buildWorkspaceWhere } from '@/database/utils/workspace';@@ -21,6 +20,7 @@ import { after } from '@/server/utils/scheduleAfterResponse';import { assertCanUseConversationTargets } from '../_helpers/conversationResourceGuard';import { batchResolveAgentIdFromSessions, resolveContext } from '../_helpers/resolveContext';import { guardCtx, topicProcedure, topicSearchProcedure } from './procedures';+import { readTopicTranscript, topicTranscriptInput } from './transcript';export const queryRouter = router({getTopicDetail: topicProcedure@@ -31,45 +31,13 @@ export const queryRouter = router({return topic;}),getTopicTranscript: topicProcedure- .input(- z.object({- includeMessages: z.boolean().default(true),- limit: z.number().int().min(1).max(500).default(50),- offset: z.number().int().min(0).default(0),- topicId: z.string(),- }),- )- .query(async ({ input, ctx }) => {- // `lh topic view` from a workspace run may be given one of the user's personal topic ids.- const topic = await new TopicReferenceService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- ).findTopic(input.topicId);-- if (!topic) {- throw new TRPCError({- code: 'NOT_FOUND',- message: `Topic not found: ${input.topicId}`,- });- }-- if (!input.includeMessages) {- return { items: [], topic, total: null };- }-- const messageModel =- (topic.workspaceId ?? undefined) === (ctx.workspaceId ?? undefined)- ? ctx.messageModel- : new MessageModel(ctx.serverDB, ctx.userId, topic.workspaceId ?? undefined);- const transcript = await messageModel.queryTopicTranscript({- limit: input.limit,- offset: input.offset,- topicId: input.topicId,- });-- return { ...transcript, topic };- }),+ .input(topicTranscriptInput)+ .query(async ({ input, ctx }) =>+ readTopicTranscript(+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },+ input,+ ),+ ),/*** @deprecated The `lobe-topic-reference` tool was removed; agents read topics with* `lh topic view`. Kept for released Desktop builds and cached web bundles whosediff --git a/apps/server/src/routers/lambda/topic/transcript.ts b/apps/server/src/routers/lambda/topic/transcript.tsnew file mode 100644index 00000000000..54b2749dc40--- /dev/null+++ b/apps/server/src/routers/lambda/topic/transcript.ts@@ -0,0 +1,57 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { MessageModel } from '@/database/models/message';+import type { LobeChatDatabase } from '@/database/type';+import { TopicReferenceService } from '@/server/services/topicReference';++export const topicTranscriptInput = z.object({+ includeMessages: z.boolean().default(true),+ limit: z.number().int().min(1).max(500).default(50),+ offset: z.number().int().min(0).default(0),+ topicId: z.string(),+});++export type TopicTranscriptInput = z.infer<typeof topicTranscriptInput>;++/**+ * One topic and a page of its transcript, as `lh topic view` shows it.+ *+ * Shared by `getTopicTranscript` (a user session) and+ * `getTopicTranscriptOperation` (a run's operation token), so what a topic read+ * may return is decided in one place for both callers.+ */+export const readTopicTranscript = async (+ scope: { db: LobeChatDatabase; userId: string; workspaceId?: string },+ input: TopicTranscriptInput,+) => {+ // `lh topic view` from a workspace run may be given one of the user's personal topic ids.+ const topic = await new TopicReferenceService(+ scope.db,+ scope.userId,+ scope.workspaceId,+ ).findTopic(input.topicId);++ if (!topic) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: `Topic not found: ${input.topicId}`,+ });+ }++ if (!input.includeMessages) {+ return { items: [], topic, total: null };+ }++ const transcript = await new MessageModel(+ scope.db,+ scope.userId,+ topic.workspaceId ?? undefined,+ ).queryTopicTranscript({+ limit: input.limit,+ offset: input.offset,+ topicId: input.topicId,+ });++ return { ...transcript, topic };+};diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.tsindex 669a5b0b6a2..ea7123904bc 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts@@ -1,4 +1,4 @@-import { lobeHubCliGuide } from '@lobechat/heterogeneous-agents/protocol';+import { lobeHubCliGuideBlock } from '@lobechat/heterogeneous-agents/protocol';import { beforeEach, describe, expect, it, vi } from 'vitest';import { spawnHeteroSandbox } from '../sandboxRunner';@@ -135,10 +135,7 @@ describe('spawnHeteroSandbox', () => {});const payload = JSON.parse(decodeStdinPayload(mockCallTool.mock.calls[0][1].command));- expect(payload).toEqual([- { text: lobeHubCliGuide, type: 'text' },- { text: 'hi', type: 'text' },- ]);+ expect(payload).toEqual([lobeHubCliGuideBlock, { text: 'hi', type: 'text' }]);});it('does not repeat the CLI introduction on a resumed session', async () => {diff --git a/apps/server/src/services/heterogeneousAgent/operationPrincipal.test.ts b/apps/server/src/services/heterogeneousAgent/operationPrincipal.test.tsindex 40d824106f4..ca8676c26c6 100644--- a/apps/server/src/services/heterogeneousAgent/operationPrincipal.test.ts+++ b/apps/server/src/services/heterogeneousAgent/operationPrincipal.test.ts@@ -45,6 +45,7 @@ const activeOperation = (overrides: Record<string, unknown> = {}) => ({model: 'model-a',provider: 'lobehub',status: 'running',+ topicId: 'tpc_run',userId: 'user-1',workspaceId: null,...overrides,@@ -82,6 +83,7 @@ describe('resolveActiveHeteroOperationPrincipal', () => {expect(principal).toEqual({agentType,operationId: 'op-1',+ topicId: 'tpc_run',userId: 'user-1',workspaceId: undefined,});diff --git a/apps/server/src/services/heterogeneousAgent/operationPrincipal.ts b/apps/server/src/services/heterogeneousAgent/operationPrincipal.tsindex 1c723137caa..808ec6a2bb6 100644--- a/apps/server/src/services/heterogeneousAgent/operationPrincipal.ts+++ b/apps/server/src/services/heterogeneousAgent/operationPrincipal.ts@@ -26,6 +26,8 @@ export class HeteroOperationPrincipalError extends Error {export interface ActiveHeteroOperationPrincipal {agentType?: ServerDefaultHeterogeneousAgentType;operationId: string;+ /** The conversation the operation answers in, when it has one. */+ topicId?: string;userId: string;workspaceId?: string;}@@ -66,6 +68,7 @@ export const resolveActiveHeteroOperationPrincipal = async (params: {model: agentOperations.model,provider: agentOperations.provider,status: agentOperations.status,+ topicId: agentOperations.topicId,userId: agentOperations.userId,workspaceId: agentOperations.workspaceId,})@@ -116,5 +119,11 @@ export const resolveActiveHeteroOperationPrincipal = async (params: {throw new HeteroOperationPrincipalError('Model invocation is no longer permitted', 403);}- return { agentType, operationId, userId: claims.sub, workspaceId };+ return {+ agentType,+ operationId,+ topicId: operation.topicId ?? undefined,+ userId: claims.sub,+ workspaceId,+ };};diff --git a/apps/server/src/services/topicReference/index.test.ts b/apps/server/src/services/topicReference/index.test.tsindex 8b3671c5c59..c79cb1fd497 100644--- a/apps/server/src/services/topicReference/index.test.ts+++ b/apps/server/src/services/topicReference/index.test.ts@@ -152,3 +152,73 @@ describe('TopicReferenceService scope resolution', () => {});});});++describe('TopicReferenceService.isNamedInConversation', () => {+ const ownerId = 'topic-named-owner';+ const scopeId = 'topic-named-workspace';+ const conversation = 'tpc_namedConvo01';++ beforeAll(async () => {+ await db.insert(users).values({ id: ownerId });+ await db.insert(workspaces).values({+ id: scopeId,+ name: scopeId,+ primaryOwnerId: ownerId,+ slug: scopeId,+ });+ await db.insert(topics).values([+ { id: conversation, userId: ownerId, workspaceId: scopeId },+ { id: 'tpc_namedElsewhere', userId: ownerId, workspaceId: scopeId },+ ]);+ const say = (id: string, content: string, role = 'user', topicId = conversation) => ({+ content,+ id,+ role,+ topicId,+ userId: ownerId,+ workspaceId: scopeId,+ });+ await db+ .insert(messages)+ .values([+ say('named-bare', '参考这个对话,tpc_bareRef0001,clone 3 个项目到当前目录'),+ say('named-tag', '<refer_topic name="Earlier" id="tpc_tagRef00001" />\nSummarize it'),+ say('named-escaped', String.raw`\<refer\_topic name="Earlier" id="tpc\_escRef00001" />`),+ say('named-longer', 'see tpc_prefixRef0001extra'),+ say('named-assistant', 'I could also read tpc_assistRef001', 'assistant'),+ say('named-other-topic', 'tpc_otherConvo01', 'user', 'tpc_namedElsewhere'),+ ]);+ });++ afterAll(async () => {+ await db.delete(users).where(inArray(users.id, [ownerId]));+ });++ const service = new TopicReferenceService(db, ownerId, scopeId);++ it.each([+ ['the conversation itself', conversation],+ ['a bare id the user wrote', 'tpc_bareRef0001'],+ ['a <refer_topic> tag', 'tpc_tagRef00001'],+ ['a markdown-escaped <refer_topic> tag', 'tpc_escRef00001'],+ ])('reaches %s', async (_label, topicId) => {+ await expect(service.isNamedInConversation(conversation, topicId)).resolves.toBe(true);+ });++ it.each([+ ['an id that only starts a longer one', 'tpc_prefixRef0001'],+ ['an id only the assistant mentioned', 'tpc_assistRef001'],+ ['an id named in another conversation', 'tpc_otherConvo01'],+ ['a pattern rather than an id', 'tpc_.*'],+ ])('does not reach %s', async (_label, topicId) => {+ await expect(service.isNamedInConversation(conversation, topicId)).resolves.toBe(false);+ });++ it("does not read another scope's conversation", async () => {+ const outsider = new TopicReferenceService(db, ownerId);++ await expect(outsider.isNamedInConversation(conversation, 'tpc_bareRef0001')).resolves.toBe(+ false,+ );+ });+});diff --git a/apps/server/src/services/topicReference/index.ts b/apps/server/src/services/topicReference/index.tsindex c3d8dcf1081..a5565ed17b9 100644--- a/apps/server/src/services/topicReference/index.ts+++ b/apps/server/src/services/topicReference/index.ts@@ -1,7 +1,13 @@import type { LobeChatDatabase } from '@lobechat/database';+import { and, eq, isNull, sql } from 'drizzle-orm';import { MessageModel } from '@/database/models/message';import { TopicModel } from '@/database/models/topic';+import { messages } from '@/database/schemas';+import { buildWorkspaceWhere } from '@/database/utils/workspace';++/** Generated ids are alphanumerics joined by `_` (`tpc_…`); anything else is never matched. */+const TOPIC_ID_PATTERN = /^\w+$/;export class TopicReferenceService {constructor(@@ -24,6 +30,37 @@ export class TopicReferenceService {return new TopicModel(this.db, this.userId).findOwnTopicById(topicId);};+ /**+ * Whether `topicId` is the conversation `conversationTopicId` itself, or one a user message+ * in its main conversation names — as a bare id or inside a `<refer_topic>` tag,+ * markdown-escaped (`tpc\_…`)+ * or not. The id has to stand on its own: one that only starts a longer id does not count.+ */+ isNamedInConversation = async (conversationTopicId: string, topicId: string) => {+ if (topicId === conversationTopicId) return true;+ if (!TOPIC_ID_PATTERN.test(topicId)) return false;++ const escaped = topicId.replaceAll('_', String.raw`\\_`);+ const pattern = `(^|[^A-Za-z0-9_])(${topicId}|${escaped})([^A-Za-z0-9_]|$)`;+ const [named] = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, conversationTopicId),+ eq(messages.role, 'user'),+ // Ingest persists agent-authored subagent prompts as `user` messages+ // in threads. They are not user authorization to read another topic.+ isNull(messages.threadId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages),+ sql`${messages.content} ~ ${pattern}`,+ ),+ )+ .limit(1);++ return !!named;+ };+getTopicContext = async ({ topicId }: { topicId: string }) => {if (!topicId) return { content: 'topicId is required', success: false };diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.tsindex fc4cc5416b5..853407cab4f 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest';import { buildHeteroExecStdinPayload } from './execStdinPayload';-import { lobeHubCliGuide } from './lobeHubCliGuide';+import { lobeHubCliGuideBlock } from './lobeHubCliGuide';describe('buildHeteroExecStdinPayload', () => {it('returns a plain JSON string when no systemContext or images', () => {@@ -47,7 +47,7 @@ describe('buildHeteroExecStdinPayload', () => {},// 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' },+ lobeHubCliGuideBlock,{ text: 'continue', type: 'text' },{ source: { id: 'file-1', type: 'url', url: 'https://x/a.png' }, type: 'image' },],@@ -60,10 +60,7 @@ describe('buildHeteroExecStdinPayload', () => {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' },- ]);+ expect(JSON.parse(payload)).toEqual([lobeHubCliGuideBlock, { text: 'hello', type: 'text' }]);});it('leaves the CLI introduction out of a resumed session', () => {diff --git a/packages/heterogeneous-agents/src/protocol/index.ts b/packages/heterogeneous-agents/src/protocol/index.tsindex 5872108bbd0..b83421d784c 100644--- a/packages/heterogeneous-agents/src/protocol/index.ts+++ b/packages/heterogeneous-agents/src/protocol/index.ts@@ -12,7 +12,13 @@ export type {HeterogeneousAgentCancellationSignal,} from './cancellation';export { buildHeteroExecStdinPayload, type HeteroExecImageRef } from './execStdinPayload';-export { lobeHubCliGuide } from './lobeHubCliGuide';+export {+ LOBEHUB_CLI_GUIDE_CONTEXT,+ lobeHubCliGuide,+ lobeHubCliGuideBlock,+ lobeHubCliSkillBody,+ lobeHubCliSkillDescription,+} from './lobeHubCliGuide';export { INHERITED_RUN_IDENTITY_ENV_KEYS, stripInheritedRunIdentity } from './runIdentityEnv';export const HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV = 'LOBEHUB_HETERO_EXEC_INHERIT_PROCESS_GROUP';export {diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.tsindex 34ab22d135f..3803d58dae0 100644--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts@@ -1,58 +1,100 @@+import type { AgentTextBlock } from './types';+/*** What an external CLI agent (Claude Code, Codex, Kimi…) is told about `lh`,- * the LobeHub CLI, at the start of a session.+ * the LobeHub CLI.** 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.+ * the working directory. This guide closes that gap.+ *+ * It reaches the agent one of two ways:+ *+ * - **As a native skill** (`lobeHubCliSkillDescription` + this body), where the+ * executing side can load one for the session — see `spawn/lobeHubCliPlugin`.+ * Only the one-line description stays in context; the body is read when the+ * request is about LobeHub. Nothing lands in the user's turn or transcript.+ * - **Inside the first user message** (`lobeHubCliGuide`) everywhere else, once+ * per session — see `isNewSession` in `promptEngine`. That copy is tagged+ * `LOBEHUB_CLI_GUIDE_CONTEXT`, so an executor that delivers the skill drops it+ * even when the dispatcher is older or newer than the executor.+ *+ * In the user turn the guide sat in front of the user's real request and read+ * as the task: an agent asked about an unrelated session id opened with+ * `env | grep -i lobehub` and `lh topic list` (lobehub/lobehub#20675). Hence+ * the first bullet scopes when `lh` is relevant at all, and the topic-id shape+ * is spelled out.** 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.+ * material as `@lobechat/builtin-skills`'s `lobehub` skill.** 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+ * desktop client-mode run inherits the machine's own `lh login`. 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. Codex runs may carry the- * token as `LOBEHUB_JWT_FILE` instead (see `codexShellEnv`); the CLI prefers- * it over an inherited token unless `LOBEHUB_JWT` is set empty, and- * PowerShell/cmd unset a variable assigned an empty value, so the guide clears both.+ * `hetero-operation` token in `LOBEHUB_JWT`, which `oidcAuth` refuses on every+ * user-scoped endpoint. `lh topic view` reads through an operation route+ * instead, as the run's own principal, limited to this conversation and the+ * ones the user names in it (`topic.getTopicTranscriptOperation`) — so the+ * most common request needs no other credential. For the rest, `lh` retries+ * those refusals with the machine's stored login itself when that login is+ * the same account+ * (`apps/cli/src/api/operationTokenFallback.ts`), so the guide no longer+ * teaches the agent to clear the variable — which also borrowed the login of+ * whoever enrolled a shared workspace device, and was applied to errors it+ * did not fit.* - **`LOBEHUB_AGENT_ID`.** Desktop client mode sets it through* `buildLobeHubSessionEnv`. CLI/Desktop dispatch launchers, including* OpenClaw/Hermes, clear inherited identity and inject the current dispatch's* agent id when supplied; a missing id must not retain the launcher's identity.* Gateway-dispatched `lh hetero exec` runs preserve that id through- * `spawnAgent` to the external agent. Auth fallback (clearing `LOBEHUB_JWT`)- * does not change authorship. The id is still not guaranteed on every path:- * `lh task comment` refuses topic/operation contexts with a missing or blank- * agent id rather than attributing Agent output to the user.+ * `spawnAgent` to the external agent. The credential fallback does not change+ * authorship. The id is still not guaranteed on every path: `lh task comment`+ * refuses topic/operation contexts with a missing or blank agent id rather+ * than attributing Agent output to the user.*/-export const lobeHubCliGuide = [- '## LobeHub CLI (`lh`)',- '',++/** Tags the in-message copy of the guide; see `AgentTextBlock.context`. */+export const LOBEHUB_CLI_GUIDE_CONTEXT = 'lobehub-cli-guide';++/**+ * When a skill-loading agent should open the guide. It is the only part such an+ * agent keeps in context, so it names the LobeHub-shaped requests and, just as+ * deliberately, says what is not one.+ */+export const lobeHubCliSkillDescription =+ "Reach the user's LobeHub — the app this conversation runs in — through the preinstalled `lh` CLI. Use when the request concerns LobeHub itself: its documents, knowledge bases, files, memory, earlier conversations (topic ids start with `tpc_`, or a `<refer_topic>` tag), agents and your own agent configuration, tasks, projects, widgets, bots, models, providers, plugins or skills, or generating images, video or speech there. Not needed for ordinary work on local files or other tools.";++const lobeHubCliGuideBody = ["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) and `LOBEHUB_WORKSPACE_ID` (the workspace this conversation belongs to, which scopes every `lh` call) are too whenever the run carries them. 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.',+ '- **When to use it:** only when 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. A request about local files, code or another tool does not need `lh`. Say what you did and where it landed.',+ "- **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) and `LOBEHUB_WORKSPACE_ID` (the workspace this conversation belongs to, which scopes every `lh` call) are too whenever the run carries them. 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. LobeHub topic ids start with `tpc_` — an id in the user's message without that prefix belongs to something else.",+ '- **Earlier conversations:** read one with `lh topic view <id>`. This run can always read its own conversation and the ones the user names in it (a `tpc_…` id or a `<refer_topic>` tag); for any other, ask the user to name it here.','- **If `lh` is older than this app**, the shell may have found a stale global install first: `lh man` lacks a command you expect, or `lh` reports an unknown command. When `LOBEHUB_CLI` is set it is the path of the CLI this app ships — run that path instead of `lh` for the rest of the session.',- '- **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.',+ '- **Look commands up, do not guess them.** `lh man` lists every command, and `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 widget` / `lh dashboard` monitoring widgets and dashboards · `lh search` local resources and the web · `lh recall` past messages, topics, goals and pages in a time window · `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.',"- **Widgets run code with the user's credentials.** Before `lh widget dry-run` of a draft that declares connector credentials (`manifest.env`) or network hosts (`manifest.network.allow`), show the user that version id, what the script does and which credentials and hosts it uses, and wait for their explicit approval of that exact version before passing `--version <id> --yes`. Never publish (`lh widget publish`) without the user's confirmation.",- '- **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 `LOBEHUB_JWT_FILE` 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= LOBEHUB_JWT_FILE= lh …` (sh/bash/zsh), `$env:LOBEHUB_JWT=''; $env:LOBEHUB_JWT_FILE=''; lh …` (PowerShell), `set LOBEHUB_JWT=` and `set LOBEHUB_JWT_FILE=` 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.',+ '- **If a command fails with an authentication or permission error**, 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 on this machine.',].join('\n');++/** The guide as the body of a native skill, under its own title. */+export const lobeHubCliSkillBody = ['# LobeHub CLI (`lh`)', '', lobeHubCliGuideBody].join('\n');++/** The guide as it is attached to the first user message of a session. */+export const lobeHubCliGuide = ['## LobeHub CLI (`lh`)', '', lobeHubCliGuideBody].join('\n');++/** The tagged block `promptEngine` attaches for a new session. */+export const lobeHubCliGuideBlock: AgentTextBlock = {+ context: LOBEHUB_CLI_GUIDE_CONTEXT,+ text: lobeHubCliGuide,+ type: 'text',+};diff --git a/packages/heterogeneous-agents/src/protocol/promptEngine.test.ts b/packages/heterogeneous-agents/src/protocol/promptEngine.test.tsindex 751f53bcdad..167052ae45f 100644--- a/packages/heterogeneous-agents/src/protocol/promptEngine.test.ts+++ b/packages/heterogeneous-agents/src/protocol/promptEngine.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { lobeHubCliGuide } from './lobeHubCliGuide';+import { lobeHubCliGuide, lobeHubCliGuideBlock } from './lobeHubCliGuide';import { buildHeterogeneousPrompt, HeterogeneousPromptEngine } from './promptEngine';describe('HeterogeneousPromptEngine', () => {@@ -43,7 +43,7 @@ describe('HeterogeneousPromptEngine', () => {expect(blocks).toEqual([{ text: 'Workspace context', type: 'text' },- { text: lobeHubCliGuide, type: 'text' },+ lobeHubCliGuideBlock,{ text: 'Draft a doc', type: 'text' },]);});diff --git a/packages/heterogeneous-agents/src/protocol/promptEngine.ts b/packages/heterogeneous-agents/src/protocol/promptEngine.tsindex 9b65ced305a..7ec69c48155 100644--- a/packages/heterogeneous-agents/src/protocol/promptEngine.ts+++ b/packages/heterogeneous-agents/src/protocol/promptEngine.ts@@ -1,4 +1,4 @@-import { lobeHubCliGuide } from './lobeHubCliGuide';+import { LOBEHUB_CLI_GUIDE_CONTEXT, lobeHubCliGuide } from './lobeHubCliGuide';import type { AgentContentBlock, AgentImageBlock } from './types';export interface HeterogeneousPromptEngineInput {@@ -11,7 +11,10 @@ export interface HeterogeneousPromptEngineInput {* 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.+ * turn would stack duplicates for the whole life of the conversation. An+ * executor that loads the guide as a native skill instead (Claude Code, see+ * `spawn/lobeHubCliPlugin`) drops this copy and delivers it every turn, so+ * the gaps below do not apply there.** Rollout consequence, accepted deliberately: a conversation that already had* a CLI session before this shipped resumes into a transcript that never saw@@ -33,6 +36,8 @@ export interface HeterogeneousPromptImage {}export interface HeterogeneousPromptContextProvider {+ /** Stamped onto the provider's block as `AgentTextBlock.context`. */+ context?: string;getContext: (input: HeterogeneousPromptEngineInput) => string | undefined;name: string;}@@ -54,6 +59,7 @@ const topicReferenceGuidanceProvider: HeterogeneousPromptContextProvider = {* Session-scoped: see `isNewSession`.*/const lobeHubCliProvider: HeterogeneousPromptContextProvider = {+ context: LOBEHUB_CLI_GUIDE_CONTEXT,getContext: ({ isNewSession }) => (isNewSession ? lobeHubCliGuide : undefined),name: 'LobeHubCliProvider',};@@ -78,8 +84,9 @@ export class HeterogeneousPromptEngine {if (systemContext?.trim()) blocks.push({ text: systemContext.trim(), type: 'text' });for (const provider of this.contextProviders) {- const context = provider.getContext(this.input)?.trim();- if (context) blocks.push({ text: context, type: 'text' });+ const text = provider.getContext(this.input)?.trim();+ if (!text) continue;+ blocks.push({ ...(provider.context && { context: provider.context }), text, type: 'text' });}if (prompt) blocks.push({ text: prompt, type: 'text' });diff --git a/packages/heterogeneous-agents/src/protocol/types.ts b/packages/heterogeneous-agents/src/protocol/types.tsindex ed8785a2354..ea875042279 100644--- a/packages/heterogeneous-agents/src/protocol/types.ts+++ b/packages/heterogeneous-agents/src/protocol/types.ts@@ -22,6 +22,13 @@ export type AgentImageSource =};export interface AgentTextBlock {+ /**+ * Set when a context provider attached this block rather than the user typing+ * it, naming the provider (e.g. `LOBEHUB_CLI_GUIDE_CONTEXT`). It lets the+ * executing side drop a copy it delivers through a native channel instead.+ * Serializers never forward it to the agent.+ */+ context?: string;text: string;type: 'text';}diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.tsindex b56c9c5cb11..ad89e6a2ccd 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts@@ -213,3 +213,50 @@ describe('ClaudeAgentSdkSession resume cost', () => {expect(resultUsage?.data.costUsd).toBeCloseTo(6.76);});});++describe('ClaudeAgentSdkSession plugins', () => {+ afterEach(() => {+ sdkQueryMock.mockReset();+ });++ const optionsFor = async (args: string[]) => {+ sdkQueryMock.mockImplementation(() => ({+ async *[Symbol.asyncIterator]() {},+ close: vi.fn(),+ }));+ await new ClaudeAgentSdkSession({+ args,+ commandPath: 'claude',+ cwd: os.tmpdir(),+ env: {} as NodeJS.ProcessEnv,+ onEvents: () => {},+ onRawMessage: () => {},+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: () => {},+ operationId: 'op-sdk-plugins',+ sessionId: 'session-1',+ stdinPayload: `${JSON.stringify({ message: { content: 'hi', role: 'user' }, type: 'user' })}\n`,+ }).run();+ return sdkQueryMock.mock.calls[0][0].options;+ };++ // `extraArgs` holds one value per flag, so a user's own `--plugin-dir` and the+ // one carrying the `lh` guide would overwrite each other there.+ it('loads every `--plugin-dir` as a session plugin', async () => {+ const options = await optionsFor(['--plugin-dir', '/user/plugin', '--plugin-dir', '/lobehub']);++ expect(options.plugins).toEqual([+ { path: '/user/plugin', type: 'local' },+ { path: '/lobehub', type: 'local' },+ ]);+ expect(options.extraArgs?.['plugin-dir']).toBeUndefined();+ });++ it('passes an appended system prompt through to the CLI', async () => {+ const options = await optionsFor(['--append-system-prompt', 'guide']);++ expect(options.extraArgs).toEqual({ 'append-system-prompt': 'guide' });+ expect(options).not.toHaveProperty('plugins');+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex 9e7d4ae4e07..58fb1bfff32 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -77,8 +77,10 @@ export const buildClaudeSdkUserMessageFromStreamJson = (stdinPayload: string): Sconst parseClaudeSdkExtraArgs = (args: string[],-): Pick<ClaudeAgentSdkOptions, 'effort' | 'extraArgs' | 'model'> => {+): Pick<ClaudeAgentSdkOptions, 'effort' | 'extraArgs' | 'model' | 'plugins'> => {const extraArgs: Record<string, string | null> = {};+ // `--plugin-dir` repeats, which `extraArgs` (one value per flag) cannot carry.+ const plugins: NonNullable<ClaudeAgentSdkOptions['plugins']> = [];let model: string | undefined;let effort: ClaudeAgentSdkOptions['effort'];@@ -102,6 +104,12 @@ const parseClaudeSdkExtraArgs = (continue;}+ if (key === 'plugin-dir' && hasValue) {+ plugins.push({ path: next, type: 'local' });+ index += 1;+ continue;+ }+extraArgs[key] = hasValue ? next : null;if (hasValue) index += 1;}@@ -110,6 +118,7 @@ const parseClaudeSdkExtraArgs = (...(effort ? { effort } : {}),extraArgs: Object.keys(extraArgs).length > 0 ? extraArgs : undefined,...(model ? { model } : {}),+ ...(plugins.length > 0 ? { plugins } : {}),};};diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex b8ecd89ae15..ee90b45d7e7 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -161,6 +161,17 @@ export {type NormalizeImageOptions,} from './input';export { JsonlStreamProcessor } from './jsonlProcessor';+export {+ buildLobeHubCliPluginFiles,+ CLAUDE_CODE_PLUGIN_SKILLS_MIN_VERSION,+ claudeCodeLoadsPluginSkills,+ type ClaudeCodeLobeHubCliDelivery,+ LOBEHUB_CLI_PLUGIN_NAME,+ LOBEHUB_CLI_SKILL_NAME,+ omitLobeHubCliGuide,+ prepareClaudeCodeLobeHubCli,+ resolveLobeHubCliPluginDir,+} from './lobeHubCliPlugin';// NOTE: `resolveCliCommand` is intentionally NOT re-exported here. It runs// `promisify(execFile)` at module load, which throws under a partial// `node:child_process` mock — and this barrel is widely imported (e.g. fordiff --git a/packages/heterogeneous-agents/src/spawn/lobeHubCliPlugin.bench.ts b/packages/heterogeneous-agents/src/spawn/lobeHubCliPlugin.bench.tsnew file mode 100644index 00000000000..a9616f916d7--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/lobeHubCliPlugin.bench.ts@@ -0,0 +1,24 @@+import { describe, test } from 'vitest';++import { claudeCodeLoadsPluginSkills } from './lobeHubCliPlugin';++// Run separately from concurrent unit tests, from this package:+// bunx vitest bench --run --maxWorkers=1 --no-file-parallelism src/spawn/lobeHubCliPlugin.bench.ts+for (const length of [10_000, 100_000]) {+ describe(`Claude Code version parsing (${length} digits)`, () => {+ const digits = '9'.repeat(length);++ for (const [name, version] of [+ ['major without separators', digits],+ ['missing patch', `${digits}.0`],+ ['long minor', `2.${digits}`],+ ['digits before a valid version', `${digits}x 2.0.20`],+ ]) {+ test(name, async ({ bench }) => {+ await bench('parse version', () => {+ claudeCodeLoadsPluginSkills(version);+ }).run();+ });+ }+ });+}diff --git a/packages/heterogeneous-agents/src/spawn/lobeHubCliPlugin.test.ts b/packages/heterogeneous-agents/src/spawn/lobeHubCliPlugin.test.tsnew file mode 100644index 00000000000..61f0d7246bc--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/lobeHubCliPlugin.test.ts@@ -0,0 +1,238 @@+import { chmod, mkdir, mkdtemp, readFile, rm, symlink } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { parse } from 'yaml';++import {+ buildHeterogeneousPrompt,+ lobeHubCliGuide,+ lobeHubCliGuideBlock,+ lobeHubCliSkillBody,+ lobeHubCliSkillDescription,+} from '../protocol';+import {+ claudeCodeLoadsPluginSkills,+ prepareClaudeCodeLobeHubCli,+ resolveLobeHubCliPluginDir,+} from './lobeHubCliPlugin';++const posixOnly = process.platform === 'win32' ? it.skip : it;++describe('LobeHub CLI plugin', () => {+ let parent: string;+ let rootDir: string;++ beforeEach(async () => {+ parent = await mkdtemp(path.join(tmpdir(), 'lobehub-cli-plugin-test-'));+ rootDir = path.join(parent, 'root');+ });++ afterEach(async () => {+ await rm(parent, { force: true, recursive: true });+ });++ it('writes a Claude Code plugin whose skill frontmatter parses', async () => {+ const pluginDir = await resolveLobeHubCliPluginDir({ rootDir });++ const manifest = JSON.parse(+ await readFile(path.join(pluginDir!, '.claude-plugin/plugin.json'), 'utf8'),+ );+ expect(manifest.name).toBe('lobehub');++ const skill = await readFile(path.join(pluginDir!, 'skills/lobehub/SKILL.md'), 'utf8');+ const [, frontmatter, body] = skill.split(/^---$/m);+ // The description contains `: `, which an unquoted YAML scalar rejects.+ expect(parse(frontmatter)).toEqual({+ description: lobeHubCliSkillDescription,+ name: 'lobehub',+ });+ expect(body.trim()).toBe(lobeHubCliSkillBody);+ });++ it('reuses one directory for the same guide', async () => {+ const first = await resolveLobeHubCliPluginDir({ rootDir });+ const second = await resolveLobeHubCliPluginDir({ rootDir });++ expect(second).toBe(first);+ });++ it('rewrites a plugin a temp-directory cleanup removed', async () => {+ const pluginDir = await resolveLobeHubCliPluginDir({ rootDir });+ await rm(pluginDir!, { force: true, recursive: true });++ await expect(resolveLobeHubCliPluginDir({ rootDir })).resolves.toBe(pluginDir);+ await expect(readFile(path.join(pluginDir!, 'skills/lobehub/SKILL.md'))).resolves.toBeTruthy();+ });++ posixOnly('refuses a root other users can write into', async () => {+ await mkdir(rootDir, { mode: 0o700 });+ await chmod(rootDir, 0o777);++ await expect(resolveLobeHubCliPluginDir({ rootDir })).resolves.toBeUndefined();+ });++ posixOnly('refuses a root that is a symlink', async () => {+ const elsewhere = path.join(parent, 'elsewhere');+ await mkdir(elsewhere, { mode: 0o700 });+ await symlink(elsewhere, rootDir);++ await expect(resolveLobeHubCliPluginDir({ rootDir })).resolves.toBeUndefined();+ });++ describe('prepareClaudeCodeLobeHubCli', () => {+ const version = '2.1.301';+ const prompt = buildHeterogeneousPrompt({+ isNewSession: true,+ prompt: 'fix the failing test',+ systemContext: 'selected code',+ });+ const withoutGuide = [+ { text: 'selected code', type: 'text' },+ { text: 'fix the failing test', type: 'text' },+ ];+ const unwritableRoot = async () => {+ await mkdir(rootDir, { mode: 0o700 });+ await chmod(rootDir, 0o755);+ };++ it('swaps the in-message guide for the plugin and keeps everything else', async () => {+ const delivery = await prepareClaudeCodeLobeHubCli(prompt, [], { rootDir, version });++ expect(prompt).toContainEqual(lobeHubCliGuideBlock);+ expect(delivery.prompt).toEqual(withoutGuide);+ expect(delivery.args).toEqual([+ '--plugin-dir',+ await resolveLobeHubCliPluginDir({ rootDir }),+ ]);+ });++ // Regression: Claude Code before plugin skills rejects `--plugin-dir` and+ // never starts the turn; the binary checks accept any version.+ it.each(['1.2.3', '2.0.19', 'unknown', undefined])(+ 'keeps the guide in the prompt for Claude Code %s',+ async (oldVersion) => {+ const delivery = await prepareClaudeCodeLobeHubCli(prompt, [], {+ rootDir,+ version: oldVersion,+ });++ expect(delivery).toEqual({ args: [], prompt });+ },+ );++ it('keeps the guide in the prompt when skills are disabled', async () => {+ const delivery = await prepareClaudeCodeLobeHubCli(prompt, ['--disable-slash-commands'], {+ rootDir,+ version,+ });++ expect(delivery).toEqual({ args: [], prompt });+ });++ posixOnly('keeps the guide in the prompt of a new session without a plugin', async () => {+ await unwritableRoot();++ const delivery = await prepareClaudeCodeLobeHubCli(prompt, [], { rootDir, version });++ expect(delivery).toEqual({ args: [], prompt });+ });++ // Regression: a resumed turn carries no in-message copy, and earlier turns+ // may have had the plugin, so losing the plugin must not lose the guide.+ // (An appended system prompt would not reach it: `--resume` keeps the+ // session's original one.)+ posixOnly('puts the guide back into a resumed turn that has no plugin', async () => {+ await unwritableRoot();++ const delivery = await prepareClaudeCodeLobeHubCli('carry on', [], {+ resumed: true,+ rootDir,+ version,+ });++ expect(delivery).toEqual({+ args: [],+ prompt: [lobeHubCliGuideBlock, { text: 'carry on', type: 'text' }],+ });+ });++ posixOnly('adds no second copy to a resumed turn that already carries one', async () => {+ await unwritableRoot();+ // A dispatcher predating the tag sends the guide untagged.+ const untagged = [+ { text: lobeHubCliGuide, type: 'text' as const },+ { text: 'hi', type: 'text' as const },+ ];++ const delivery = await prepareClaudeCodeLobeHubCli(untagged, [], {+ resumed: true,+ rootDir,+ version,+ });++ expect(delivery).toEqual({ args: [], prompt: untagged });+ });++ it('keeps a resumed turn unchanged apart from loading the plugin', async () => {+ const delivery = await prepareClaudeCodeLobeHubCli('carry on', [], {+ resumed: true,+ rootDir,+ version,+ });++ expect(delivery).toEqual({+ args: ['--plugin-dir', await resolveLobeHubCliPluginDir({ rootDir })],+ prompt: 'carry on',+ });+ });+ });++ posixOnly("moves to the user's cache directory when the temp root is unusable", async () => {+ const env = { HOME: process.env.HOME, TMPDIR: process.env.TMPDIR };+ const owner = String(process.getuid!());+ process.env.TMPDIR = path.join(parent, 'tmp');+ process.env.HOME = path.join(parent, 'home');+ try {+ await mkdir(path.join(parent, 'tmp', `lobehub-cli-plugin-${owner}`), { recursive: true });+ await chmod(path.join(parent, 'tmp', `lobehub-cli-plugin-${owner}`), 0o777);++ const pluginDir = await resolveLobeHubCliPluginDir();++ expect(pluginDir?.startsWith(path.join(parent, 'home', '.cache', 'lobehub-cli-plugin'))).toBe(+ true,+ );+ } finally {+ for (const [key, value] of Object.entries(env)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });++ it.each([+ ['2.0.20', true],+ ['2.1.0', true],+ ['10.0.0', true],+ ['2.1.301 (Claude Code)', true],+ ['Claude Code v2.0.20', true],+ ['1.2 then 2.0.20', true],+ ['0.2.0.20', false],+ ['2.0.19', false],+ ['1.9.99', false],+ ])('treats Claude Code %s as loading plugin skills: %s', (version, expected) => {+ expect(claudeCodeLoadsPluginSkills(version)).toBe(expected);+ });++ it.each([+ ['major without separators', (digits: string) => digits, false],+ ['missing patch', (digits: string) => `${digits}.0`, false],+ ['long minor', (digits: string) => `2.${digits}`, false],+ ['digits before a valid version', (digits: string) => `${digits}x 2.0.20`, true],+ ] as const)('parses a long banner with %s', (_name, banner, expected) => {+ const version = banner('9'.repeat(100_000));++ expect(claudeCodeLoadsPluginSkills(version)).toBe(expected);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/lobeHubCliPlugin.ts b/packages/heterogeneous-agents/src/spawn/lobeHubCliPlugin.tsnew file mode 100644index 00000000000..3da8919c04e--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/lobeHubCliPlugin.ts@@ -0,0 +1,228 @@+import { createHash, randomUUID } from 'node:crypto';+import { lstat, mkdir, rename, rm, writeFile } from 'node:fs/promises';+import { homedir, tmpdir } from 'node:os';+import path from 'node:path';++import type { AgentContentBlock, AgentPromptInput } from '../protocol';+import {+ LOBEHUB_CLI_GUIDE_CONTEXT,+ lobeHubCliGuide,+ lobeHubCliGuideBlock,+ lobeHubCliSkillBody,+ lobeHubCliSkillDescription,+} from '../protocol/lobeHubCliGuide';++/**+ * Delivers the `lh` guide to Claude Code as a native skill instead of text in+ * the user's turn (lobehub/lobehub#20675).+ *+ * Claude Code loads a plugin directory for one session with `--plugin-dir`+ * (the Agent SDK's `plugins` option), leaving the user's own `~/.claude`+ * untouched. Only the skill's description stays in context; the body is read+ * when a request concerns LobeHub. A plugin is passed on every spawn, resumed+ * turns included, so it never needs the once-per-session bookkeeping the+ * in-message copy does — and nothing lands in the CLI's transcript as words+ * the user said.+ *+ * Only a Claude Code that loads plugin skills gets this; an older or unknown+ * build keeps the in-message guide exactly as before, since it would reject+ * `--plugin-dir` and fail to launch.+ */++export const LOBEHUB_CLI_PLUGIN_NAME = 'lobehub';+export const LOBEHUB_CLI_SKILL_NAME = 'lobehub';++/**+ * Claude Code loads skills, plugin ones included, from 2.0.20 (plugins arrived+ * in 2.0.12). The CLI binary checks accept any version, so this gates delivery.+ */+export const CLAUDE_CODE_PLUGIN_SKILLS_MIN_VERSION = '2.0.20';++/** `claude --disable-slash-commands` disables every skill, plugin ones included. */+const CLAUDE_CODE_DISABLE_SKILLS_FLAG = '--disable-slash-commands';++// Only start at the beginning of a digit run. Otherwise a malformed banner+// retries the match at every digit, taking quadratic time on long numeric runs.+const parseVersion = (version: string) =>+ version+ .match(/(?<!\d)(\d+)\.(\d+)\.(\d+)/)+ ?.slice(1, 4)+ .map(Number);++/** Whether a reported Claude Code version loads plugin skills; unknown means no. */+export const claudeCodeLoadsPluginSkills = (version: string | undefined): boolean => {+ const actual = version ? parseVersion(version) : undefined;+ if (!actual) return false;++ const minimum = parseVersion(CLAUDE_CODE_PLUGIN_SKILLS_MIN_VERSION)!;+ const differing = actual.findIndex((part, index) => part !== minimum[index]);+ return differing === -1 || actual[differing] > minimum[differing];+};++const hasFlag = (args: readonly string[], flag: string) =>+ args.some((arg) => arg === flag || arg.startsWith(`${flag}=`));++const toBlocks = (prompt: AgentPromptInput): AgentContentBlock[] =>+ typeof prompt === 'string' ? (prompt ? [{ text: prompt, type: 'text' }] : []) : prompt;++/** `## LobeHub CLI (`lh`)` — also how dispatchers predating the tag start the guide. */+const LOBEHUB_CLI_GUIDE_HEADING = lobeHubCliGuide.slice(0, lobeHubCliGuide.indexOf('\n'));++/** Whether the prompt carries the guide, tagged or from a dispatcher predating the tag. */+const carriesLobeHubCliGuide = (prompt: AgentPromptInput) =>+ toBlocks(prompt).some(+ (block) =>+ block.type === 'text' &&+ (block.context === LOBEHUB_CLI_GUIDE_CONTEXT ||+ block.text.startsWith(LOBEHUB_CLI_GUIDE_HEADING)),+ );++/** Plugin files keyed by their path inside the plugin root. */+export const buildLobeHubCliPluginFiles = (): Record<string, string> => ({+ '.claude-plugin/plugin.json': `${JSON.stringify(+ {+ description: 'The LobeHub CLI (`lh`) for agents running inside a LobeHub conversation.',+ name: LOBEHUB_CLI_PLUGIN_NAME,+ version: '1.0.0',+ },+ null,+ 2,+ )}\n`,+ // A JSON string is a valid YAML double-quoted scalar, and the description+ // contains `: `, which a plain YAML scalar cannot.+ [`skills/${LOBEHUB_CLI_SKILL_NAME}/SKILL.md`]: [+ '---',+ `name: ${LOBEHUB_CLI_SKILL_NAME}`,+ `description: ${JSON.stringify(lobeHubCliSkillDescription)}`,+ '---',+ '',+ lobeHubCliSkillBody,+ '',+ ].join('\n'),+});++/**+ * Where the plugin may live, in order. The shared temp directory comes first;+ * the user's cache directory backs it when the temp root is unusable (another+ * user created it, a cleanup changed it), so the plugin is only unavailable when+ * neither can be written — and then Claude Code's own writes fail as well.+ */+const defaultRootDirs = () => {+ const owner = typeof process.getuid === 'function' ? String(process.getuid()) : 'user';+ return [+ path.join(tmpdir(), `lobehub-cli-plugin-${owner}`),+ path.join(homedir(), '.cache', 'lobehub-cli-plugin'),+ ];+};++/**+ * The root may sit in a shared temp directory, and whatever a plugin there says+ * is read by the agent as instructions. Only a real directory this user owns+ * and nobody else can write into is used.+ */+const assertPrivateRoot = async (rootDir: string) => {+ await mkdir(rootDir, { mode: 0o700, recursive: true });+ const stat = await lstat(rootDir);+ if (!stat.isDirectory()) throw new Error(`${rootDir} is not a directory`);+ if (typeof process.getuid !== 'function') return;+ if (stat.uid !== process.getuid()) throw new Error(`${rootDir} belongs to another user`);+ if ((stat.mode & 0o077) !== 0) throw new Error(`${rootDir} is accessible to other users`);+};++const pathExists = async (target: string) =>+ lstat(target).then(+ () => true,+ () => false,+ );++const materializePlugin = async (rootDir: string): Promise<string> => {+ const files = buildLobeHubCliPluginFiles();+ // Content-addressed: every run of the same guide shares one directory, so a+ // path an earlier turn saw stays valid, and a changed guide never reuses it.+ const digest = createHash('sha256').update(JSON.stringify(files)).digest('hex').slice(0, 16);+ const pluginDir = path.join(rootDir, digest);++ await assertPrivateRoot(rootDir);+ if (await pathExists(path.join(pluginDir, `skills/${LOBEHUB_CLI_SKILL_NAME}/SKILL.md`))) {+ return pluginDir;+ }++ // Written aside and renamed into place, so a concurrent run never loads a+ // half-written plugin.+ const stagingDir = path.join(rootDir, `.staging-${randomUUID()}`);+ try {+ for (const [relativePath, content] of Object.entries(files)) {+ const target = path.join(stagingDir, relativePath);+ await mkdir(path.dirname(target), { mode: 0o700, recursive: true });+ await writeFile(target, content, { mode: 0o600 });+ }+ await rename(stagingDir, pluginDir).catch(async (error) => {+ // Another run finished first; its copy is identical.+ if (!(await pathExists(pluginDir))) throw error;+ });+ return pluginDir;+ } finally {+ await rm(stagingDir, { force: true, recursive: true });+ }+};++/**+ * Directory of the plugin carrying the guide, written on first use and checked+ * on every spawn — a long-lived desktop process outlives temp-directory+ * cleanups. Resolves `undefined` when no root can be written safely; callers+ * then keep the guide in the prompt, so a run never loses it.+ */+export const resolveLobeHubCliPluginDir = async (+ options: { rootDir?: string } = {},+): Promise<string | undefined> => {+ for (const rootDir of options.rootDir ? [options.rootDir] : defaultRootDirs()) {+ const pluginDir = await materializePlugin(rootDir).catch(() => undefined);+ if (pluginDir) return pluginDir;+ }+};++/** Drop the in-message copy of the guide, which a native skill now carries. */+export const omitLobeHubCliGuide = (prompt: AgentPromptInput): AgentPromptInput =>+ typeof prompt === 'string'+ ? prompt+ : prompt.filter(+ (block) => block.type !== 'text' || block.context !== LOBEHUB_CLI_GUIDE_CONTEXT,+ );++export interface ClaudeCodeLobeHubCliDelivery {+ /** Spawn arguments loading the plugin; empty when the guide is in the prompt. */+ args: string[];+ /** The prompt to send: without the in-message guide exactly when `args` carries it. */+ prompt: AgentPromptInput;+}++/**+ * Prepare a Claude Code spawn to carry the guide as a skill. Every Claude Code+ * launch inside a LobeHub conversation goes through this, so the plugin and the+ * removal of the in-message copy always come together.+ *+ * Without the plugin the guide stays in the prompt as before. A resumed turn+ * carries no in-message copy (`isNewSession`) and its earlier turns may have+ * had the plugin, so there the guide is put back into the prompt rather than+ * lost. An appended system prompt would not do: on `--resume` Claude Code keeps+ * the system prompt the session started with and ignores a new one.+ *+ * @param args the spawn's own arguments; skills disabled there keep the guide in+ * the prompt.+ * @param options.version the Claude Code version the caller detected.+ * @param options.resumed whether this launch resumes a native session.+ */+export const prepareClaudeCodeLobeHubCli = async (+ prompt: AgentPromptInput,+ args: readonly string[] = [],+ options: { resumed?: boolean; rootDir?: string; version?: string } = {},+): Promise<ClaudeCodeLobeHubCliDelivery> => {+ if (hasFlag(args, CLAUDE_CODE_DISABLE_SKILLS_FLAG)) return { args: [], prompt };+ if (!claudeCodeLoadsPluginSkills(options.version)) return { args: [], prompt };++ const pluginDir = await resolveLobeHubCliPluginDir(options);+ if (pluginDir) return { args: ['--plugin-dir', pluginDir], prompt: omitLobeHubCliGuide(prompt) };++ if (!options.resumed || carriesLobeHubCliGuide(prompt)) return { args: [], prompt };+ return { args: [], prompt: [lobeHubCliGuideBlock, ...toBlocks(prompt)] };+};diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.tsindex e455948855c..27619d0112e 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts@@ -1269,15 +1269,15 @@ build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);expect(resolved.command).toBe('/Users/x/.local/bin/amp');});- it('resolves the default bare command to the validated absolute path', async () => {+ it('resolves the default bare command to the validated absolute path and version', async () => {callExecFile('/usr/local/bin/codex\n');callExecFile('codex-cli 0.142.5');const { resolveHeteroSpawnCommand } = await importModule();const resolved = await resolveHeteroSpawnCommand('codex', undefined);- expect(resolved.command).toBe('/usr/local/bin/codex');- expect(resolved.pathEnv).toBeUndefined();+ // The version decides how Claude Code is handed the `lh` guide.+ expect(resolved).toEqual({ command: '/usr/local/bin/codex', version: '0.142.5' });});it('surfaces the login-shell PATH as pathEnv when resolution used it', async () => {diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex 04edfff7222..d6f4852f557 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -942,6 +942,8 @@ export interface ResolvedHeteroCommand {* login-shell PATH; undefined when nothing extra is needed.*/pathEnv?: string;+ /** Version the validating `--version` probe reported; undefined when not resolved. */+ version?: string;}/**@@ -971,7 +973,7 @@ export const resolveHeteroSpawnCommand = async (try {const status = await detectHeterogeneousCliCommand(agentType, defaultCommand);if (status.available && status.path) {- return { command: status.path, pathEnv: status.resolvedPathEnv };+ return { command: status.path, pathEnv: status.resolvedPathEnv, version: status.version };}} catch {// best-effort: fall through to the bare command belowdiff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.lobeHubCli.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.lobeHubCli.test.tsnew file mode 100644index 00000000000..57a7746c4d0--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.lobeHubCli.test.ts@@ -0,0 +1,166 @@+import type * as childProcess from 'node:child_process';+import { EventEmitter } from 'node:events';+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import * as os from 'node:os';+import path from 'node:path';+import { PassThrough } from 'node:stream';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { buildHeterogeneousPrompt, lobeHubCliGuide } from '../protocol';+import { spawnAgent } from './spawnAgent';++const spawnCalls: Array<{ args: string[]; command: string }> = [];+let nextFakeProc: any = null;++vi.mock('node:child_process', async () => {+ const actual = await vi.importActual<typeof childProcess>('node:child_process');+ return {+ ...actual,+ spawn: vi.fn((command: string, args: string[]) => {+ spawnCalls.push({ args, command });+ return nextFakeProc;+ }),+ };+});++vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof os>('node:os');+ return { ...actual, platform: vi.fn(() => 'linux') };+});++/** A one-shot Claude Code child that records what it was sent on stdin. */+const createProc = () => {+ const proc = new EventEmitter() as any;+ const stdinWrites: string[] = [];+ proc.stdin = {+ end: vi.fn(),+ once: vi.fn(),+ write: vi.fn((chunk: string, cb?: () => void) => {+ stdinWrites.push(chunk);+ cb?.();+ return true;+ }),+ };+ proc.stdout = new PassThrough();+ proc.stderr = new PassThrough();+ proc.kill = vi.fn();+ proc.pid = 4321;+ return {+ exit: () => {+ proc.stdout.end();+ proc.stderr.end();+ proc.emit('exit', 0, null);+ },+ proc,+ userContent: () => JSON.parse(stdinWrites[0]).message.content,+ };+};++const run = async (options: Partial<Parameters<typeof spawnAgent>[0]>) => {+ const fake = createProc();+ nextFakeProc = fake.proc;+ const handle = await spawnAgent({+ agentType: 'claude-code',+ // What `lh hetero exec` passes on from its validated `claude --version`.+ commandVersion: '2.1.301',+ operationId: 'op-1',+ prompt: 'hello',+ ...options,+ });+ const drained = (async () => {+ for await (const _event of handle.events);+ })();+ fake.exit();+ await drained;+ return { args: spawnCalls[0].args, userContent: fake.userContent() };+};++const pluginDirArg = (args: string[]) => {+ const index = args.indexOf('--plugin-dir');+ return index === -1 ? undefined : args[index + 1];+};++// The dispatcher's own first-turn prompt: the guide, then the user's request.+const userRequest =+ 'Look at openclaw session 5a8fe152b3cc4537ba69af868b133cc1 — why does the browser fail?';+const firstTurnPrompt = buildHeterogeneousPrompt({ isNewSession: true, prompt: userRequest });++describe('spawnAgent — LobeHub CLI guide for Claude Code', () => {+ let tempRoot: string;+ const originalTmpdir = process.env.TMPDIR;++ beforeEach(async () => {+ spawnCalls.length = 0;+ tempRoot = await mkdtemp(path.join(os.tmpdir(), 'lobehub-cli-spawn-'));+ process.env.TMPDIR = tempRoot;+ });++ afterEach(async () => {+ nextFakeProc = null;+ if (originalTmpdir === undefined) delete process.env.TMPDIR;+ else process.env.TMPDIR = originalTmpdir;+ await rm(tempRoot, { force: true, recursive: true });+ });++ /**+ * Regression (lobehub/lobehub#20675): the guide was prepended to the user's+ * message, persisted in the CLI's transcript as words the user said, and+ * read as the task — the agent went looking for LobeHub topics instead of+ * answering.+ */+ it("loads the guide as a skill and keeps it out of the user's turn", async () => {+ const { args, userContent } = await run({+ env: { LOBEHUB_TOPIC_ID: 'tpc_1' },+ prompt: firstTurnPrompt,+ });++ expect(userContent).toEqual([{ text: userRequest, type: 'text' }]);+ const pluginDir = pluginDirArg(args);+ expect(pluginDir).toBeDefined();+ const skill = await readFile(path.join(pluginDir!, 'skills/lobehub/SKILL.md'), 'utf8');+ expect(skill).toContain('`LOBEHUB_TOPIC_ID` (this conversation)');+ });++ it('loads the skill on a resumed turn, which carries no in-message copy', async () => {+ const { args } = await run({+ env: { LOBEHUB_TOPIC_ID: 'tpc_1' },+ prompt: buildHeterogeneousPrompt({ isNewSession: false, prompt: 'carry on' }),+ resumeSessionId: 'cc-session',+ });++ expect(pluginDirArg(args)).toBeDefined();+ });++ it('leaves a run outside any LobeHub conversation untouched', async () => {+ const { args, userContent } = await run({ prompt: firstTurnPrompt });++ expect(pluginDirArg(args)).toBeUndefined();+ expect(userContent[0]).toEqual({ text: lobeHubCliGuide, type: 'text' });+ });++ it('keeps the guide in the prompt for a Claude Code that predates plugin skills', async () => {+ const { args, userContent } = await run({+ commandVersion: '2.0.11',+ env: { LOBEHUB_TOPIC_ID: 'tpc_1' },+ prompt: firstTurnPrompt,+ });++ expect(pluginDirArg(args)).toBeUndefined();+ expect(userContent[0]).toEqual({ text: lobeHubCliGuide, type: 'text' });+ });++ it('keeps the guide in the prompt when skills are disabled for the run', async () => {+ const { args, userContent } = await run({+ env: { LOBEHUB_TOPIC_ID: 'tpc_1' },+ extraArgs: ['--disable-slash-commands'],+ prompt: firstTurnPrompt,+ });++ expect(pluginDirArg(args)).toBeUndefined();+ expect(userContent.map((block: { text: string }) => block.text)).toEqual([+ lobeHubCliGuide,+ userRequest,+ ]);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 64d09ceb6c5..953705daef7 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -26,6 +26,7 @@ import {} from './codexShellEnv';import type { AgentPromptInput, BuildAgentInputOptions } from './input';import { buildAgentInput } from './input';+import { prepareClaudeCodeLobeHubCli } from './lobeHubCliPlugin';import { getHeterogeneousAgentPresetEnv } from './presetEnv';import { assertSpawnableWorkingDirectory } from './workingDirectory';@@ -40,6 +41,11 @@ export interface SpawnAgentOptions {* path or is wrapped by a launcher.*/command?: string;+ /**+ * Version of the CLI being spawned, when the caller detected it. Claude Code+ * gets the `lh` guide as a skill only on a version known to load one.+ */+ commandVersion?: string;/** Working directory for the spawned child. Defaults to `process.cwd()`. */cwd?: string;/** Create a dedicated Unix process group. Disable beneath a detached wrapper. */@@ -479,7 +485,23 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentreturn spawnDroidAcpAgent(options, command, cwd);}- const inputPlan = await buildAgentInput(options.agentType, options.prompt, options.inputOptions);+ // A run answering a LobeHub conversation (`lh hetero exec --topic`) gets the+ // `lh` guide as a Claude Code skill rather than in the user's turn. The+ // caller's env, not the inherited one: a standalone run nested inside some+ // other conversation is not answering it.+ const lobeHubCli =+ options.agentType === 'claude-code' && options.env?.LOBEHUB_TOPIC_ID+ ? await prepareClaudeCodeLobeHubCli(options.prompt, options.extraArgs, {+ resumed: Boolean(options.resumeSessionId),+ version: options.commandVersion,+ })+ : { args: [], prompt: options.prompt };+ const promptPlan = await buildAgentInput(+ options.agentType,+ lobeHubCli.prompt,+ options.inputOptions,+ );+ const inputPlan = { ...promptPlan, args: [...lobeHubCli.args, ...promptPlan.args] };const childEnv: NodeJS.ProcessEnv = {...process.env,...getHeterogeneousAgentPresetEnv(options.agentType),