Skip to content

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

♻️ refactor(agent): replace the topic-reference tool with `lh topic` via the lobehub skill (#20834)

Arvin Xu5c161dbc7563
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 11c73fda2e0..c85b4cc7f41 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -287,7 +287,12 @@ export const topicRouter = router({
}),
)
.query(async ({ input, ctx }) => {
- const topic = await ctx.topicModel.findOwnTopicById(input.topicId);
+ // `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({
@@ -300,7 +305,11 @@ export const topicRouter = router({
return { items: [], topic, total: null };
}
- const transcript = await ctx.messageModel.queryTopicTranscript({
+ 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,
@@ -309,6 +318,11 @@ export const topicRouter = router({
return { ...transcript, topic };
}),
+ /**
+ * @deprecated The `lobe-topic-reference` tool was removed; agents read topics with
+ * `lh topic view`. Kept for released Desktop builds and cached web bundles whose
+ * client executor still calls this. Remove once those clients have aged out.
+ */
getTopicContext: topicProcedure
.input(z.object({ topicId: z.string() }))
.query(async ({ input, ctx }) =>
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index 152bd66e3f1..dc9f03e900c 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -1,9 +1,9 @@
import type { AgentRuntimeContext } from '@lobechat/agent-runtime';
import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';
-import { builtinSkills } from '@lobechat/builtin-skills';
+import { builtinSkills, LobeHubIdentifier } from '@lobechat/builtin-skills';
import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';
import type { OperationSkillSet, ProjectInstructionFile } from '@lobechat/context-engine';
-import { buildExpertiseContextSnapshot } from '@lobechat/context-engine';
+import { buildExpertiseContextSnapshot, mentionsTopic } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
import { assembleSkillPool } from '@lobechat/mecha';
import { buildTaskManagerDefaultsPrompt, resourcesTreePrompt } from '@lobechat/prompts';
@@ -793,7 +793,7 @@ export const prepareOperation = async (
// not lazily via the `activateSkill` tool. Gate on the agent's genuinely
// pinned entries (`getActivePluginIds(agentConfig.plugins)`), NOT the
// fully-expanded `agentPlugins`: the latter also carries turn-scoped tool
- // ids (mentions, selected tools, `lobe-topic-reference`, …), which would
+ // ids (mentions, selected tools, `lobe-message`, …), which would
// eager-activate an auto-mode skill whose identifier merely collides with
// one of them. `findAll` uses `skillListColumns` (no `content`), so fetch
// bodies only for the pinned subset to keep the op-param payload bounded.
@@ -922,6 +922,9 @@ export const prepareOperation = async (
enabledPluginIds: [...new Set([...(agentPlugins ?? []), ...shareEnabledSkillIds])],
shareAllowedIds: shareAllowedSkillIds,
skillActivateMode: agentConfig.chatConfig?.skillActivateMode,
+ // Reading another topic (`<refer_topic>` or a raw `tpc_` id) goes through `lh topic view`,
+ // which the lobehub skill teaches.
+ turnSkillIds: mentionsTopic([{ content: prompt ?? '' }]) ? [LobeHubIdentifier] : [],
},
);
} catch (error) {
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index 59d73402983..7dc5da7e2a4 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -361,7 +361,7 @@ export const discoverTools = async (
// OAuth credentials touched for a visitor turn (issuing background MCP
// traffic and refresh jobs on behalf of the creator). The later pass right
// before manifest discovery (~line 618) stays as defense in depth: internal
- // additions like the topic-reference / bot message / multimodal
+ // additions like the bot message / multimodal
// understanding tool are appended after this point and must run through the
// same allowlist.
if (shareGate) {
@@ -839,7 +839,6 @@ export const discoverTools = async (
};
// Dynamically inject turn-scoped builtin tools.
- const hasTopicReference = /refer_topic/.test(prompt ?? '');
const modelAbilities =
builtinModels.find((item) => item.id === model && item.providerId === provider)?.abilities ??
builtinModels.find((item) => item.id === model)?.abilities;
@@ -872,7 +871,6 @@ export const discoverTools = async (
(needsAudioUnderstanding || needsImageUnderstanding || needsVideoUnderstanding);
agentPlugins = [
...agentPlugins,
- ...(hasTopicReference ? ['lobe-topic-reference'] : []),
...(isBotConversation ? [MessageToolIdentifier] : []),
...(shouldEnableMultimodalUnderstanding ? [LobeAgentManifest.identifier] : []),
];
@@ -890,8 +888,8 @@ export const discoverTools = async (
// `discoverTools` (before connector resolution) so that ungranted
// connectors never reach `resolveByIdentifiers` /
// `scheduleStaleConnectorToolsRefresh`. Keep this second pass — the
- // internal additions above (topic reference, bot message tool,
- // multimodal understanding) are appended after the first pass and would
+ // internal additions above (bot message tool, multimodal understanding)
+ // are appended after the first pass and would
// otherwise slip through.
if (shareGate) {
agentPlugins = filterPluginsByShareGate(agentPlugins, shareGate);
diff --git a/apps/server/src/services/aiAgent/shareGate/README.md b/apps/server/src/services/aiAgent/shareGate/README.md
index 1a87db1ac56..bac1015ec22 100644
--- a/apps/server/src/services/aiAgent/shareGate/README.md
+++ b/apps/server/src/services/aiAgent/shareGate/README.md
@@ -63,19 +63,6 @@ Confirmed leak paths (a concrete visitor→creator-data route was found):
with no share-run scoping designed in — same risk class as
`lobe-agent-management`.
-- `lobe-topic-reference`: `topicReferenceRuntime.getTopicContext`
- (`apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts`)
- resolves a free-form model-supplied `topicId` via
- `TopicModel.findOwnTopicById`, scoped only to the creator's `userId` — not
- to this share or agent — letting a visitor's model read the summary or
- recent messages of ANY other topic the creator owns by guessing/enumerating
- ids. `DATA_TOOL_ACCESS_RULES` has no entry for it (it isn't a
- memory/knowledge-base/agent-documents style store), so nothing narrows the
- allowlist grant. The automatic `<refer_topic>` injection path
- (`serverCallLlmContextBuilder.ts`) is separately share-scoped via
- `isTopicVisibleToRun` and is unaffected by this denial — only the
- model-invokable tool-call path is unsafe.
-
Denied for lack of positive safety evidence (no confirmed exploit was
required to withhold access — the point of default-deny is that an unproven
tool does not ship):
diff --git a/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts b/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts
index 56bf75551a9..659a276afef 100644
--- a/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts
+++ b/apps/server/src/services/aiAgent/shareGate/dispatch.test.ts
@@ -12,7 +12,6 @@ import {
import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';
import { SkillsApiName, SkillsIdentifier } from '@lobechat/builtin-tool-skills';
-import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';
import {
AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,
AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,
@@ -37,7 +36,6 @@ describe('AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS', () => {
'lobe-local-system',
'lobe-creds',
'lobe-task',
- TopicReferenceIdentifier,
]) {
expect(AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has(identifier)).toBe(false);
}
diff --git a/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts
index cf52b2e4f9e..0f236d378fd 100644
--- a/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts
+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.test.ts
@@ -28,7 +28,6 @@ import {
SkillsIdentifier,
SkillsManifest,
} from '@lobechat/builtin-tool-skills';
-import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';
import { generateToolsFromManifest } from '@lobechat/context-engine';
import { describe, expect, it } from 'vitest';
@@ -72,26 +71,6 @@ describe('applyShareGateToToolSet', () => {
expect(toolSet.tools).toEqual([]);
});
- it('drops a stale lobe-topic-reference grant left over from before it was denied', () => {
- // `TopicReferenceExecutionRuntime.getTopicContext` resolves a free-form
- // topicId via `TopicModel.findOwnTopicById`, scoped only to the creator's
- // whole store — not to this share/agent. A share config saved while it was
- // still allowlisted could still carry it in `toolGrants`; the gate must
- // keep dropping it rather than newly trusting the stored config.
- const toolSet = buildToolSet([
- { apis: [{ name: 'getTopicContext' }], identifier: TopicReferenceIdentifier },
- ]);
-
- applyShareGateToToolSet(
- toolSet,
- buildGate({ toolGrants: [{ identifier: TopicReferenceIdentifier }] }),
- );
-
- expect(toolSet.enabledToolIds).toEqual([]);
- expect(toolSet.manifestMap).toEqual({});
- expect(toolSet.tools).toEqual([]);
- });
-
it('keeps a non-builtin plugin the owner enabled', () => {
const toolSet = buildToolSet([{ apis: [{ name: 'run' }], identifier: 'mcp-github' }]);
toolSet.manifestMap['mcp-github'].systemRole = 'Use run for repository operations.';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts
deleted file mode 100644
index 50c3b810e48..00000000000
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts
+++ /dev/null
@@ -1,359 +0,0 @@
-import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { type ToolExecutionContext } from '../../types';
-
-// Mock database models
-const mockTopicModelFindOwnTopicById = vi.fn();
-const mockMessageModelQuery = vi.fn();
-
-vi.mock('@/database/models/topic', () => ({
- TopicModel: vi.fn().mockImplementation(function () {
- return {
- findOwnTopicById: (...args: any[]) => mockTopicModelFindOwnTopicById(...args),
- };
- }),
-}));
-
-vi.mock('@/database/models/message', () => ({
- MessageModel: vi.fn().mockImplementation(function () {
- return {
- query: (...args: any[]) => mockMessageModelQuery(...args),
- };
- }),
-}));
-
-// Import after mock setup
-const { MessageModel } = await import('@/database/models/message');
-const { TopicModel } = await import('@/database/models/topic');
-const { topicReferenceRuntime } = await import('../topicReference');
-
-describe('topicReferenceRuntime', () => {
- it('should have the correct identifier', () => {
- expect(topicReferenceRuntime.identifier).toBe(TopicReferenceIdentifier);
- expect(topicReferenceRuntime.identifier).toBe('lobe-topic-reference');
- });
-
- describe('factory', () => {
- it('should throw when serverDB is missing', () => {
- const context: ToolExecutionContext = {
- toolManifestMap: {},
- userId: 'user-1',
- };
-
- expect(() => topicReferenceRuntime.factory(context)).toThrow(
- 'serverDB is required for TopicReference execution',
- );
- });
-
- it('should throw when userId is missing', () => {
- const context: ToolExecutionContext = {
- serverDB: {} as any,
- toolManifestMap: {},
- };
-
- expect(() => topicReferenceRuntime.factory(context)).toThrow(
- 'userId is required for TopicReference execution',
- );
- });
-
- it('should create a runtime with getTopicContext method', () => {
- const context: ToolExecutionContext = {
- serverDB: {} as any,
- toolManifestMap: {},
- userId: 'user-1',
- };
-
- const runtime = topicReferenceRuntime.factory(context);
- expect(runtime).toBeDefined();
- expect(typeof runtime.getTopicContext).toBe('function');
- });
-
- it('should scope models to workspace context', async () => {
- const serverDB = {} as any;
- const runtime = topicReferenceRuntime.factory({
- serverDB,
- toolManifestMap: {},
- userId: 'user-1',
- workspaceId: 'workspace-1',
- });
-
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- id: 'topic-1',
- title: 'Topic',
- workspaceId: 'workspace-1',
- });
- mockMessageModelQuery.mockResolvedValue([]);
-
- await runtime.getTopicContext({ topicId: 'topic-1' });
-
- expect(TopicModel).toHaveBeenCalledWith(serverDB, 'user-1', 'workspace-1');
- expect(MessageModel).toHaveBeenCalledWith(serverDB, 'user-1', 'workspace-1');
- });
- });
-
- describe('getTopicContext', () => {
- let runtime: any;
-
- beforeEach(() => {
- vi.clearAllMocks();
-
- const context: ToolExecutionContext = {
- serverDB: {} as any,
- toolManifestMap: {},
- userId: 'user-1',
- };
-
- runtime = topicReferenceRuntime.factory(context);
- });
-
- it('should return error when topicId is missing', async () => {
- const result = await runtime.getTopicContext({ topicId: '' });
-
- expect(result).toEqual({ content: 'topicId is required', success: false });
- });
-
- it('reads personal messages after a workspace lookup misses', async () => {
- const serverDB = {} as any;
- runtime = topicReferenceRuntime.factory({
- serverDB,
- toolManifestMap: {},
- userId: 'user-1',
- workspaceId: 'workspace-1',
- });
- mockTopicModelFindOwnTopicById.mockResolvedValueOnce(null).mockResolvedValueOnce({
- agentId: 'personal-agent',
- id: 'personal-topic',
- title: 'Personal notes',
- workspaceId: null,
- });
- mockMessageModelQuery.mockResolvedValue([{ content: 'Pitch notes', role: 'user' }]);
-
- const result = await runtime.getTopicContext({ topicId: 'personal-topic' });
-
- expect(result.success).toBe(true);
- expect(result.content).toContain('Pitch notes');
- expect(TopicModel).toHaveBeenNthCalledWith(1, serverDB, 'user-1', 'workspace-1');
- expect(TopicModel).toHaveBeenNthCalledWith(2, serverDB, 'user-1');
- expect(MessageModel).toHaveBeenCalledWith(serverDB, 'user-1', undefined);
- expect(mockMessageModelQuery).toHaveBeenCalledWith({
- agentId: 'personal-agent',
- groupId: undefined,
- topicId: 'personal-topic',
- });
- });
-
- it('should return error when topicId is undefined', async () => {
- const result = await runtime.getTopicContext({ topicId: undefined });
-
- expect(result).toEqual({ content: 'topicId is required', success: false });
- });
-
- it('should return error when topic is not found', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue(null);
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result).toEqual({
- content: 'Topic not found: topic-123',
- success: false,
- });
- expect(mockTopicModelFindOwnTopicById).toHaveBeenCalledWith('topic-123');
- });
-
- it('should return historySummary when topic has one', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- historySummary: 'This is a summary of the conversation.',
- id: 'topic-123',
- title: 'My Topic',
- });
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result).toEqual({
- content: '# Topic: My Topic\n\n## Summary\nThis is a summary of the conversation.',
- success: true,
- });
- // Should NOT fetch messages when summary exists
- expect(mockMessageModelQuery).not.toHaveBeenCalled();
- });
-
- it('should use "Untitled" when topic has no title and has historySummary', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- historySummary: 'Summary content',
- id: 'topic-123',
- title: null,
- });
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result.content).toContain('# Topic: Untitled');
- expect(result.success).toBe(true);
- });
-
- it('should fallback to messages when topic has no historySummary', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- agentId: 'agent-1',
- groupId: 'group-1',
- id: 'topic-123',
- title: 'Chat Topic',
- });
-
- mockMessageModelQuery.mockResolvedValue([
- { content: 'Hello', role: 'user' },
- { content: 'Hi there!', role: 'assistant' },
- ]);
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result.success).toBe(true);
- expect(result.content).toContain('# Topic: Chat Topic');
- expect(result.content).toContain('## Recent Messages');
- expect(result.content).toContain('**User**: Hello');
- expect(result.content).toContain('**Assistant**: Hi there!');
-
- expect(mockMessageModelQuery).toHaveBeenCalledWith({
- agentId: 'agent-1',
- groupId: 'group-1',
- topicId: 'topic-123',
- });
- });
-
- it('should pass undefined agentId/groupId when topic has none', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- id: 'topic-123',
- title: 'Simple Topic',
- });
-
- mockMessageModelQuery.mockResolvedValue([]);
-
- await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(mockMessageModelQuery).toHaveBeenCalledWith({
- agentId: undefined,
- groupId: undefined,
- topicId: 'topic-123',
- });
- });
-
- it('should limit messages to last 30', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- id: 'topic-123',
- title: 'Long Chat',
- });
-
- // Create 35 messages with unique identifiable content
- const messages = Array.from({ length: 35 }, (_, i) => ({
- content: `UniqueMsg-${String(i + 1).padStart(3, '0')}`,
- role: 'user',
- }));
- mockMessageModelQuery.mockResolvedValue(messages);
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result.success).toBe(true);
- // Should only contain last 30 messages (indices 5-34, i.e. UniqueMsg-006 to UniqueMsg-035)
- expect(result.content).not.toContain('UniqueMsg-001');
- expect(result.content).not.toContain('UniqueMsg-005');
- expect(result.content).toContain('UniqueMsg-006');
- expect(result.content).toContain('UniqueMsg-035');
- });
-
- it('should skip messages with empty content', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- id: 'topic-123',
- title: 'Topic',
- });
-
- mockMessageModelQuery.mockResolvedValue([
- { content: 'Valid message', role: 'user' },
- { content: '', role: 'assistant' },
- { content: ' ', role: 'user' },
- { content: 'Another message', role: 'assistant' },
- ]);
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result.content).toContain('**User**: Valid message');
- expect(result.content).toContain('**Assistant**: Another message');
- // Empty/whitespace messages should not appear
- const lines = result.content.split('\n').filter((l: string) => l.trim());
- const messageLines = lines.filter((l: string) => l.startsWith('**'));
- expect(messageLines).toHaveLength(2);
- });
-
- it('should handle non-user and non-assistant roles', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- id: 'topic-123',
- title: 'Topic',
- });
-
- mockMessageModelQuery.mockResolvedValue([
- { content: 'System message', role: 'system' },
- { content: 'Tool result', role: 'tool' },
- ]);
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result.success).toBe(true);
- expect(result.content).toContain('**system**: System message');
- expect(result.content).toContain('**tool**: Tool result');
- });
-
- it('should return error when topic model throws', async () => {
- const error = new Error('Database connection failed');
- mockTopicModelFindOwnTopicById.mockRejectedValue(error);
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result.success).toBe(false);
- expect(result.content).toContain('Failed to fetch topic context: Database connection failed');
- expect(result.error).toBe(error);
- });
-
- it('should return error when message model throws', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- id: 'topic-123',
- title: 'Topic',
- });
-
- const error = new Error('Query failed');
- mockMessageModelQuery.mockRejectedValue(error);
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result.success).toBe(false);
- expect(result.content).toContain('Failed to fetch topic context: Query failed');
- expect(result.error).toBe(error);
- });
-
- it('should handle non-Error exceptions', async () => {
- mockTopicModelFindOwnTopicById.mockRejectedValue('string error');
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result.success).toBe(false);
- expect(result.content).toContain('Failed to fetch topic context: string error');
- });
-
- it('should handle null message content', async () => {
- mockTopicModelFindOwnTopicById.mockResolvedValue({
- id: 'topic-123',
- title: 'Topic',
- });
-
- mockMessageModelQuery.mockResolvedValue([
- { content: null, role: 'user' },
- { content: 'Real message', role: 'assistant' },
- ]);
-
- const result = await runtime.getTopicContext({ topicId: 'topic-123' });
-
- expect(result.success).toBe(true);
- // null content should be treated as empty and skipped
- const messageLines = result.content.split('\n').filter((l: string) => l.startsWith('**'));
- expect(messageLines).toHaveLength(1);
- expect(result.content).toContain('**Assistant**: Real message');
- });
- });
-});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
index 75dbe9809c4..6630e4aec0f 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
@@ -44,7 +44,6 @@ import { skillManagementRuntime } from './skillManagement';
import { skillsRuntime } from './skills';
import { skillStoreRuntime } from './skillStore';
import { taskRuntime } from './task';
-import { topicReferenceRuntime } from './topicReference';
import type { ServerRuntimeFactory, ServerRuntimeRegistration } from './types';
import { userInteractionRuntime } from './userInteraction';
import { verifyResultRuntime } from './verifyResult';
@@ -88,7 +87,6 @@ registerRuntimes([
remoteDeviceRuntime,
briefRuntime,
taskRuntime,
- topicReferenceRuntime,
userInteractionRuntime,
credsRuntime,
dashboardRuntime,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts b/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts
deleted file mode 100644
index 08bc4e61794..00000000000
--- a/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';
-import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
-
-import { TopicReferenceService } from '@/server/services/topicReference';
-
-import type { ServerRuntimeRegistration } from './types';
-
-export const topicReferenceRuntime: ServerRuntimeRegistration = {
- factory: (context) => {
- if (!context.serverDB) {
- throw new Error('serverDB is required for TopicReference execution');
- }
- if (!context.userId) {
- throw new Error('userId is required for TopicReference execution');
- }
- const service = new TopicReferenceService(
- context.serverDB,
- context.userId,
- context.workspaceId,
- );
- return {
- getTopicContext: async (params: { topicId: string }): Promise<BuiltinServerRuntimeOutput> => {
- try {
- return await service.getTopicContext(params);
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error);
- return {
- content: `Failed to fetch topic context: ${errorMessage}`,
- error,
- success: false,
- };
- }
- },
- };
- },
- identifier: TopicReferenceIdentifier,
-};
diff --git a/apps/server/src/services/topicReference/index.test.ts b/apps/server/src/services/topicReference/index.test.ts
index 526260edb11..8b3671c5c59 100644
--- a/apps/server/src/services/topicReference/index.test.ts
+++ b/apps/server/src/services/topicReference/index.test.ts
@@ -118,6 +118,33 @@ describe('TopicReferenceService scope resolution', () => {
});
});
+ describe('findTopic', () => {
+ it('falls back to the caller’s personal topic from a workspace', async () => {
+ expect(await workspaceService.findTopic('reference-personal-messages')).toMatchObject({
+ id: 'reference-personal-messages',
+ workspaceId: null,
+ });
+ });
+
+ it('prefers the current workspace', async () => {
+ expect(await workspaceService.findTopic('reference-current')).toMatchObject({
+ id: 'reference-current',
+ workspaceId,
+ });
+ });
+
+ it.each(['reference-other-user', 'reference-other-workspace', 'reference-visitor', 'missing'])(
+ 'does not resolve inaccessible topic %s',
+ async (topicId) => {
+ expect(await workspaceService.findTopic(topicId)).toBeUndefined();
+ },
+ );
+
+ it('does not reach a workspace from personal mode', async () => {
+ expect(await personalService.findTopic('reference-current')).toBeUndefined();
+ });
+ });
+
it('does not expand personal-mode reads into workspaces', async () => {
expect(await personalService.getTopicContext({ topicId: 'reference-current' })).toEqual({
content: 'Topic not found: reference-current',
diff --git a/apps/server/src/services/topicReference/index.ts b/apps/server/src/services/topicReference/index.ts
index 55aa1ccc00c..c3d8dcf1081 100644
--- a/apps/server/src/services/topicReference/index.ts
+++ b/apps/server/src/services/topicReference/index.ts
@@ -10,16 +10,24 @@ export class TopicReferenceService {
private workspaceId?: string,
) {}
- getTopicContext = async ({ topicId }: { topicId: string }) => {
- if (!topicId) return { content: 'topicId is required', success: false };
-
- let topic = await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(
+ /**
+ * Find one of the user's topics by id from the current scope. A workspace run can still be
+ * handed one of the user's personal topic ids, so a workspace miss retries the personal scope.
+ * It never reaches another workspace or another user's topics.
+ */
+ findTopic = async (topicId: string) => {
+ const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(
topicId,
);
+ if (topic || !this.workspaceId) return topic;
- if (!topic && this.workspaceId) {
- topic = await new TopicModel(this.db, this.userId).findOwnTopicById(topicId);
- }
+ return new TopicModel(this.db, this.userId).findOwnTopicById(topicId);
+ };
+
+ getTopicContext = async ({ topicId }: { topicId: string }) => {
+ if (!topicId) return { content: 'topicId is required', success: false };
+
+ const topic = await this.findTopic(topicId);
if (!topic) return { content: `Topic not found: ${topicId}`, success: false };
diff --git a/locales/ar/setting.json b/locales/ar/setting.json
index 625d6a86c95..ec5dbdee7a5 100644
--- a/locales/ar/setting.json
+++ b/locales/ar/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "المهارات",
"tools.builtins.lobe-task.description": "إنشاء، عرض، تحرير، وحذف المهام مع إدارة التبعيات وإعدادات المراجعة",
"tools.builtins.lobe-task.title": "أدوات المهام",
- "tools.builtins.lobe-topic-reference.description": "استرجاع السياق من المحادثات المرجعية للمواضيع",
- "tools.builtins.lobe-topic-reference.title": "مرجع الموضوع",
"tools.builtins.lobe-user-interaction.description": "طرح الأسئلة على المستخدمين عبر تفاعلات الواجهة ومتابعة نتائج دورة حياتهم",
"tools.builtins.lobe-user-interaction.title": "تفاعل المستخدم",
"tools.builtins.lobe-user-memory.description": "أنشئ قاعدة معرفة مخصصة عنك. تذكّر التفضيلات، وتتبع الأنشطة والتجارب، واحفظ معلومات الهوية، واسترجع السياق المناسب في المحادثات المستقبلية.",
diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.json
index 511e83b8f9c..fadcfcf5000 100644
--- a/locales/bg-BG/setting.json
+++ b/locales/bg-BG/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Умения",
"tools.builtins.lobe-task.description": "Създаване, изброяване, редактиране и изтриване на задачи с зависимости и настройки за преглед",
"tools.builtins.lobe-task.title": "Инструменти за задачи",
- "tools.builtins.lobe-topic-reference.description": "Извличане на контекст от свързани тематични разговори",
- "tools.builtins.lobe-topic-reference.title": "Тематична препратка",
"tools.builtins.lobe-user-interaction.description": "Задаване на въпроси на потребителите чрез UI взаимодействия и проследяване на техните резултати",
"tools.builtins.lobe-user-interaction.title": "Взаимодействие с потребителя",
"tools.builtins.lobe-user-memory.description": "Изградете персонализирана база знания за вас. Запомняйте предпочитания, следете дейности и преживявания, съхранявайте информация за идентичност и извличайте релевантен контекст в бъдещи разговори.",
diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.json
index 45cdc87a118..44dd68eb550 100644
--- a/locales/de-DE/setting.json
+++ b/locales/de-DE/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Fähigkeiten",
"tools.builtins.lobe-task.description": "Aufgaben mit Abhängigkeiten und Review‑Konfiguration erstellen, auflisten, bearbeiten und löschen",
"tools.builtins.lobe-task.title": "Aufgabentools",
- "tools.builtins.lobe-topic-reference.description": "Kontext aus referenzierten Themenunterhaltungen abrufen",
- "tools.builtins.lobe-topic-reference.title": "Themenreferenz",
"tools.builtins.lobe-user-interaction.description": "Benutzern über UI‑Interaktionen Fragen stellen und deren Ergebnisverläufe beobachten",
"tools.builtins.lobe-user-interaction.title": "Benutzerinteraktion",
"tools.builtins.lobe-user-memory.description": "Erstellen Sie eine personalisierte Wissensdatenbank über sich selbst. Präferenzen merken, Aktivitäten und Erfahrungen verfolgen, Identitätsinformationen speichern und relevanten Kontext in zukünftigen Gesprächen abrufen.",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index dc96300be8c..8ea930a348a 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Skills",
"tools.builtins.lobe-task.description": "Create, schedule, list, edit, and delete tasks with dependencies and review configuration",
"tools.builtins.lobe-task.title": "Task Tools",
- "tools.builtins.lobe-topic-reference.description": "Retrieve context from referenced topic conversations",
- "tools.builtins.lobe-topic-reference.title": "Topic Reference",
"tools.builtins.lobe-user-interaction.description": "Ask users questions through UI interactions and observe their lifecycle outcomes",
"tools.builtins.lobe-user-interaction.title": "User Interaction",
"tools.builtins.lobe-user-memory.description": "Remember user preferences, activities, and experiences across conversations",
diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.json
index 174e480aa47..8ddf1f42ce9 100644
--- a/locales/es-ES/setting.json
+++ b/locales/es-ES/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Habilidades",
"tools.builtins.lobe-task.description": "Crea, lista, edita y elimina tareas con dependencias y configuración de revisión",
"tools.builtins.lobe-task.title": "Herramientas de Tareas",
- "tools.builtins.lobe-topic-reference.description": "Recupera contexto de conversaciones de temas referenciados",
- "tools.builtins.lobe-topic-reference.title": "Referencia de Temas",
"tools.builtins.lobe-user-interaction.description": "Realiza preguntas a los usuarios mediante interacciones de la interfaz y observa los resultados de su ciclo de vida",
"tools.builtins.lobe-user-interaction.title": "Interacción con el Usuario",
"tools.builtins.lobe-user-memory.description": "Construye una base de conocimiento personalizada sobre ti. Recuerda preferencias, realiza seguimiento de actividades y experiencias, almacena información de identidad y recupera contexto relevante en futuras conversaciones.",
diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.json
index 692c814bc1e..bd19056ebee 100644
--- a/locales/fa-IR/setting.json
+++ b/locales/fa-IR/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "مهارت‌ها",
"tools.builtins.lobe-task.description": "ایجاد، فهرست، ویرایش و حذف وظایف با وابستگی‌ها و پیکربندی بازبینی",
"tools.builtins.lobe-task.title": "ابزارهای وظیفه",
- "tools.builtins.lobe-topic-reference.description": "بازیابی زمینه از گفتگوهای موضوعی مرجع‌شده",
- "tools.builtins.lobe-topic-reference.title": "مرجع موضوع",
"tools.builtins.lobe-user-interaction.description": "پرسیدن سؤال از کاربران از طریق تعاملات UI و مشاهده نتایج چرخه عمر آنها",
"tools.builtins.lobe-user-interaction.title": "تعامل کاربر",
"tools.builtins.lobe-user-memory.description": "ساخت پایگاه دانش شخصی درباره شما. به خاطر سپردن ترجیحات، پیگیری فعالیت‌ها و تجربیات، ذخیره اطلاعات هویتی و یادآوری زمینه‌های مرتبط در گفتگوهای آینده.",
diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.json
index 1da221499d1..92445b0d07d 100644
--- a/locales/fr-FR/setting.json
+++ b/locales/fr-FR/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Compétences",
"tools.builtins.lobe-task.description": "Créer, lister, modifier et supprimer des tâches avec dépendances et configuration de révision",
"tools.builtins.lobe-task.title": "Outils de Tâches",
- "tools.builtins.lobe-topic-reference.description": "Récupérer le contexte depuis des conversations de sujets référencés",
- "tools.builtins.lobe-topic-reference.title": "Référence de Sujet",
"tools.builtins.lobe-user-interaction.description": "Poser des questions aux utilisateurs via des interactions d’interface et observer leurs résultats",
"tools.builtins.lobe-user-interaction.title": "Interaction Utilisateur",
"tools.builtins.lobe-user-memory.description": "Créez une base de connaissances personnalisée à votre sujet. Mémorisez vos préférences, suivez vos activités et expériences, stockez des informations d'identité et retrouvez le contexte pertinent dans de futures conversations.",
diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.json
index c4fcfb5b16c..fc6851923a5 100644
--- a/locales/it-IT/setting.json
+++ b/locales/it-IT/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Skill",
"tools.builtins.lobe-task.description": "Crea, elenca, modifica e cancella attività con dipendenze e configurazione di revisione",
"tools.builtins.lobe-task.title": "Strumenti di Attività",
- "tools.builtins.lobe-topic-reference.description": "Recupera contesto da conversazioni su argomenti di riferimento",
- "tools.builtins.lobe-topic-reference.title": "Riferimento Argomenti",
"tools.builtins.lobe-user-interaction.description": "Poni domande agli utenti tramite interazioni UI e osservane gli esiti",
"tools.builtins.lobe-user-interaction.title": "Interazione Utente",
"tools.builtins.lobe-user-memory.description": "Ricorda preferenze, attività ed esperienze dell'utente nelle conversazioni",
diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.json
index 398be55ab35..88259030a99 100644
--- a/locales/ja-JP/setting.json
+++ b/locales/ja-JP/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "スキル",
"tools.builtins.lobe-task.description": "依存関係とレビュー設定を備えたタスクの作成、一覧、編集、削除を行います",
"tools.builtins.lobe-task.title": "タスクツール",
- "tools.builtins.lobe-topic-reference.description": "参照されたトピック会話からコンテキストを取得します",
- "tools.builtins.lobe-topic-reference.title": "トピック参照",
"tools.builtins.lobe-user-interaction.description": "UI を通じてユーザーへ質問し、そのライフサイクル結果を観察します",
"tools.builtins.lobe-user-interaction.title": "ユーザーインタラクション",
"tools.builtins.lobe-user-memory.description": "あなたに関するパーソナライズされたナレッジベースを構築します。好みを記憶し、活動や体験を追跡し、個人情報を保存して、将来の会話で関連するコンテキストを呼び出します。",
diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.json
index 263a4a489a3..872254ce6dd 100644
--- a/locales/ko-KR/setting.json
+++ b/locales/ko-KR/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "스킬",
"tools.builtins.lobe-task.description": "의존성과 검토 설정이 포함된 작업을 생성, 목록 조회, 편집, 삭제합니다",
"tools.builtins.lobe-task.title": "작업 도구",
- "tools.builtins.lobe-topic-reference.description": "참조된 주제 대화에서 컨텍스트를 가져옵니다",
- "tools.builtins.lobe-topic-reference.title": "토픽 참조",
"tools.builtins.lobe-user-interaction.description": "UI 상호작용을 통해 사용자에게 질문하고 그 결과를 관찰합니다",
"tools.builtins.lobe-user-interaction.title": "사용자 상호작용",
"tools.builtins.lobe-user-memory.description": "사용자의 선호도, 활동 및 경험을 대화 전반에 걸쳐 기억",
diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.json
index ea0810859c9..d0844c4b27a 100644
--- a/locales/nl-NL/setting.json
+++ b/locales/nl-NL/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Skills",
"tools.builtins.lobe-task.description": "Maak, lijst, bewerk en verwijder taken met afhankelijkheden en reviewconfiguratie",
"tools.builtins.lobe-task.title": "Task‑tools",
- "tools.builtins.lobe-topic-reference.description": "Haal context op uit gelinkte onderwerpconversaties",
- "tools.builtins.lobe-topic-reference.title": "Onderwerpverwijzing",
"tools.builtins.lobe-user-interaction.description": "Stel gebruikers vragen via UI‑interacties en observeer hun levenscyclusresultaten",
"tools.builtins.lobe-user-interaction.title": "Gebruikersinteractie",
"tools.builtins.lobe-user-memory.description": "Bouw een gepersonaliseerde kennisbasis over jezelf. Onthoud voorkeuren, houd activiteiten en ervaringen bij, sla identiteitsinformatie op en herinner relevante context in toekomstige gesprekken.",
diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.json
index 4759b930a64..73b4e76eaf5 100644
--- a/locales/pl-PL/setting.json
+++ b/locales/pl-PL/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Umiejętności",
"tools.builtins.lobe-task.description": "Twórz, wyświetlaj, edytuj i usuwaj zadania z zależnościami i konfiguracją przeglądu",
"tools.builtins.lobe-task.title": "Narzędzia Zadań",
- "tools.builtins.lobe-topic-reference.description": "Pobieraj kontekst z rozmów przypisanych do określonych tematów",
- "tools.builtins.lobe-topic-reference.title": "Odwołanie do Tematu",
"tools.builtins.lobe-user-interaction.description": "Zadawaj użytkownikom pytania poprzez interakcje w interfejsie i obserwuj ich wyniki",
"tools.builtins.lobe-user-interaction.title": "Interakcja z Użytkownikiem",
"tools.builtins.lobe-user-memory.description": "Buduj spersonalizowaną bazę wiedzy o sobie. Zapamiętuj preferencje, śledź aktywności i doświadczenia, przechowuj informacje tożsamościowe i przywołuj istotny kontekst w przyszłych rozmowach.",
diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.json
index 6dbb1d1066f..e6c5a4dac96 100644
--- a/locales/pt-BR/setting.json
+++ b/locales/pt-BR/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Habilidades",
"tools.builtins.lobe-task.description": "Crie, liste, edite e exclua tarefas com dependências e configuração de revisão",
"tools.builtins.lobe-task.title": "Ferramentas de Tarefas",
- "tools.builtins.lobe-topic-reference.description": "Recupere contexto de conversas em tópicos referenciados",
- "tools.builtins.lobe-topic-reference.title": "Referência de Tópico",
"tools.builtins.lobe-user-interaction.description": "Faça perguntas aos usuários através de interações na interface e acompanhe os resultados",
"tools.builtins.lobe-user-interaction.title": "Interação com o Usuário",
"tools.builtins.lobe-user-memory.description": "Construa uma base de conhecimento personalizada sobre você. Lembre preferências, acompanhe atividades e experiências, armazene informações de identidade e recupere contextos relevantes em conversas futuras.",
diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.json
index c1dd1108a88..31d9213e65a 100644
--- a/locales/ru-RU/setting.json
+++ b/locales/ru-RU/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Навыки",
"tools.builtins.lobe-task.description": "Создание, список, редактирование и удаление задач с зависимостями и настройками проверки",
"tools.builtins.lobe-task.title": "Инструменты задач",
- "tools.builtins.lobe-topic-reference.description": "Получение контекста из связанных тематических бесед",
- "tools.builtins.lobe-topic-reference.title": "Тематические ссылки",
"tools.builtins.lobe-user-interaction.description": "Задавайте вопросы пользователям через UI‑взаимодействие и отслеживайте результаты",
"tools.builtins.lobe-user-interaction.title": "Взаимодействие с пользователем",
"tools.builtins.lobe-user-memory.description": "Создайте персонализированную базу знаний о себе. Запоминайте предпочтения, отслеживайте действия и события, сохраняйте информацию о личности и вспоминайте важный контекст в будущих беседах.",
diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.json
index b9e9078d9fb..b6c573ffc7a 100644
--- a/locales/tr-TR/setting.json
+++ b/locales/tr-TR/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Beceri",
"tools.builtins.lobe-task.description": "Bağımlılıkları ve inceleme yapılandırması olan görevler oluşturun, listeleyin, düzenleyin ve silin",
"tools.builtins.lobe-task.title": "Görev Araçları",
- "tools.builtins.lobe-topic-reference.description": "Referanslanan konu konuşmalarından bağlam alın",
- "tools.builtins.lobe-topic-reference.title": "Konu Referansı",
"tools.builtins.lobe-user-interaction.description": "Kullanıcılara arayüz etkileşimleriyle sorular sorun ve yaşam döngüsü sonuçlarını gözlemleyin",
"tools.builtins.lobe-user-interaction.title": "Kullanıcı Etkileşimi",
"tools.builtins.lobe-user-memory.description": "Kullanıcı tercihlerini, etkinliklerini ve deneyimlerini konuşmalar arasında hatırlayın",
diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.json
index b9c25653f5a..1ab8d98024b 100644
--- a/locales/vi-VN/setting.json
+++ b/locales/vi-VN/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "Kỹ Năng",
"tools.builtins.lobe-task.description": "Tạo, liệt kê, chỉnh sửa và xóa tác vụ với cấu hình phụ thuộc và rà soát",
"tools.builtins.lobe-task.title": "Công Cụ Tác Vụ",
- "tools.builtins.lobe-topic-reference.description": "Truy xuất ngữ cảnh từ các cuộc hội thoại theo chủ đề được tham chiếu",
- "tools.builtins.lobe-topic-reference.title": "Tham Chiếu Chủ Đề",
"tools.builtins.lobe-user-interaction.description": "Đặt câu hỏi cho người dùng thông qua tương tác giao diện và theo dõi kết quả của chúng",
"tools.builtins.lobe-user-interaction.title": "Tương Tác Người Dùng",
"tools.builtins.lobe-user-memory.description": "Xây dựng cơ sở kiến thức cá nhân hóa về bạn. Ghi nhớ sở thích, theo dõi hoạt động và trải nghiệm, lưu trữ thông tin nhận dạng và gợi nhớ ngữ cảnh liên quan trong các cuộc trò chuyện sau.",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index bbdc27b31d7..6138277029a 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "技能",
"tools.builtins.lobe-task.description": "创建、调度、列出、编辑和删除任务,支持依赖关系和审核配置",
"tools.builtins.lobe-task.title": "任务工具",
- "tools.builtins.lobe-topic-reference.description": "从被引用的话题对话中检索上下文",
- "tools.builtins.lobe-topic-reference.title": "话题引用",
"tools.builtins.lobe-user-interaction.description": "通过界面交互向用户提问,并观察其生命周期结果",
"tools.builtins.lobe-user-interaction.title": "用户交互",
"tools.builtins.lobe-user-memory.description": "记住用户的偏好、活动和经历",
diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.json
index f50bb246111..9fb6c21f6fe 100644
--- a/locales/zh-TW/setting.json
+++ b/locales/zh-TW/setting.json
@@ -1851,8 +1851,6 @@
"tools.builtins.lobe-skills.title": "技能",
"tools.builtins.lobe-task.description": "建立、列出、編輯與刪除具有相依性與審查設定的任務",
"tools.builtins.lobe-task.title": "任務工具",
- "tools.builtins.lobe-topic-reference.description": "從被引用的主題對話中擷取上下文",
- "tools.builtins.lobe-topic-reference.title": "主題參考",
"tools.builtins.lobe-user-interaction.description": "透過 UI 互動向使用者提問並觀察其操作流程結果",
"tools.builtins.lobe-user-interaction.title": "使用者互動",
"tools.builtins.lobe-user-memory.description": "建立關於您的個人化知識庫。記住偏好設定、追蹤活動與經歷、儲存身份資訊,並在未來對話中回憶相關背景。",
diff --git a/package.json b/package.json
index b4f2076c5ad..b1fdd1c9618 100644
--- a/package.json
+++ b/package.json
@@ -269,7 +269,6 @@
"@lobechat/builtin-tool-skill-store": "workspace:*",
"@lobechat/builtin-tool-skills": "workspace:*",
"@lobechat/builtin-tool-task": "workspace:*",
- "@lobechat/builtin-tool-topic-reference": "workspace:*",
"@lobechat/builtin-tool-user-interaction": "workspace:*",
"@lobechat/builtin-tool-verify": "workspace:*",
"@lobechat/builtin-tool-video-generation": "workspace:*",
diff --git a/packages/builtin-skills/src/lobehub/manifest.ts b/packages/builtin-skills/src/lobehub/manifest.ts
index ce9ba32d0c9..f6840bb932b 100644
--- a/packages/builtin-skills/src/lobehub/manifest.ts
+++ b/packages/builtin-skills/src/lobehub/manifest.ts
@@ -9,7 +9,7 @@ const LOBEHUB_AVATAR =
export const LobeHubManifest: BuiltinSkillManifest = {
avatar: LOBEHUB_AVATAR,
description:
- "Manage the LobeHub platform via the `lh` CLI — INCLUDING modifying THIS agent's own configuration. ACTIVATE this skill whenever the user asks you to: change your system prompt / instructions / persona, enable or disable tools / plugins / skills, switch model or provider, attach knowledge bases or files, edit the opening message, rename the topic, OR operate on any other platform resource (agents, topics, memory, documents, search, content generation, model/provider/plugin management, bot integrations, evals, usage stats). ALSO ACTIVATE when the user asks to connect, link, or set up a messaging platform bot — including Discord, Telegram, Slack, Feishu (飞书), Lark, QQ, or WeChat (微信) — or uses phrases like '帮我链接 Discord', 'connect my Slack', '接入飞书', '配置 QQ 机器人', 'link WeChat'. Without activation you cannot persist any change — you can only describe what you would do.",
+ "Read and change LobeHub platform data through the `lh` CLI, including this agent's own configuration. ACTIVATE when the user wants to: (1) change this agent — system prompt / persona, tools / plugins / skills, model or provider, knowledge bases or files, opening message, or topic title; (2) work with any platform resource — agents, topics, messages, memory, documents, knowledge bases, files, search, content generation, models / providers / plugins, evals, usage stats; (3) connect a chat-platform bot — Discord, Telegram, Slack, Feishu (飞书), Lark, QQ, WeChat (微信), e.g. '接入飞书', 'connect my Slack'; (4) read another conversation — the message contains a topic id (`tpc_…`) or a `<refer_topic>` tag. Without activation you cannot read or change platform data; you can only describe what you would do.",
identifier: LobeHubIdentifier,
name: 'lobehub',
source: 'builtin',
diff --git a/packages/builtin-skills/src/lobehub/references/topic.ts b/packages/builtin-skills/src/lobehub/references/topic.ts
index ef6347e93cd..fa56814ec7a 100644
--- a/packages/builtin-skills/src/lobehub/references/topic.ts
+++ b/packages/builtin-skills/src/lobehub/references/topic.ts
@@ -17,6 +17,7 @@ Manage conversation topics (chat sessions).
- Topics are associated with agents; use \`--agent-id\` to filter
- Use \`--json\` for structured output suitable for piping
- \`lh topic view\` shows 50 messages per page by default; page with \`--from\` / \`--to\`, or \`--no-messages\` for metadata only
+- Topic ids start with \`tpc_\`. When the user pastes one, or a \`<refer_topic>\` tag carries one in its \`id\` attribute, read that conversation with \`lh topic view <id>\` (page long topics with \`--from\` / \`--to\`)
- When the prompt injects a \`<recent_topics>\` block (IM channels without a history-read API), use the \`id\` attribute with \`lh topic view <id>\` to read that session's full conversation
`;
diff --git a/packages/builtin-tool-topic-reference/package.json b/packages/builtin-tool-topic-reference/package.json
deleted file mode 100644
index 1fb9ca4016d..00000000000
--- a/packages/builtin-tool-topic-reference/package.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "name": "@lobechat/builtin-tool-topic-reference",
- "version": "1.0.0",
- "private": true,
- "exports": {
- ".": "./src/index.ts",
- "./executor": "./src/executor/index.ts"
- },
- "main": "./src/index.ts",
- "devDependencies": {
- "@lobechat/types": "workspace:*"
- }
-}
diff --git a/packages/builtin-tool-topic-reference/src/executor/index.ts b/packages/builtin-tool-topic-reference/src/executor/index.ts
deleted file mode 100644
index 8b930f1bfb7..00000000000
--- a/packages/builtin-tool-topic-reference/src/executor/index.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
-import { BaseExecutor } from '@lobechat/types';
-
-import { TopicReferenceIdentifier } from '../types';
-
-const TopicReferenceApiName = {
- getTopicContext: 'getTopicContext',
-} as const;
-
-interface GetTopicContextParams {
- topicId: string;
-}
-
-interface TopicReferenceExecutionRuntime {
- getTopicContext: (params: GetTopicContextParams) => Promise<BuiltinToolResult>;
-}
-
-export class TopicReferenceExecutor extends BaseExecutor<typeof TopicReferenceApiName> {
- readonly identifier = TopicReferenceIdentifier;
- protected readonly apiEnum = TopicReferenceApiName;
- private runtime: TopicReferenceExecutionRuntime;
-
- constructor(runtime: TopicReferenceExecutionRuntime) {
- super();
- this.runtime = runtime;
- }
-
- getTopicContext = async (
- params: GetTopicContextParams,
- _ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- return this.runtime.getTopicContext(params);
- };
-}
diff --git a/packages/builtin-tool-topic-reference/src/index.ts b/packages/builtin-tool-topic-reference/src/index.ts
deleted file mode 100644
index 7d26beed34f..00000000000
--- a/packages/builtin-tool-topic-reference/src/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export { TopicReferenceManifest } from './manifest';
-export {
- TopicReferenceApiName,
- type TopicReferenceApiNameType,
- TopicReferenceIdentifier,
-} from './types';
diff --git a/packages/builtin-tool-topic-reference/src/manifest.ts b/packages/builtin-tool-topic-reference/src/manifest.ts
deleted file mode 100644
index 0fc30807e25..00000000000
--- a/packages/builtin-tool-topic-reference/src/manifest.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { type BuiltinToolManifest } from '@lobechat/types';
-
-import { TopicReferenceApiName, TopicReferenceIdentifier } from './types';
-
-export const TopicReferenceManifest: BuiltinToolManifest = {
- api: [
- {
- description:
- 'Retrieve context from a referenced topic conversation. Returns the topic summary if available, otherwise returns the most recent messages. Use this when you see a topic reference tag in the user message and need to understand what was discussed in that topic.',
- name: TopicReferenceApiName.getTopicContext,
- parameters: {
- additionalProperties: false,
- properties: {
- topicId: {
- description: 'The ID of the topic to retrieve context from',
- type: 'string',
- },
- },
- required: ['topicId'],
- type: 'object',
- },
- },
- ],
- identifier: TopicReferenceIdentifier,
- meta: {
- avatar: '📋',
- description: 'Retrieve context from referenced topic conversations',
- title: 'Topic Reference',
- },
- systemRole: '',
- type: 'builtin',
-};
diff --git a/packages/builtin-tool-topic-reference/src/types.ts b/packages/builtin-tool-topic-reference/src/types.ts
deleted file mode 100644
index 9d1f3b27b73..00000000000
--- a/packages/builtin-tool-topic-reference/src/types.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export const TopicReferenceIdentifier = 'lobe-topic-reference';
-
-export const TopicReferenceApiName = {
- getTopicContext: 'getTopicContext',
-} as const;
-
-export type TopicReferenceApiNameType =
- (typeof TopicReferenceApiName)[keyof typeof TopicReferenceApiName];
diff --git a/packages/builtin-tool-topic-reference/tsconfig.json b/packages/builtin-tool-topic-reference/tsconfig.json
deleted file mode 100644
index cf07830f64d..00000000000
--- a/packages/builtin-tool-topic-reference/tsconfig.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "ESNext",
- "moduleResolution": "node",
- "declaration": true,
- "outDir": "dist",
- "rootDir": "src",
- "strict": true,
- "skipLibCheck": true,
- "esModuleInterop": true,
- "allowSyntheticDefaultImports": true,
- "forceConsistentCasingInFileNames": true,
- "resolveJsonModule": true
- },
- "exclude": ["node_modules"],
- "include": ["src/**/*"]
-}
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index b348fb5d744..008b2bfa687 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -53,7 +53,6 @@
"@lobechat/builtin-tool-skill-store": "workspace:*",
"@lobechat/builtin-tool-skills": "workspace:*",
"@lobechat/builtin-tool-task": "workspace:*",
- "@lobechat/builtin-tool-topic-reference": "workspace:*",
"@lobechat/builtin-tool-user-interaction": "workspace:*",
"@lobechat/builtin-tool-verify": "workspace:*",
"@lobechat/builtin-tool-video-generation": "workspace:*",
diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.ts
index 60e15e6b6c4..c64a28624ef 100644
--- a/packages/builtin-tools/src/identifiers.ts
+++ b/packages/builtin-tools/src/identifiers.ts
@@ -33,7 +33,6 @@ import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';
import { selfFeedbackIntentManifest } from '@lobechat/builtin-tool-self-iteration';
import { SkillStoreManifest } from '@lobechat/builtin-tool-skill-store';
import { SkillsManifest } from '@lobechat/builtin-tool-skills';
-import { TopicReferenceManifest } from '@lobechat/builtin-tool-topic-reference';
import { UserInteractionManifest } from '@lobechat/builtin-tool-user-interaction';
import { VerifyToolManifest } from '@lobechat/builtin-tool-verify';
import { VideoGenerationManifest } from '@lobechat/builtin-tool-video-generation';
@@ -71,7 +70,6 @@ export const builtinToolIdentifiers: string[] = [
agentSignalSkillManagementManifest.identifier,
SkillsManifest.identifier,
SkillStoreManifest.identifier,
- TopicReferenceManifest.identifier,
LobeActivatorManifest.identifier,
WebBrowsingManifest.identifier,
UserInteractionManifest.identifier,
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index d7db39a42ea..9fc8c95f12f 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -50,7 +50,6 @@ import {
SkillsManifest,
} from '@lobechat/builtin-tool-skills';
import { TaskManifest } from '@lobechat/builtin-tool-task';
-import { TopicReferenceManifest } from '@lobechat/builtin-tool-topic-reference';
import { UserInteractionManifest } from '@lobechat/builtin-tool-user-interaction';
import { VerifyToolManifest } from '@lobechat/builtin-tool-verify';
import { VideoGenerationManifest } from '@lobechat/builtin-tool-video-generation';
@@ -74,7 +73,6 @@ export const defaultToolIds = [
LocalSystemManifest.identifier,
BrowserManifest.identifier,
CloudSandboxManifest.identifier,
- TopicReferenceManifest.identifier,
AgentDocumentsManifest.identifier,
TaskManifest.identifier,
LobeAgentManifest.identifier,
@@ -228,8 +226,7 @@ export const runtimeManagedToolIds = [
* `lobe-skill-store`, `lobe-agent-builder`,
* `lobe-group-agent-builder`, `lobe-group-management`, `agent-signal-review`,
* `lobe-user-interaction`,
- * `lobe-local-system`, `lobe-browser`, `lobe-remote-device`,
- * `lobe-topic-reference`, and the hidden system-only self-iteration tools),
+ * `lobe-local-system`, `lobe-browser`, `lobe-remote-device`, and the hidden system-only self-iteration tools),
* see the denied-builtins section of
* `apps/server/src/services/aiAgent/shareGate/README.md`.
*/
@@ -520,13 +517,6 @@ const builtinToolRegistry: LobeBuiltinTool[] = [
manifest: RemoteDeviceManifest,
type: 'builtin',
},
- {
- discoverable: false,
- hidden: true,
- identifier: TopicReferenceManifest.identifier,
- manifest: TopicReferenceManifest,
- type: 'builtin',
- },
{
discoverable: false,
hidden: true,
diff --git a/packages/context-engine/src/engine/topicReference/__tests__/resolveTopicReferences.test.ts b/packages/context-engine/src/engine/topicReference/__tests__/resolveTopicReferences.test.ts
index 2faa4a12597..719c3ad469e 100644
--- a/packages/context-engine/src/engine/topicReference/__tests__/resolveTopicReferences.test.ts
+++ b/packages/context-engine/src/engine/topicReference/__tests__/resolveTopicReferences.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it, vi } from 'vitest';
-import { parseReferTopicTags, resolveTopicReferences } from '../resolveTopicReferences';
+import {
+ mentionsTopic,
+ parseReferTopicTags,
+ resolveTopicReferences,
+} from '../resolveTopicReferences';
// ============ parseReferTopicTags ============
@@ -276,3 +280,23 @@ describe('resolveTopicReferences', () => {
expect(result![0].recentMessages).toBeUndefined();
});
});
+
+describe('mentionsTopic', () => {
+ it('detects a <refer_topic> tag', () => {
+ expect(mentionsTopic([{ content: '<refer_topic name="Plan" id="topic-1" />\nGo on' }])).toBe(
+ true,
+ );
+ });
+
+ it.each([
+ 'tpc_AbCdEf123456 read this and rewrite the outline',
+ 'read (tpc_AbCdEf123456) first',
+ 'read tpc\\_AbCdEf123456 first',
+ ])('detects a raw topic id in %s', (content) => {
+ expect(mentionsTopic([{ content }])).toBe(true);
+ });
+
+ it.each(['no topic here', 'mytpc_AbCdEf123456', 'tpc_short', 'tpc_'])('ignores %s', (content) => {
+ expect(mentionsTopic([{ content }])).toBe(false);
+ });
+});
diff --git a/packages/context-engine/src/engine/topicReference/index.ts b/packages/context-engine/src/engine/topicReference/index.ts
index aa68fcca34a..0782b8f2b1e 100644
--- a/packages/context-engine/src/engine/topicReference/index.ts
+++ b/packages/context-engine/src/engine/topicReference/index.ts
@@ -3,4 +3,8 @@ export type {
TopicLookupResult,
TopicMessageItem,
} from './resolveTopicReferences';
-export { parseReferTopicTags, resolveTopicReferences } from './resolveTopicReferences';
+export {
+ mentionsTopic,
+ parseReferTopicTags,
+ resolveTopicReferences,
+} from './resolveTopicReferences';
diff --git a/packages/context-engine/src/engine/topicReference/resolveTopicReferences.ts b/packages/context-engine/src/engine/topicReference/resolveTopicReferences.ts
index 71a1abd49ec..551bdb5ef48 100644
--- a/packages/context-engine/src/engine/topicReference/resolveTopicReferences.ts
+++ b/packages/context-engine/src/engine/topicReference/resolveTopicReferences.ts
@@ -29,6 +29,21 @@ const MAX_RECENT_MESSAGES = 5;
/** Max characters per message content */
const MAX_MESSAGE_LENGTH = 300;
+const RAW_TOPIC_ID = /(?:^|\W)tpc_[\dA-Za-z]{8,}(?![\dA-Za-z])/;
+
+/**
+ * Whether the messages point at another topic, either through a `<refer_topic>`
+ * tag or a raw `tpc_` topic id the user pasted.
+ */
+export function mentionsTopic(messages: Array<{ content: string | unknown }>): boolean {
+ if (parseReferTopicTags(messages).length > 0) return true;
+
+ return messages.some((msg) => {
+ const raw = typeof msg.content === 'string' ? msg.content : '';
+ return RAW_TOPIC_ID.test(raw.replaceAll('\\_', '_'));
+ });
+}
+
/**
* Parse <refer_topic> tags from message contents
*/
diff --git a/packages/context-engine/src/providers/TopicReferenceContextInjector.ts b/packages/context-engine/src/providers/TopicReferenceContextInjector.ts
index cfe7ea7ee61..01da5842d8e 100644
--- a/packages/context-engine/src/providers/TopicReferenceContextInjector.ts
+++ b/packages/context-engine/src/providers/TopicReferenceContextInjector.ts
@@ -35,7 +35,7 @@ export interface TopicReferenceContextInjectorConfig {
/**
* Format topic references for injection
- * Topics with summaries are inlined; topics without summaries prompt the agent to use the tool
+ * Topics with summaries are inlined; topics without summaries prompt the agent to read them via `lh topic view`
*/
function formatRecentMessages(messages: Array<{ content: string; role: string }>): string {
return messages
@@ -53,7 +53,7 @@ function formatTopicReferences(items: TopicReferenceItem[]): string | null {
const withoutContext = items.filter((item) => !item.summary && !item.recentMessages?.length);
const lines: string[] = [
- '<referred_topics hint="The following are brief summaries or excerpts of referenced topics. For complete conversation history, use the getTopicContext tool.">',
+ '<referred_topics hint="The following are brief summaries or excerpts of referenced topics. For the complete conversation history, activate the lobehub skill and run `lh topic view` with the topic id.">',
];
for (const item of withContext) {
@@ -70,7 +70,7 @@ function formatTopicReferences(items: TopicReferenceItem[]): string | null {
if (withoutContext.length > 0) {
lines.push(
- '<pending_topics hint="No context available for the following topics. Use the getTopicContext tool to retrieve their conversation history.">',
+ '<pending_topics hint="No context available for the following topics. Activate the lobehub skill and run `lh topic view` with the topic id to read their conversation history.">',
);
for (const item of withoutContext) {
const title = item.topicTitle ? ` title="${item.topicTitle}"` : '';
@@ -90,7 +90,7 @@ function formatTopicReferences(items: TopicReferenceItem[]): string | null {
* When user messages contain <refer_topic> tags referencing other topics,
* this injector appends the referenced topics' context to the last user message.
* - Topics with summaries: summary is inlined directly
- * - Topics without summaries: a hint is added prompting the agent to call the getTopicContext tool
+ * - Topics without summaries: a hint is added prompting the agent to read them via `lh topic view`
*/
export class TopicReferenceContextInjector extends BaseLastUserContentProvider {
readonly name = 'TopicReferenceContextInjector';
diff --git a/packages/context-engine/src/providers/__tests__/TopicReferenceContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/TopicReferenceContextInjector.test.ts
index ab7f5c7c39a..3f2e986a211 100644
--- a/packages/context-engine/src/providers/__tests__/TopicReferenceContextInjector.test.ts
+++ b/packages/context-engine/src/providers/__tests__/TopicReferenceContextInjector.test.ts
@@ -63,7 +63,8 @@ describe('TopicReferenceContextInjector', () => {
expect(result.messages).toHaveLength(3);
const lastContent = result.messages[2].content as string;
expect(lastContent).toContain('<referred_topics hint=');
- expect(lastContent).toContain('getTopicContext tool');
+ expect(lastContent).toContain('lh topic view');
+ expect(lastContent).not.toContain('getTopicContext');
expect(lastContent).toContain(
'<topic id="topic-1" title="React Hooks Discussion" type="summary">',
);
@@ -90,7 +91,7 @@ describe('TopicReferenceContextInjector', () => {
const lastContent = result.messages[0].content as string;
expect(lastContent).toContain('<pending_topics');
- expect(lastContent).toContain('getTopicContext');
+ expect(lastContent).toContain('lh topic view');
expect(lastContent).toContain('<topic id="topic-no-summary" title="Old Chat" />');
expect(lastContent).not.toContain('</topic>');
expect(result.metadata.topicReferenceInjected).toBe(true);
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index f052b64a462..3fe5dea59be 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -3756,9 +3756,6 @@ When I am ___, I need ___
'tools.builtins.lobe-task.description':
'Create, schedule, list, edit, and delete tasks with dependencies and review configuration',
'tools.builtins.lobe-task.title': 'Task Tools',
- 'tools.builtins.lobe-topic-reference.description':
- 'Retrieve context from referenced topic conversations',
- 'tools.builtins.lobe-topic-reference.title': 'Topic Reference',
'tools.builtins.lobe-user-interaction.description':
'Ask users questions through UI interactions and observe their lifecycle outcomes',
'tools.builtins.lobe-user-interaction.title': 'User Interaction',
diff --git a/packages/mecha/src/toolSet/skillPool.test.ts b/packages/mecha/src/toolSet/skillPool.test.ts
index 0f74719afbe..159a3a8f4bf 100644
--- a/packages/mecha/src/toolSet/skillPool.test.ts
+++ b/packages/mecha/src/toolSet/skillPool.test.ts
@@ -77,6 +77,25 @@ describe('assembleSkillPool', () => {
).toEqual([AgentBrowserIdentifier, 'artifacts']);
});
+ it('keeps a turn skill selectable in manual mode without pinning it', () => {
+ const pool = assembleSkillPool(
+ { builtin: [skill('lobehub'), skill('artifacts')], db: [skill('picked')] },
+ { enabledPluginIds: ['picked'], skillActivateMode: 'manual', turnSkillIds: ['lobehub'] },
+ );
+
+ expect(pool.skills.map((s) => s.identifier)).toEqual(['picked', 'lobehub']);
+ expect(pool.enabledPluginIds).toEqual(['picked']);
+ });
+
+ it('still lets a share configuration withhold a turn skill', () => {
+ const pool = assembleSkillPool(
+ { builtin: [skill('lobehub')] },
+ { shareAllowedIds: [], skillActivateMode: 'manual', turnSkillIds: ['lobehub'] },
+ );
+
+ expect(pool.skills).toEqual([]);
+ });
+
it('exposes only the selected skills in manual mode, keeping the discovered project ones', () => {
const sources = {
agentSkills: [skill('agent-skills:notes', 'agent-skills:notes')],
diff --git a/packages/mecha/src/toolSet/skillPool.ts b/packages/mecha/src/toolSet/skillPool.ts
index 297ff751098..5ed0bf2786d 100644
--- a/packages/mecha/src/toolSet/skillPool.ts
+++ b/packages/mecha/src/toolSet/skillPool.ts
@@ -46,6 +46,12 @@ export interface AssembleSkillPoolOptions {
* always-on `lobe-skills` tool and resolves against this pool.
*/
skillActivateMode?: 'auto' | 'manual';
+ /**
+ * Skills this turn needs to stay selectable even in `manual` mode (e.g. the
+ * lobehub skill for a `<refer_topic>` turn). They are not pinned, so their
+ * content is only loaded through `activateSkill`.
+ */
+ turnSkillIds?: readonly string[];
}
/**
@@ -61,13 +67,16 @@ export const assembleSkillPool = (
options: AssembleSkillPoolOptions = {},
): OperationSkillSet => {
const enabledPluginIds = new Set(options.enabledPluginIds ?? []);
+ const turnSkillIds = new Set(options.turnSkillIds ?? []);
// Manual mode exposes only what the user picked. Project / device skills are
// discovered from the run's working directory and can never be picked in the
// UI, so the mode does not speak about them and they stay.
const selectable =
options.skillActivateMode === 'manual'
? (skills: readonly SkillMeta[] = []) =>
- skills.filter((skill) => enabledPluginIds.has(skill.identifier))
+ skills.filter(
+ (skill) => enabledPluginIds.has(skill.identifier) || turnSkillIds.has(skill.identifier),
+ )
: (skills: readonly SkillMeta[] = []) => skills;
const ordered = [
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 31683b7c1e4..6b4b7bfbe72 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -133,8 +133,7 @@ export interface AgentShareVisitorContext {
skillGrants?: string[];
/**
* Mirrors `shareConfig.toolGrants` so tool runtimes that resolve their
- * target outside `toolManifestMap` (e.g. `activateSkill`,
- * `lobe-topic-reference`) can apply the same allowlist the assembled tool set
+ * target outside `toolManifestMap` (e.g. `activateSkill`) can apply the same allowlist the assembled tool set
* already enforces.
*/
toolGrants?: AgentShareToolGrant[];
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 4bb6d723db5..e1ffb569f11 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -1,3 +1,4 @@
+import { LobeHubIdentifier } from '@lobechat/builtin-skills/manifests';
import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';
import { isDesktop } from '@lobechat/const';
@@ -9,6 +10,7 @@ import type {
ToolDiscoveryConfig,
UserMemoryData,
} from '@lobechat/context-engine';
+import { mentionsTopic } from '@lobechat/context-engine';
import { type ContextSnapshot, gatherContextFacts, runContextEngineering } from '@lobechat/mecha';
import { historySummaryPrompt } from '@lobechat/prompts';
import {
@@ -298,6 +300,9 @@ export const contextEngineering = async ({
plugins,
disabledPluginIds,
agentChatConfigSelectors.skillActivateMode(agentStoreState),
+ // Reading another topic (`<refer_topic>` or a raw `tpc_` id) goes through `lh topic view`,
+ // which the lobehub skill teaches.
+ mentionsTopic(messages) ? [LobeHubIdentifier] : undefined,
)
).skills;
}
diff --git a/src/services/chat/mecha/skillEngineering.test.ts b/src/services/chat/mecha/skillEngineering.test.ts
index 3309498c382..afa803b0138 100644
--- a/src/services/chat/mecha/skillEngineering.test.ts
+++ b/src/services/chat/mecha/skillEngineering.test.ts
@@ -197,6 +197,24 @@ describe('resolveClientSkills', () => {
expect(skill?.activated).toBeFalsy();
});
+ it('keeps a turn skill selectable in manual mode without pinning it', async () => {
+ setToolState({
+ builtinSkills: [
+ {
+ content: '<lh_guide />',
+ description: 'LobeHub CLI',
+ identifier: 'lobehub',
+ name: 'lobehub',
+ },
+ ],
+ });
+
+ const result = await resolveClientSkills([], [], 'manual', ['lobehub']);
+
+ expect(result.enabledPluginIds).toEqual([]);
+ expect(findSkill(result.skills, 'lobehub')).toMatchObject({ activated: false });
+ });
+
describe('disabled skills', () => {
it('excludes a disabled DB skill entirely, not just from the pinned set', async () => {
setToolState({
diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.ts
index 6733c4530f4..f91840ad731 100644
--- a/src/services/chat/mecha/skillEngineering.ts
+++ b/src/services/chat/mecha/skillEngineering.ts
@@ -46,6 +46,8 @@ export const resolveClientSkills = async (
pluginIds?: string[],
disabledIds?: string[],
skillActivateMode?: 'auto' | 'manual',
+ /** Selectable for this turn even in manual mode, without being pinned. */
+ turnSkillIds?: string[],
): Promise<OperationSkillSet> => {
const toolState = getToolStoreState();
const pinnedIds = new Set(pluginIds ?? []);
@@ -116,6 +118,7 @@ export const resolveClientSkills = async (
canExecuteOnDevice: isDesktop,
enabledPluginIds: pluginIds,
skillActivateMode,
+ turnSkillIds,
},
);
};
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index fb0604683de..e8695ace5f0 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -93,17 +93,6 @@ const dynamicInterventionAudits = {
}),
};
-const hasReferTopicNode = (editorData: Record<string, any> | null | undefined): boolean => {
- if (!editorData) return false;
- const walk = (node: any): boolean => {
- if (!node) return false;
- if (node.type === 'refer-topic') return true;
- if (Array.isArray(node.children)) return node.children.some(walk);
- return false;
- };
- return walk(editorData.root);
-};
-
const getMediaAvailability = (messages: UIChatMessage[]) => ({
hasAudios: messages.some((message) => message.role === 'user' && !!message.audioList?.length),
hasImages: messages.some((message) => message.role === 'user' && !!message.imageList?.length),
@@ -257,7 +246,6 @@ export class StreamingExecutorActionImpl {
}
// Dynamically inject turn-scoped builtin tools.
- const hasTopicReference = messages.some((m) => hasReferTopicNode(m.editorData));
const mediaAvailability = getMediaAvailability(messages);
const serverConfigState = getServerConfigStoreState();
const multimodalUnderstandingConfigured =
@@ -273,7 +261,6 @@ export class StreamingExecutorActionImpl {
const runtimePluginIds = [
...new Set([
...(pluginIds || []),
- ...(hasTopicReference ? ['lobe-topic-reference'] : []),
...(shouldEnableMultimodalUnderstanding ? [LobeAgentManifest.identifier] : []),
]),
];
@@ -284,11 +271,10 @@ export class StreamingExecutorActionImpl {
: effectivePluginIds;
log(
- '[internal_createAgentState] resolved plugins=%o, isSubAgent=%s, disableTools=%s, hasTopicReference=%s',
+ '[internal_createAgentState] resolved plugins=%o, isSubAgent=%s, disableTools=%s',
effectivePluginIds,
isSubAgent,
disableTools,
- hasTopicReference,
);
// Generate tools using ToolsEngine (centralized here, passed to chatService via agentConfig)
diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.ts
index a40c2940fe3..132fe967e01 100644
--- a/src/store/tool/slices/builtin/executors/catalog.ts
+++ b/src/store/tool/slices/builtin/executors/catalog.ts
@@ -40,7 +40,6 @@ import { notebookExecutor } from './lobe-notebook';
import { pageAgentExecutor } from './lobe-page-agent';
import { skillStoreExecutor } from './lobe-skill-store';
import { skillsExecutor } from './lobe-skills';
-import { topicReferenceExecutor } from './lobe-topic-reference';
import { userInteractionExecutor } from './lobe-user-interaction';
import { webBrowsing } from './lobe-web-browsing';
import { webOnboardingExecutor } from './lobe-web-onboarding';
@@ -87,7 +86,6 @@ export const builtinToolExecutors = [
dashboardExecutor,
videoGenerationExecutor,
activatorExecutor,
- topicReferenceExecutor,
userInteractionExecutor,
lobeAgentExecutor,
webOnboardingExecutor,
diff --git a/src/store/tool/slices/builtin/executors/lobe-topic-reference.ts b/src/store/tool/slices/builtin/executors/lobe-topic-reference.ts
deleted file mode 100644
index 493029b5d59..00000000000
--- a/src/store/tool/slices/builtin/executors/lobe-topic-reference.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { TopicReferenceExecutor } from '@lobechat/builtin-tool-topic-reference/executor';
-import type { BuiltinToolResult } from '@lobechat/types';
-
-import { lambdaClient } from '@/libs/trpc/client';
-
-interface GetTopicContextParams {
- topicId: string;
-}
-
-class TopicReferenceExecutionRuntime {
- getTopicContext = async (params: GetTopicContextParams): Promise<BuiltinToolResult> => {
- const { topicId } = params;
-
- if (!topicId) {
- return { content: 'topicId is required', success: false };
- }
-
- try {
- const result = await lambdaClient.topic.getTopicContext.query({ topicId });
- return { content: result.content, success: result.success };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error);
- return { content: `Failed to fetch topic context: ${errorMessage}`, success: false };
- }
- };
-}
-
-const runtime = new TopicReferenceExecutionRuntime();
-
-export const topicReferenceExecutor = new TopicReferenceExecutor(runtime);