🤯 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(agent-share): enable scoped document authoring (#19720)
YuTengjing6705230b74c4
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.tsindex b1863706ad7..04f3dffb2f2 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -3,7 +3,11 @@ import { formatWebOnboardingStateMessage } from '@lobechat/builtin-tool-web-onboimport { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';import type { ContextFactProviders, ContextFactRequest } from '@lobechat/mecha';-import { getActivePluginIds } from '@lobechat/types';+import {+ agentShareDocumentAccessScope,+ getActivePluginIds,+ ordinaryDocumentAccessScope,+} from '@lobechat/types';import { loadModels } from '@/business/client/model-bank/loadModels';import { composioEnv } from '@/config/composio';@@ -63,6 +67,13 @@ export const createServerContextFactProviders = ({if (!serverDB || !userId) return {};const db = serverDB;const workspaceId = state.origin?.workspaceId ?? ctx.workspaceId;+ const documentAccessScope = ctx.agentShareVisitor+ ? agentShareDocumentAccessScope({+ shareId: ctx.agentShareVisitor.shareId,+ topicId: state.origin?.topicId ?? ctx.topicId ?? '',+ visitorUserId: ctx.agentShareVisitor.visitorUserId,+ })+ : ordinaryDocumentAccessScope;return {findTopic: async (topicId) => {@@ -181,6 +192,8 @@ export const createServerContextFactProviders = ({db,userId,workspaceId,+ undefined,+ documentAccessScope,).getAgentContextDocuments(agentId);return toAgentContextDocuments(docs);},diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.tsindex a83424fc8c5..8995de0cf88 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts@@ -4,15 +4,19 @@ import { describe, expect, it, vi } from 'vitest';import { createServerContextFactProviders } from './index';const {+ agentDocumentsConstructor,credsList,findById,+ getAgentContextDocuments,getInfoForAIGeneration,getUserSettings,loadConnectedComposioIds,pluginQuery,} = vi.hoisted(() => ({+ agentDocumentsConstructor: vi.fn(),credsList: vi.fn(),findById: vi.fn(),+ getAgentContextDocuments: vi.fn(),getInfoForAIGeneration: vi.fn(),getUserSettings: vi.fn(),loadConnectedComposioIds: vi.fn(),@@ -40,6 +44,16 @@ vi.mock('@/database/models/workspace', () => ({vi.mock('@/server/modules/AgentRuntime/adapters/composioConnectedIds', () => ({loadConnectedComposioIds,}));+vi.mock('@/server/services/agentDocuments', () => ({+ AgentDocumentsService: class {+ constructor(...args: unknown[]) {+ agentDocumentsConstructor(...args);+ }++ getAgentContextDocuments = getAgentContextDocuments;+ getDocumentByFilename = vi.fn();+ },+}));vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.test' } }));vi.mock('@/server/services/market', () => ({MarketService: class {@@ -204,4 +218,36 @@ describe('createServerContextFactProviders', () => {slug: undefined,});});++ it('loads Share context documents only from the exact visitor topic scope', async () => {+ getAgentContextDocuments.mockResolvedValue([]);+ const providers = createServerContextFactProviders({+ ctx: {+ agentShareVisitor: {+ agentId: 'agent-1',+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ serverDB: {},+ topicId: 'topic-fallback',+ userId: 'owner-1',+ } as never,+ state: { origin: { topicId: 'topic-1' } } as never,+ });++ await providers.listAgentDocuments!('agent-1');++ expect(agentDocumentsConstructor).toHaveBeenLastCalledWith(+ expect.anything(),+ 'owner-1',+ undefined,+ undefined,+ {+ shareId: 'share-1',+ topicId: 'topic-1',+ type: 'agentShare',+ visitorUserId: 'visitor-1',+ },+ );+ });});diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.tsindex 0056645b01f..8a41a4ebc72 100644--- a/apps/server/src/services/agentDocuments/index.ts+++ b/apps/server/src/services/agentDocuments/index.ts@@ -8,6 +8,8 @@ import { DocumentLoadPosition, getDocumentTemplate, PolicyLoad } from '@lobechatimport { buildAgentSkillIdentifier } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';import { DOCUMENT_FOLDER_TYPE } from '@lobechat/database/schemas';+import type { DocumentAccessScope } from '@lobechat/types';+import { ordinaryDocumentAccessScope } from '@lobechat/types';import type {AgentDocument,@@ -152,13 +154,20 @@ export class AgentDocumentsService {userId: string,workspaceId?: string,callerAgentVisibility?: 'private' | 'public' | null,+ documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,) {- this.agentDocumentModel = new AgentDocumentModel(db, userId, workspaceId);+ this.agentDocumentModel = new AgentDocumentModel(db, userId, workspaceId, documentAccessScope);// Public-agent gate flows through DocumentService → DocumentModel so// agentDocuments list / attach / read cannot see the caller's own// private documents when the invoking agent itself is workspace-public.- this.documentService = new DocumentService(db, userId, workspaceId, callerAgentVisibility);- this.topicDocumentModel = new TopicDocumentModel(db, userId, workspaceId);+ this.documentService = new DocumentService(+ db,+ userId,+ workspaceId,+ callerAgentVisibility,+ documentAccessScope,+ );+ this.topicDocumentModel = new TopicDocumentModel(db, userId, workspaceId, documentAccessScope);}private async projectDocumentContent<T extends ProjectableAgentDocument>(doc: T): Promise<T>;diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.tsindex a1a3c4614d2..3e012d5da08 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts@@ -1,3 +1,4 @@+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';import type * as ModelBankModule from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -12,6 +13,7 @@ import { AiAgentService } from '../../index';// below (which run before the test body) can wire them into stubbed models.const {mockCreateOperation,+ mockCreateServerAgentToolsEngine,mockFindByIds,mockGetAgentConfig,mockGetUserSettings,@@ -20,6 +22,10 @@ const {mockScheduleStaleConnectorToolsRefresh,} = vi.hoisted(() => ({mockCreateOperation: vi.fn(),+ mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),mockFindByIds: vi.fn(),mockGetAgentConfig: vi.fn(),mockGetUserSettings: vi.fn(),@@ -163,10 +169,7 @@ vi.mock('@/server/services/file', () => ({}));vi.mock('@/server/modules/Mecha', () => ({- createServerAgentToolsEngine: vi.fn().mockReturnValue({- generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),- getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),- }),+ createServerAgentToolsEngine: mockCreateServerAgentToolsEngine,serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),}));@@ -298,6 +301,46 @@ describe('discoverTools - share gate blocks ungranted connectors early', () => {);});+ it('enables Agent Documents for this run only after an explicit Share grant', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Create a document',+ shareGate: {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [{ identifier: AgentDocumentsIdentifier }] },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ });++ expect(mockCreateServerAgentToolsEngine).toHaveBeenCalledTimes(1);+ expect(mockCreateServerAgentToolsEngine.mock.calls[0][1].agentConfig.plugins).toEqual([+ AgentDocumentsIdentifier,+ ]);++ vi.clearAllMocks();+ mockCreateOperation.mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-2',+ operationId: 'op-456',+ success: true,+ });+ mockGetUserSettings.mockResolvedValue({ general: { timezone: 'UTC' } });++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Create a document',+ shareGate: {+ agentId: 'agent-1',+ shareConfig: { toolGrants: [] },+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ });++ expect(mockCreateServerAgentToolsEngine.mock.calls[0][1].agentConfig.plugins).toEqual([]);+ });+it('reads attached file types through the exact share visitor scope', async () => {mockFindByIds.mockResolvedValue([{ fileType: 'image/png', id: 'file-visitor' }]);diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex f4c05b2c146..c8570a6ab2f 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -92,7 +92,11 @@ import {isMultimodalUnderstandingConfigured,} from '../helpers/mediaAvailability';import { resolveServerSearchDecision } from '../searchDecision';-import { filterPluginsByShareGate, shareGateGrantsCloudSandbox } from '../shareGate';+import {+ filterPluginsByShareGate,+ getShareGrantActivatedPluginIds,+ shareGateGrantsCloudSandbox,+} from '../shareGate';import type { ExecRunContext, InternalExecAgentParams } from '../types';import { markDegradedStage, traceDiscoveryStage } from './discoveryTracing';@@ -320,6 +324,7 @@ export const discoverTools = async (...(additionalPluginIds || []),...(selectedToolIds || []),...(hasMentionedAgents ? ['lobe-agent-management'] : []),+ ...(shareGate ? getShareGrantActivatedPluginIds(shareGate) : []),]),];diff --git a/apps/server/src/services/aiAgent/shareGate.test.ts b/apps/server/src/services/aiAgent/shareGate.test.tsindex d8c48fb85ca..80c054f6a90 100644--- a/apps/server/src/services/aiAgent/shareGate.test.ts+++ b/apps/server/src/services/aiAgent/shareGate.test.ts@@ -1,6 +1,8 @@import {AgentDocumentsApiName,AgentDocumentsIdentifier,+ AgentDocumentsManifest,+ agentShareSystemPrompt,} from '@lobechat/builtin-tool-agent-documents';import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';import { CalculatorIdentifier } from '@lobechat/builtin-tool-calculator';@@ -14,14 +16,18 @@ import {LobeAgentIdentifier,systemPromptWithoutSubAgent,} from '@lobechat/builtin-tool-lobe-agent';-import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import {+ MemoryApiName,+ MemoryIdentifier,+ memoryReadOnlySystemPrompt,+} from '@lobechat/builtin-tool-memory';import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';import {AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS,builtinTools,} from '@lobechat/builtin-tools';-import { ToolNameResolver } from '@lobechat/context-engine';+import { generateToolsFromManifest, ToolNameResolver } from '@lobechat/context-engine';import { describe, expect, it } from 'vitest';import type { AgentShareGate, ShareGateToolSet } from './shareGate';@@ -29,6 +35,7 @@ import {applyShareGateToAgentConfig,applyShareGateToToolSet,filterPluginsByShareGate,+ getShareGrantActivatedPluginIds,isShareBlockedBuiltinDispatch,isShareBlockedDataToolCall,shareGateGrantsCloudSandbox,@@ -136,6 +143,17 @@ describe('filterPluginsByShareGate', () => {});});+describe('getShareGrantActivatedPluginIds', () => {+ it('activates Agent Documents only after the owner grants it for this Share', () => {+ expect(getShareGrantActivatedPluginIds(buildGate())).toEqual([]);+ expect(+ getShareGrantActivatedPluginIds(+ buildGate({ toolGrants: [{ identifier: AgentDocumentsIdentifier }] }),+ ),+ ).toEqual([AgentDocumentsIdentifier]);+ });+});+describe('applyShareGateToAgentConfig', () => {it('always strips files and knowledge bases', () => {const agentConfig = {@@ -188,7 +206,11 @@ describe('AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS', () => {* ignores — so pin the two together.*/describe('AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS', () => {- const maximalPermissions = { allowReadMemory: true, knowledgeBaseIds: ['kb1'] };+ const maximalPermissions = {+ allowReadMemory: true,+ knowledgeBaseIds: ['kb1'],+ toolGrants: [{ identifier: AgentDocumentsIdentifier }],+ };it('names only allowlisted identifiers', () => {for (const identifier of AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS) {@@ -211,6 +233,10 @@ describe('AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS', () => {it('excludes memory, whose grant is conditional on allowReadMemory', () => {expect(AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(MemoryIdentifier)).toBe(false);});++ it('excludes Agent Documents, whose grant enables only share-scoped authoring APIs', () => {+ expect(AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS.has(AgentDocumentsIdentifier)).toBe(false);+ });});describe('isShareBlockedDataToolCall', () => {@@ -245,14 +271,34 @@ describe('isShareBlockedDataToolCall', () => {});});- it('blocks agent documents and knowledge base outright (no grant exists)', () => {+ it('keeps Agent Documents closed by default, then allows only its scoped authoring APIs', () => {expect(- isShareBlockedDataToolCall(- { allowReadMemory: true },- AgentDocumentsIdentifier,- AgentDocumentsApiName.listDocuments,- ),+ isShareBlockedDataToolCall({}, AgentDocumentsIdentifier, AgentDocumentsApiName.listDocuments),).toBe(true);++ const permissions = { toolGrants: [{ identifier: AgentDocumentsIdentifier }] };+ for (const apiName of [+ AgentDocumentsApiName.createDocument,+ AgentDocumentsApiName.readDocument,+ AgentDocumentsApiName.listDocuments,+ AgentDocumentsApiName.modifyNodes,+ AgentDocumentsApiName.replaceDocumentContent,+ AgentDocumentsApiName.renameDocument,+ ]) {+ expect(isShareBlockedDataToolCall(permissions, AgentDocumentsIdentifier, apiName)).toBe(+ false,+ );+ }+ for (const apiName of [+ AgentDocumentsApiName.copyDocument,+ AgentDocumentsApiName.removeDocument,+ AgentDocumentsApiName.updateLoadRule,+ ]) {+ expect(isShareBlockedDataToolCall(permissions, AgentDocumentsIdentifier, apiName)).toBe(true);+ }+ });++ it('blocks knowledge base outright (no grant exists)', () => {expect(isShareBlockedDataToolCall({ allowReadMemory: true, knowledgeBaseIds: ['kb1'] },@@ -321,10 +367,12 @@ describe('applyShareGateToToolSet', () => {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.';applyShareGateToToolSet(toolSet, buildGate({ toolGrants: [{ identifier: 'mcp-github' }] }));expect(toolSet.enabledToolIds).toEqual(['mcp-github']);+ expect(toolSet.manifestMap['mcp-github'].systemRole).toBe('Use run for repository operations.');});it('collapses the whole set when no tools are enabled', () => {@@ -432,6 +480,7 @@ describe('applyShareGateToToolSet', () => {buildToolSet([{apis: [+ { name: MemoryApiName.queryTaxonomyOptions },{ name: MemoryApiName.searchUserMemory },{ name: MemoryApiName.addContextMemory },],@@ -450,13 +499,109 @@ describe('applyShareGateToToolSet', () => {buildGate({ allowReadMemory: true, toolGrants: [{ identifier: MemoryIdentifier }] }),);expect(granted.manifestMap[MemoryIdentifier].api.map((api) => api.name)).toEqual([+ MemoryApiName.queryTaxonomyOptions,MemoryApiName.searchUserMemory,]);+ expect(granted.manifestMap[MemoryIdentifier].systemRole).toBe(memoryReadOnlySystemPrompt);expect(granted.tools!.map((tool: any) => tool.function.name)).toEqual([+ toolName(MemoryIdentifier, MemoryApiName.queryTaxonomyOptions),toolName(MemoryIdentifier, MemoryApiName.searchUserMemory),]);});+ it('keeps only Share-scoped Agent Documents authoring APIs', () => {+ const toolSet = buildToolSet([+ {+ apis: Object.values(AgentDocumentsApiName).map((name) => ({ name })),+ identifier: AgentDocumentsIdentifier,+ },+ ]);+ toolSet.manifestMap[AgentDocumentsIdentifier] = AgentDocumentsManifest;+ toolSet.tools = generateToolsFromManifest(AgentDocumentsManifest);++ applyShareGateToToolSet(+ toolSet,+ buildGate({ toolGrants: [{ identifier: AgentDocumentsIdentifier }] }),+ );++ const manifest = toolSet.manifestMap[AgentDocumentsIdentifier];+ expect(manifest.api.map((api) => api.name).sort()).toEqual(+ [+ AgentDocumentsApiName.createDocument,+ AgentDocumentsApiName.listDocuments,+ AgentDocumentsApiName.modifyNodes,+ AgentDocumentsApiName.readDocument,+ AgentDocumentsApiName.renameDocument,+ AgentDocumentsApiName.replaceDocumentContent,+ ].sort(),+ );+ expect(manifest.systemRole).toBe(agentShareSystemPrompt);+ expect(manifest.meta?.description).toBe(+ 'Create, list, read, edit, and rename documents isolated to the current shared-agent topic.',+ );++ const createDocument = manifest.api.find(+ (api) => api.name === AgentDocumentsApiName.createDocument,+ );+ const listDocuments = manifest.api.find(+ (api) => api.name === AgentDocumentsApiName.listDocuments,+ );+ expect(Object.keys(createDocument!.parameters.properties).sort()).toEqual(['content', 'title']);+ expect(Object.keys(listDocuments!.parameters.properties)).toEqual([]);++ const createDocumentTool = toolSet.tools!.find(+ (tool: any) =>+ tool.function.name ===+ toolName(AgentDocumentsIdentifier, AgentDocumentsApiName.createDocument),+ );+ const listDocumentsTool = toolSet.tools!.find(+ (tool: any) =>+ tool.function.name ===+ toolName(AgentDocumentsIdentifier, AgentDocumentsApiName.listDocuments),+ );+ expect(Object.keys(createDocumentTool!.function.parameters.properties).sort()).toEqual([+ 'content',+ 'title',+ ]);+ expect(Object.keys(listDocumentsTool!.function.parameters.properties)).toEqual([]);+ });++ it('preserves the restricted Agent Documents schema for a per-API grant', () => {+ const toolSet = buildToolSet([+ {+ apis: Object.values(AgentDocumentsApiName).map((name) => ({ name })),+ identifier: AgentDocumentsIdentifier,+ },+ ]);+ toolSet.manifestMap[AgentDocumentsIdentifier] = AgentDocumentsManifest;+ toolSet.tools = generateToolsFromManifest(AgentDocumentsManifest);++ applyShareGateToToolSet(+ toolSet,+ buildGate({+ toolGrants: [+ {+ apis: [AgentDocumentsApiName.createDocument],+ identifier: AgentDocumentsIdentifier,+ },+ ],+ }),+ );++ const manifest = toolSet.manifestMap[AgentDocumentsIdentifier];+ expect(manifest.api.map((api) => api.name)).toEqual([AgentDocumentsApiName.createDocument]);+ expect(manifest.meta?.description).toBe(+ 'Use documents isolated to the current shared-agent topic.',+ );+ expect(manifest.systemRole).toBeUndefined();+ expect(Object.keys(manifest.api[0].parameters.properties).sort()).toEqual(['content', 'title']);+ expect(toolSet.tools).toHaveLength(1);+ expect(Object.keys(toolSet.tools![0].function.parameters.properties).sort()).toEqual([+ 'content',+ 'title',+ ]);+ });+it('strips apis whose humanIntervention can never resolve under reject mode', () => {const toolSet = buildToolSet([{@@ -538,6 +683,8 @@ describe('applyShareGateToToolSet', () => {type: 'mcp',},]);+ toolSet.manifestMap['mcp-github'].systemRole =+ 'Use listRepos and deleteRepo for repository operations.';// The grant in `shareConfig.toolGrants` names the RAW api name, independent// of whatever `ToolNameResolver.generate` does for the WIRE tool-call name@@ -549,6 +696,7 @@ describe('applyShareGateToToolSet', () => {);expect(toolSet.manifestMap['mcp-github'].api.map((api) => api.name)).toEqual(['listRepos']);+ expect(toolSet.manifestMap['mcp-github'].systemRole).toBeUndefined();expect(toolSet.tools!.map((tool: any) => tool.function.name)).toEqual([toolName('mcp-github', 'listRepos', 'mcp'),]);@@ -738,6 +886,39 @@ describe('isShareBlockedBuiltinDispatch', () => {).toBe(true);});+ it('allows granted Agent Documents authoring APIs but blocks destructive and policy APIs', () => {+ const enabled = { toolGrants: [{ identifier: AgentDocumentsIdentifier }] };++ expect(+ isShareBlockedBuiltinDispatch(+ enabled,+ AgentDocumentsIdentifier,+ AgentDocumentsApiName.createDocument,+ ),+ ).toBe(false);+ expect(+ isShareBlockedBuiltinDispatch(+ enabled,+ AgentDocumentsIdentifier,+ AgentDocumentsApiName.renameDocument,+ ),+ ).toBe(false);+ expect(+ isShareBlockedBuiltinDispatch(+ enabled,+ AgentDocumentsIdentifier,+ AgentDocumentsApiName.removeDocument,+ ),+ ).toBe(true);+ expect(+ isShareBlockedBuiltinDispatch(+ enabled,+ AgentDocumentsIdentifier,+ AgentDocumentsApiName.updateLoadRule,+ ),+ ).toBe(true);+ });+it('ignores non-builtin identifiers entirely', () => {expect(isShareBlockedBuiltinDispatch({}, 'some-mcp-server', 'anything')).toBe(false);});diff --git a/apps/server/src/services/aiAgent/shareGate.ts b/apps/server/src/services/aiAgent/shareGate.tsindex 7b032e68e0e..6d7f5655031 100644--- a/apps/server/src/services/aiAgent/shareGate.ts+++ b/apps/server/src/services/aiAgent/shareGate.ts@@ -1,4 +1,5 @@import {+ AGENT_SHARE_DOCUMENT_API_NAMES,AgentDocumentsApiName,AgentDocumentsIdentifier,} from '@lobechat/builtin-tool-agent-documents';@@ -26,11 +27,13 @@ import {type ShareToolGrant,} from '@lobechat/const';import type { LobeToolManifest, ToolExecutor, ToolSource } from '@lobechat/context-engine';-import { ToolNameResolver } from '@lobechat/context-engine';+import { generateToolsFromManifest, ToolNameResolver } from '@lobechat/context-engine';import type { AgentShareToolGrant } from '@lobechat/types';import type { AgentShareConfig } from '@/database/schemas';+import { resolveShareToolManifest } from './shareToolManifest';+/*** Single shared resolver instance for regenerating function-calling names* from a manifest's identifier/api/type — same class `ToolsEngine` used to@@ -92,6 +95,21 @@ export const filterPluginsByShareGate = (pluginIds: string[], gate: AgentShareGareturn pluginIds.filter((id) => hasShareToolGrant(grants, id));};+/**+ * Builtins whose Share grant is also their runtime opt-in.+ *+ * Agent Documents is a default activatable builtin rather than a profile+ * plugin, so creators have no separate profile switch that could place it in+ * `agentConfig.plugins`. Adding it here only after an explicit Share grant+ * lets the picker act as that opt-in for visitor runs while keeping the+ * default-closed behavior. The final tool-set gate still narrows its APIs.+ */+export const getShareGrantActivatedPluginIds = (gate: AgentShareGate): string[] => {+ const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);++ return hasShareToolGrant(grants, AgentDocumentsIdentifier) ? [AgentDocumentsIdentifier] : [];+};+/*** Whether the share grants `lobe-cloud-sandbox` (at any API scope). Drives* `resolveExecutionPlan`'s `sandboxFallback`: a visitor can never reach the@@ -140,6 +158,7 @@ export interface ShareDataToolPermissions {* below stays wired should a knowledge-base grant return.*/knowledgeBaseIds?: string[];+ toolGrants?: AgentShareToolGrant[];}/**@@ -215,19 +234,16 @@ interface DataToolAccessRule {*/const DATA_TOOL_ACCESS_RULES: Record<string, DataToolAccessRule> = {[AgentDocumentsIdentifier]: {- // No file grant exists in the current `AgentShareConfig` — see- // `applyShareGateToAgentConfig`'s adaptation note. Fail closed rather than- // silently defaulting the missing grant to `read`.- grant: () => 'none',- writeApiNames: [- AgentDocumentsApiName.createDocument,- AgentDocumentsApiName.copyDocument,- AgentDocumentsApiName.modifyNodes,- AgentDocumentsApiName.removeDocument,- AgentDocumentsApiName.renameDocument,- AgentDocumentsApiName.replaceDocumentContent,- AgentDocumentsApiName.updateLoadRule,- ],+ // The tool grant opts into a separately scoped authoring store. It never+ // exposes the creator's ordinary Agent Documents: the runtime and database+ // both constrain reads and writes to (shareId, visitorUserId, topicId).+ grant: (permissions) =>+ hasShareToolGrant(resolveShareToolGrants(permissions.toolGrants), AgentDocumentsIdentifier)+ ? 'read'+ : 'none',+ writeApiNames: Object.values(AgentDocumentsApiName).filter(+ (apiName) => !AGENT_SHARE_DOCUMENT_API_NAMES.has(apiName),+ ),},[KnowledgeBaseIdentifier]: {// `listFiles` / `getFileDetail` browse the creator's whole resource@@ -882,6 +898,32 @@ const pruneToolsForIdentifier = (});};+/**+ * Replace surviving function schemas with a builtin-owned restricted+ * projection while preserving which tools the upstream engine activated.+ */+const replaceToolsForIdentifier = (+ toolSet: ShareGateToolSet,+ identifier: string,+ ownedNames: ReadonlySet<string>,+ manifest: LobeToolManifest,+): void => {+ if (!toolSet.tools) return;++ const replacements = new Map(+ generateToolsFromManifest(manifest).map((tool) => [tool.function.name, tool]),+ );++ for (let i = 0; i < toolSet.tools.length; i += 1) {+ const name: string | undefined = toolSet.tools[i]?.function?.name;+ if (!name) continue;++ const owned = ownedNames.has(name) || name.split(PLUGIN_SCHEMA_SEPARATOR)[0] === identifier;+ const replacement = replacements.get(name);+ if (owned && replacement) toolSet.tools[i] = replacement;+ }+};+/** Every generated tool-call name the manifest can currently produce. */const generateOwnedToolNames = (identifier: string,@@ -920,8 +962,28 @@ const stripApisFromTool = (if (!manifest) return;const survivingApi = manifest.api.filter((api) => !blockedApiNames.has(api.name));-- toolSet.manifestMap[identifier] = { ...manifest, api: survivingApi };+ const wasTrimmed = survivingApi.length < manifest.api.length;+ const ownedNames = generateOwnedToolNames(identifier, manifest);+ const restrictedManifest = wasTrimmed+ ? resolveShareToolManifest({+ allowedApiNames: survivingApi.map((api) => api.name),+ identifier,+ })+ : undefined;+ const restrictedApiMap = new Map(restrictedManifest?.api.map((api) => [api.name, api]) ?? []);++ // A manifest-level system role commonly documents its complete API surface.+ // Keeping it after a partial strip lets the model infer and advertise APIs+ // that are no longer callable, even though the function schemas are safe.+ // ToolResolver applies the same invariant for per-step tool-name filtering.+ toolSet.manifestMap[identifier] = {+ ...manifest,+ api: survivingApi.map((api) => restrictedApiMap.get(api.name) ?? api),+ meta: restrictedManifest?.meta ?? manifest.meta,+ ...(wasTrimmed && {+ systemRole: restrictedManifest?.systemRole,+ }),+ };// Fail-closed: only keep `tools[]` entries this file can PROVE still// belong to a surviving API, by regenerating their exact names rather than@@ -929,13 +991,17 @@ const stripApisFromTool = (pruneToolsForIdentifier(toolSet,identifier,- generateOwnedToolNames(identifier, manifest),+ ownedNames,generateToolNames(identifier,survivingApi.map((api) => api.name),manifest.type,),);++ if (restrictedManifest) {+ replaceToolsForIdentifier(toolSet, identifier, ownedNames, toolSet.manifestMap[identifier]);+ }};const pruneArrayInPlace = <T>(array: T[], keep: (item: T) => boolean): void => {diff --git a/apps/server/src/services/aiAgent/shareToolManifest.ts b/apps/server/src/services/aiAgent/shareToolManifest.tsnew file mode 100644index 00000000000..d3cea7b44dc--- /dev/null+++ b/apps/server/src/services/aiAgent/shareToolManifest.ts@@ -0,0 +1,46 @@+import { builtinTools } from '@lobechat/builtin-tools';+import type { LobeToolManifest } from '@lobechat/context-engine';++interface ResolveShareToolManifestOptions {+ allowedApiNames: readonly string[];+ identifier: string;+}++const hasExactApiSet = (+ manifest: LobeToolManifest,+ allowedApiNames: readonly string[],+): boolean => {+ const allowed = new Set(allowedApiNames);++ return manifest.api.length === allowed.size && manifest.api.every((api) => allowed.has(api.name));+};++/**+ * Transitional bridge between Agent Share policy filtering and builtin-owned+ * restricted manifests.+ *+ * Keep this adapter separate from `shareGate.ts`: a future shared tool+ * finalization pipeline can move the same optional resolver without retaining+ * Agent Share-specific registry lookup or Documents/Memory knowledge in the+ * gate. The exact-set check prevents a tool-owned projection from widening the+ * policy-approved API set.+ */+export const resolveShareToolManifest = ({+ allowedApiNames,+ identifier,+}: ResolveShareToolManifestOptions): LobeToolManifest | undefined => {+ const resolver = builtinTools.find(+ (tool) => tool.identifier === identifier,+ )?.resolveRestrictedManifest;+ const manifest = resolver?.({ allowedApiNames, restriction: 'agentShare' });++ if (+ !manifest ||+ manifest.identifier !== identifier ||+ !hasExactApiSet(manifest, allowedApiNames)+ ) {+ return undefined;+ }++ return manifest;+};diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.tsindex 41aa8459c37..c2902dc9159 100644--- a/apps/server/src/services/document/__tests__/index.test.ts+++ b/apps/server/src/services/document/__tests__/index.test.ts@@ -2009,6 +2009,7 @@ describe('DocumentService', () => {userId,'workspace-1','public',+ { type: 'ordinary' },);expect(transactionModel.findByFileId).toHaveBeenCalledWith('file-1', {type: 'ordinary',diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex 3ceafa73438..73a3761dd21 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -5,8 +5,12 @@ import { type LobeChatDatabase } from '@lobechat/database';import { type DocumentItem } from '@lobechat/database/schemas';import { documents, files } from '@lobechat/database/schemas';import { loadFile, UnsupportedFileTypeError } from '@lobechat/file-loaders';-import type { FileAccessScope } from '@lobechat/types';-import { ordinaryFileAccessScope, stripAgentShareFileProvenance } from '@lobechat/types';+import type { DocumentAccessScope, FileAccessScope } from '@lobechat/types';+import {+ ordinaryDocumentAccessScope,+ ordinaryFileAccessScope,+ stripAgentShareDocumentProvenance,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import { and, eq, sql } from 'drizzle-orm';@@ -63,6 +67,7 @@ export class DocumentService {private editLockService: EditLockService;private db: LobeChatDatabase;private callerAgentVisibility?: 'private' | 'public' | null;+ private documentAccessScope: DocumentAccessScope;private workspaceId?: string;@@ -71,14 +76,22 @@ export class DocumentService {userId: string,workspaceId?: string,callerAgentVisibility?: 'private' | 'public' | null,+ documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,) {this.userId = userId;this.db = db;this.workspaceId = workspaceId;this.callerAgentVisibility = callerAgentVisibility;+ this.documentAccessScope = documentAccessScope;this.fileModel = new FileModel(db, userId, workspaceId);this.knowledgeBaseModel = new KnowledgeBaseModel(db, userId, workspaceId);- this.documentModel = new DocumentModel(db, userId, workspaceId, callerAgentVisibility);+ this.documentModel = new DocumentModel(+ db,+ userId,+ workspaceId,+ callerAgentVisibility,+ documentAccessScope,+ );this.editLockService = new EditLockService(userId);}@@ -146,7 +159,7 @@ export class DocumentService {slug,visibility,} = params;- const sanitizedMetadata = stripAgentShareFileProvenance(metadata);+ const sanitizedMetadata = stripAgentShareDocumentProvenance(metadata);// Calculate character and line countsconst totalCharCount = content?.length || 0;@@ -635,6 +648,7 @@ export class DocumentService {this.userId,this.workspaceId,this.callerAgentVisibility,+ this.documentAccessScope,);const fileModel = new FileModel(transactionDb, this.userId, this.workspaceId);const documentHistoryService = new DocumentHistoryService(@@ -902,6 +916,7 @@ export class DocumentService {this.userId,this.workspaceId,this.callerAgentVisibility,+ this.documentAccessScope,);// Whoever inserted first wins; discard this parse rather than adding adiff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.tsindex 1ac28d33cbf..81951ebaade 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts@@ -36,6 +36,21 @@ describe('agentDocumentsRuntime', () => {'userId and serverDB are required for Agent Documents execution',);});++ it('fails closed when a Share document call has no topic context', () => {+ expect(() =>+ agentDocumentsRuntime.factory({+ agentShareVisitor: {+ agentId: 'agent-1',+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ serverDB: {} as any,+ toolManifestMap: {},+ userId: 'user-1',+ }),+ ).toThrow('topicId is required for Agent Share document execution');+ });});describe('agentDocumentsRuntime auto-pin to task', () => {@@ -51,6 +66,8 @@ describe('agentDocumentsRuntime auto-pin to task', () => {createDocument: ReturnType<typeof vi.fn>;createForTopic: ReturnType<typeof vi.fn>;getDocumentSnapshotById: ReturnType<typeof vi.fn>;+ listDocuments: ReturnType<typeof vi.fn>;+ listDocumentsForTopic: ReturnType<typeof vi.fn>;renameDocumentById: ReturnType<typeof vi.fn>;};let pinDocument: ReturnType<typeof vi.fn>;@@ -63,6 +80,8 @@ describe('agentDocumentsRuntime auto-pin to task', () => {createDocument: vi.fn().mockResolvedValue(newDoc),createForTopic: vi.fn().mockResolvedValue(newDoc),getDocumentSnapshotById: vi.fn().mockResolvedValue(newDoc),+ listDocuments: vi.fn().mockResolvedValue([newDoc]),+ listDocumentsForTopic: vi.fn().mockResolvedValue([newDoc]),renameDocumentById: vi.fn().mockResolvedValue(newDoc),};pinDocument = vi.fn().mockResolvedValue(undefined);@@ -79,7 +98,11 @@ describe('agentDocumentsRuntime auto-pin to task', () => {});});- const buildContext = (taskId?: string, workspaceId?: string) => {+ const buildContext = (+ taskId?: string,+ workspaceId?: string,+ overrides?: Partial<ToolExecutionContext>,+ ) => {// Mock the workspace lookup chain that `pinToTask` runs against the task// row. Returning `workspaceId: null` reproduces personal-mode behavior.const limit = vi.fn().mockResolvedValue([{ workspaceId: null }]);@@ -92,6 +115,7 @@ describe('agentDocumentsRuntime auto-pin to task', () => {toolManifestMap: {},userId: 'user-1',workspaceId,+ ...overrides,};};@@ -231,6 +255,60 @@ describe('agentDocumentsRuntime auto-pin to task', () => {'Created document "Daily Brief" (internal id: agent-doc-assoc-id).',);});++ it('forces Share creation and listing into the visitor current-topic scope', async () => {+ const runtime = agentDocumentsRuntime.factory(+ buildContext(undefined, undefined, {+ agentShareVisitor: {+ agentId: 'agent-1',+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ topicId: 'topic-1',+ }),+ );++ const created = await runtime.createDocument(+ {+ content: 'body',+ hintIsSkill: true,+ parentId: 'creator-folder',+ scope: 'agent',+ title: 'Visitor Note',+ },+ { agentId: 'agent-1', topicId: 'topic-1' },+ );+ await runtime.listDocuments(+ { parentId: 'creator-folder', scope: 'agent' },+ { agentId: 'agent-1', topicId: 'topic-1' },+ );++ expect(serviceImpl.createForTopic).toHaveBeenCalledWith(+ 'agent-1',+ 'Visitor Note',+ 'body',+ 'topic-1',+ );+ expect(serviceImpl.createDocument).not.toHaveBeenCalled();+ expect(serviceImpl.listDocumentsForTopic).toHaveBeenCalledWith('agent-1', 'topic-1', 'all', {+ includeArchivedToolResults: true,+ });+ expect(serviceImpl.listDocuments).not.toHaveBeenCalled();+ expect(created.content).not.toContain('https://app.example.com');+ expect(created.state).toMatchObject({ readonly: true });+ expect(AgentDocumentsService).toHaveBeenLastCalledWith(+ expect.anything(),+ 'user-1',+ undefined,+ undefined,+ {+ shareId: 'share-1',+ topicId: 'topic-1',+ type: 'agentShare',+ visitorUserId: 'visitor-1',+ },+ );+ });});describe('agentDocumentsRuntime Work registration state', () => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.tsindex aef5702c96b..5d2d694a1bd 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts@@ -1,6 +1,7 @@import type { DocumentLoadRule } from '@lobechat/agent-templates';import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';import { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-documents/executionRuntime';+import { agentShareDocumentAccessScope, ordinaryDocumentAccessScope } from '@lobechat/types';import { eq } from 'drizzle-orm';import { TaskModel } from '@/database/models/task';@@ -19,11 +20,24 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {const db = context.serverDB;const userId = context.userId;+ if (context.agentShareVisitor && !context.topicId) {+ throw new Error('topicId is required for Agent Share document execution');+ }++ const shareTopicId = context.agentShareVisitor ? context.topicId : undefined;+ const documentAccessScope = context.agentShareVisitor+ ? agentShareDocumentAccessScope({+ shareId: context.agentShareVisitor.shareId,+ topicId: shareTopicId!,+ visitorUserId: context.agentShareVisitor.visitorUserId,+ })+ : ordinaryDocumentAccessScope;const service = new AgentDocumentsService(db,userId,context.workspaceId,context.agentVisibility,+ documentAccessScope,);const { taskId } = context;const workRegistrar = createDocumentWorkRegistrar({@@ -158,7 +172,10 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents created a document.',toolAction: 'create',},- () => service.createDocument(agentId, title, content, { hintIsSkill, parentId }),+ () =>+ shareTopicId+ ? service.createForTopic(agentId, title, content, shareTopicId)+ : service.createDocument(agentId, title, content, { hintIsSkill, parentId }),),);return doc;@@ -183,10 +200,13 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {toolAction: 'create',},() =>- service.createForTopic(agentId, title, content, topicId, {- hintIsSkill,- parentId,- }),+ service.createForTopic(+ agentId,+ title,+ content,+ shareTopicId ?? topicId,+ shareTopicId ? undefined : { hintIsSkill, parentId },+ ),),);return doc;@@ -194,10 +214,14 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {listDocuments: async ({ agentId, parentId, sourceType }) => {// Agents discover archived tool results via this path (see// `excludeArchivedToolResults`), so keep the `.tool-results` archive visible.- const docs = await service.listDocuments(agentId, sourceType, {- includeArchivedToolResults: true,- parentId,- });+ const docs = shareTopicId+ ? await service.listDocumentsForTopic(agentId, shareTopicId, sourceType, {+ includeArchivedToolResults: true,+ })+ : await service.listDocuments(agentId, sourceType, {+ includeArchivedToolResults: true,+ parentId,+ });return docs.map((d) => ({documentId: d.documentId,filename: d.filename,@@ -206,9 +230,14 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {}));},listTopicDocuments: async ({ agentId, parentId, sourceType, topicId }) => {- const docs = await service.listDocumentsForTopic(agentId, topicId, sourceType, {- includeArchivedToolResults: true,- });+ const docs = await service.listDocumentsForTopic(+ agentId,+ shareTopicId ?? topicId,+ sourceType,+ {+ includeArchivedToolResults: true,+ },+ );// Topic listing joins through topic associations rather than the agent// folder tree, so the folder filter is applied in-memory here.const filtered = parentId ? docs.filter((d) => d.parentId === parentId) : docs;@@ -293,8 +322,11 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {),},{- getDocumentUrl: ({ agentId, documentId }) =>- workRegistrar.buildRegisteredDocumentUrl(agentId, documentId),+ documentReadonly: Boolean(context.agentShareVisitor),+ getDocumentUrl: context.agentShareVisitor+ ? undefined+ : ({ agentId, documentId }) =>+ workRegistrar.buildRegisteredDocumentUrl(agentId, documentId),},);},diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.tsindex 8e582af3050..de1305ec54a 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts@@ -160,6 +160,8 @@ export interface AgentDocumentsRuntimeService {}export interface AgentDocumentsRuntimeOptions {+ /** Keep the backing id for bookkeeping while hiding owner-only edit affordances. */+ documentReadonly?: boolean;/*** Build a shareable URL that opens a document in the standalone document* route. When provided and it returns a URL, the create result surfaces the@@ -411,7 +413,12 @@ export class AgentDocumentsExecutionRuntime {return {content: formatCreateDocumentResult({ id: created.id, title, url }),- state: { agentDocumentId: created.id, agentId, documentId: created.documentId },+ state: {+ agentDocumentId: created.id,+ agentId,+ documentId: created.documentId,+ ...(this.options.documentReadonly && { readonly: true }),+ },success: true,};}diff --git a/packages/builtin-tool-agent-documents/src/agentShareSystemRole.ts b/packages/builtin-tool-agent-documents/src/agentShareSystemRole.tsnew file mode 100644index 00000000000..b0cb16d4bef--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/agentShareSystemRole.ts@@ -0,0 +1,30 @@+export const agentShareSystemPrompt = `You have access to a restricted Agent Documents tool for documents created during the current shared-agent topic.++<scope_boundary>+- Every list, create, read, and update is isolated to the current share, visitor, and topic.+- You cannot access the creator's ordinary agent documents or documents from another visitor or topic.+- Uploaded files, PDFs, images, and resource-library content are not Agent Documents. Use an available file or Knowledge Base tool for those resources.+</scope_boundary>++<core_capabilities>+1. Create a document (createDocument).+2. List documents from this shared topic (listDocuments).+3. Read one document by ID (readDocument).+4. Apply precise LiteXML edits (modifyNodes).+5. Replace a document's complete content (replaceDocumentContent).+6. Rename a document (renameDocument).+</core_capabilities>++<workflow>+1. Identify the requested document operation.+2. Use listDocuments when only a title is known, then use the returned id for later calls.+3. Read a document before editing when the current content matters. Prefer XML before modifyNodes because XML includes stable node IDs.+4. Prefer modifyNodes for targeted edits and replaceDocumentContent only for full rewrites.+5. Confirm the completed action and present any returned document URL as a clickable markdown link.+</workflow>++<response_boundaries>+- Never expose an internal document ID to the user.+- Do not claim access to documents outside this shared topic.+- Explain clearly when a document is not found or an operation fails.+</response_boundaries>`;diff --git a/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsx b/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsxindex 835fab79cc0..0dfcd012f3b 100644--- a/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/DocumentCard.tsx@@ -56,10 +56,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({interface DocumentCardProps {content: string;documentId?: string;+ readonly?: boolean;title: string;}-const DocumentCard = memo<DocumentCardProps>(({ content, documentId, title }) => {+const DocumentCard = memo<DocumentCardProps>(({ content, documentId, readonly, title }) => {const { t } = useTranslation('plugin');const [portalDocumentId, openDocument, closeDocument] = useChatStore((s) => [chatPortalSelectors.portalDocumentId(s),@@ -92,7 +93,7 @@ const DocumentCard = memo<DocumentCardProps>(({ content, documentId, title }) =>size={'small'}title={t('builtins.lobe-notebook.actions.copy')}/>- {documentId && (+ {documentId && !readonly && (<ActionIconicon={PencilLine}size={'small'}@@ -109,7 +110,7 @@ const DocumentCard = memo<DocumentCardProps>(({ content, documentId, title }) =></Markdown></ScrollShadow>- {documentId && (+ {documentId && !readonly && (<ButtonclassName={styles.expandButton}icon={isExpanded ? <Minimize2 size={14} /> : <Maximize2 size={14} />}diff --git a/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/index.tsx b/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/index.tsxindex 26a67bc94f3..1bd6779cf52 100644--- a/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/index.tsx+++ b/packages/builtin-tool-agent-documents/src/client/Render/CreateDocument/index.tsx@@ -17,7 +17,14 @@ const CreateDocument = memo<CreateDocumentRenderProps>(({ args, pluginState }) =if (!title || !content) return null;- return <DocumentCard content={content} documentId={pluginState?.documentId} title={title} />;+ return (+ <DocumentCard+ content={content}+ documentId={pluginState?.documentId}+ readonly={pluginState?.readonly}+ title={title}+ />+ );});export default CreateDocument;diff --git a/packages/builtin-tool-agent-documents/src/index.ts b/packages/builtin-tool-agent-documents/src/index.tsindex 18123a6f5b3..1e08c9a5a07 100644--- a/packages/builtin-tool-agent-documents/src/index.ts+++ b/packages/builtin-tool-agent-documents/src/index.ts@@ -1,6 +1,9 @@+export { agentShareSystemPrompt } from './agentShareSystemRole';export { AgentDocumentsManifest } from './manifest';+export { resolveAgentDocumentsRestrictedManifest } from './resolveRestrictedManifest';export { systemPrompt } from './systemRole';export {+ AGENT_SHARE_DOCUMENT_API_NAMES,AgentDocumentsApiName,AgentDocumentsIdentifier,type CopyDocumentArgs,diff --git a/packages/builtin-tool-agent-documents/src/resolveRestrictedManifest.test.ts b/packages/builtin-tool-agent-documents/src/resolveRestrictedManifest.test.tsnew file mode 100644index 00000000000..5794172942a--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/resolveRestrictedManifest.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from 'vitest';++import { agentShareSystemPrompt } from './agentShareSystemRole';+import { AgentDocumentsManifest } from './manifest';+import { resolveAgentDocumentsRestrictedManifest } from './resolveRestrictedManifest';+import { AGENT_SHARE_DOCUMENT_API_NAMES, AgentDocumentsApiName } from './types';++describe('resolveAgentDocumentsRestrictedManifest', () => {+ it('returns the Agent Share manifest for the exact visitor API set regardless of order', () => {+ const manifest = resolveAgentDocumentsRestrictedManifest({+ allowedApiNames: [...AGENT_SHARE_DOCUMENT_API_NAMES].reverse(),+ restriction: 'agentShare',+ });++ expect(manifest?.api.map((api) => api.name).sort()).toEqual(+ [...AGENT_SHARE_DOCUMENT_API_NAMES].sort(),+ );+ expect(manifest?.meta.description).toBe(+ 'Create, list, read, edit, and rename documents isolated to the current shared-agent topic.',+ );+ expect(manifest?.systemRole).toBe(agentShareSystemPrompt);+ });++ it('supports safe subsets without advertising APIs outside the grant', () => {+ const manifest = resolveAgentDocumentsRestrictedManifest({+ allowedApiNames: [AgentDocumentsApiName.createDocument, AgentDocumentsApiName.listDocuments],+ restriction: 'agentShare',+ });++ expect(manifest?.api.map((api) => api.name)).toEqual([+ AgentDocumentsApiName.createDocument,+ AgentDocumentsApiName.listDocuments,+ ]);+ expect(manifest?.meta.description).toBe(+ 'Use documents isolated to the current shared-agent topic.',+ );+ expect(manifest?.systemRole).toBeUndefined();+ expect(Object.keys(manifest!.api[0].parameters.properties).sort()).toEqual([+ 'content',+ 'title',+ ]);+ expect(Object.keys(manifest!.api[1].parameters.properties)).toEqual([]);+ });++ it('fails closed for unknown APIs, empty grants, and non-Share restrictions', () => {+ expect(+ resolveAgentDocumentsRestrictedManifest({+ allowedApiNames: ['unknownApi'],+ restriction: 'agentShare',+ }),+ ).toBeUndefined();+ expect(+ resolveAgentDocumentsRestrictedManifest({+ allowedApiNames: [],+ restriction: 'agentShare',+ }),+ ).toBeUndefined();+ expect(+ resolveAgentDocumentsRestrictedManifest({+ allowedApiNames: [...AGENT_SHARE_DOCUMENT_API_NAMES],+ restriction: 'toolSelection',+ }),+ ).toBeUndefined();+ });++ it('projects schemas to the arguments that Share actually honors', () => {+ const manifest = resolveAgentDocumentsRestrictedManifest({+ allowedApiNames: [...AGENT_SHARE_DOCUMENT_API_NAMES],+ restriction: 'agentShare',+ })!;+ const createDocument = manifest.api.find(+ (api) => api.name === AgentDocumentsApiName.createDocument,+ )!;+ const listDocuments = manifest.api.find(+ (api) => api.name === AgentDocumentsApiName.listDocuments,+ )!;++ expect(Object.keys(createDocument.parameters.properties).sort()).toEqual(['content', 'title']);+ expect(Object.keys(listDocuments.parameters.properties)).toEqual([]);+ expect(+ AgentDocumentsManifest.api.find((api) => api.name === AgentDocumentsApiName.createDocument)!+ .parameters.properties,+ ).toHaveProperty('parentId');+ });++ it('documents only the callable visitor surface', () => {+ for (const apiName of AGENT_SHARE_DOCUMENT_API_NAMES) {+ expect(agentShareSystemPrompt).toContain(apiName);+ }++ for (const forbiddenTerm of [+ 'copyDocument',+ 'removeDocument',+ 'updateLoadRule',+ 'hintIsSkill',+ 'parentId',+ 'sourceType',+ ]) {+ expect(agentShareSystemPrompt).not.toContain(forbiddenTerm);+ }+ });+});diff --git a/packages/builtin-tool-agent-documents/src/resolveRestrictedManifest.ts b/packages/builtin-tool-agent-documents/src/resolveRestrictedManifest.tsnew file mode 100644index 00000000000..0d1944a478a--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/resolveRestrictedManifest.ts@@ -0,0 +1,86 @@+import type { BuiltinRestrictedManifestResolver, LobeChatPluginApi } from '@lobechat/types';++import { agentShareSystemPrompt } from './agentShareSystemRole';+import { AgentDocumentsManifest } from './manifest';+import { AGENT_SHARE_DOCUMENT_API_NAMES, AgentDocumentsApiName } from './types';++const matchesExactApiSet = (apiNames: readonly string[], expected: ReadonlySet<string>) => {+ const actual = new Set(apiNames);++ return actual.size === expected.size && [...actual].every((apiName) => expected.has(apiName));+};++const isSupportedAgentShareApiSet = (apiNames: readonly string[]) =>+ apiNames.length > 0 && apiNames.every((apiName) => AGENT_SHARE_DOCUMENT_API_NAMES.has(apiName));++const getApi = (name: string): LobeChatPluginApi => {+ const api = AgentDocumentsManifest.api.find((item) => item.name === name);++ if (!api) throw new Error(`Agent Documents manifest is missing ${name}`);++ return api;+};++const createDocumentApi: LobeChatPluginApi = {+ ...getApi(AgentDocumentsApiName.createDocument),+ description: 'Create a document in the current shared-agent topic.',+ parameters: {+ properties: {+ content: getApi(AgentDocumentsApiName.createDocument).parameters.properties.content,+ title: getApi(AgentDocumentsApiName.createDocument).parameters.properties.title,+ },+ required: ['title', 'content'],+ type: 'object',+ },+};++const listDocumentsApi: LobeChatPluginApi = {+ ...getApi(AgentDocumentsApiName.listDocuments),+ description: 'List documents created during the current shared-agent topic.',+ parameters: {+ properties: {},+ required: [],+ type: 'object',+ },+};++const agentShareApiOverrides = new Map<string, LobeChatPluginApi>([+ [AgentDocumentsApiName.createDocument, createDocumentApi],+ [AgentDocumentsApiName.listDocuments, listDocumentsApi],+]);++/**+ * Owns the temporary Agent Share projection of Documents capabilities.+ *+ * Keeping the semantic projection in this package prevents Share orchestration+ * from learning Documents-specific arguments and makes a future common tool+ * finalization pipeline a registry wiring change rather than another rewrite.+ */+export const resolveAgentDocumentsRestrictedManifest: BuiltinRestrictedManifestResolver = ({+ allowedApiNames,+ restriction,+}) => {+ if (restriction !== 'agentShare' || !isSupportedAgentShareApiSet(allowedApiNames)) {+ return undefined;+ }++ const allowedApiNameSet = new Set(allowedApiNames);+ const hasFullAgentShareApiSet = matchesExactApiSet(+ allowedApiNames,+ AGENT_SHARE_DOCUMENT_API_NAMES,+ );++ return {+ ...AgentDocumentsManifest,+ api: AgentDocumentsManifest.api+ .filter((api) => allowedApiNameSet.has(api.name))+ .map((api) => agentShareApiOverrides.get(api.name) ?? api),+ meta: {+ ...AgentDocumentsManifest.meta,+ description: hasFullAgentShareApiSet+ ? 'Create, list, read, edit, and rename documents isolated to the current shared-agent topic.'+ : 'Use documents isolated to the current shared-agent topic.',+ },+ systemRole: hasFullAgentShareApiSet ? agentShareSystemPrompt : undefined,+ };+};diff --git a/packages/builtin-tool-agent-documents/src/types.ts b/packages/builtin-tool-agent-documents/src/types.tsindex c195392d39c..e93ab4ad2b2 100644--- a/packages/builtin-tool-agent-documents/src/types.ts+++ b/packages/builtin-tool-agent-documents/src/types.ts@@ -12,6 +12,19 @@ export const AgentDocumentsApiName = {updateLoadRule: 'updateLoadRule',} as const;+/**+ * Document APIs a shared-agent visitor may use after the owner grants this tool.+ * The server still scopes every call to the exact share, visitor, and topic.+ */+export const AGENT_SHARE_DOCUMENT_API_NAMES = new Set<string>([+ AgentDocumentsApiName.createDocument,+ AgentDocumentsApiName.listDocuments,+ AgentDocumentsApiName.modifyNodes,+ AgentDocumentsApiName.readDocument,+ AgentDocumentsApiName.renameDocument,+ AgentDocumentsApiName.replaceDocumentContent,+]);+export interface CreateDocumentArgs {content: string;hintIsSkill?: boolean;@@ -26,6 +39,8 @@ export interface CreateDocumentState {/** Owning agent id — used to attribute the created document's Work. */agentId?: string;documentId?: string;+ /** The caller may preview/copy this result but must not open the owner-only editor. */+ readonly?: boolean;}export interface ReadDocumentArgs {diff --git a/packages/builtin-tool-memory/src/index.ts b/packages/builtin-tool-memory/src/index.tsindex 33fb982e422..adfdd19a762 100644--- a/packages/builtin-tool-memory/src/index.ts+++ b/packages/builtin-tool-memory/src/index.ts@@ -1,3 +1,10 @@export { MemoryIdentifier, MemoryManifest } from './manifest';+export { memoryReadOnlySystemPrompt } from './readOnlySystemRole';+export { resolveMemoryRestrictedManifest } from './resolveRestrictedManifest';export { systemPrompt } from './systemRole';-export { MEMORY_WRITE_API_NAMES, MemoryApiName, type MemoryApiNameType } from './types';+export {+ MEMORY_READ_API_NAMES,+ MEMORY_WRITE_API_NAMES,+ MemoryApiName,+ type MemoryApiNameType,+} from './types';diff --git a/packages/builtin-tool-memory/src/readOnlySystemRole.ts b/packages/builtin-tool-memory/src/readOnlySystemRole.tsnew file mode 100644index 00000000000..87192ab38f1--- /dev/null+++ b/packages/builtin-tool-memory/src/readOnlySystemRole.ts@@ -0,0 +1,23 @@+export const memoryReadOnlySystemPrompt = `You have read-only access to the creator-approved LobeHub Memory retrieval tools for this shared-agent conversation.++<scope_boundary>+- Memory access is retrieval-only. Do not claim that you can create, update, or delete memories.+- Use retrieved information only when it is relevant to the visitor's request.+- Never expose internal memory or database IDs. Refer to memories by descriptive titles or summaries.+</scope_boundary>++<tooling>+- queryTaxonomyOptions: discover the categories, tags, labels, statuses, roles, and relationships available for retrieval.+- searchUserMemory: search with one or more targeted queries and optional structured filters.+- The queries field must be a JSON array of strings. Use separate entries for separate intents.+- layers, categories, tags, labels, relationships, status, and types must also be JSON arrays.+- Prefer timeIntent for calendar or relative expressions such as "last month" or "yesterday". Use timeRange only when exact boundaries are already known.+</tooling>++<retrieval_guidelines>+1. Search only when remembered context would materially improve the answer.+2. Use multiple focused queries instead of one overloaded query.+3. Refine a search when the first result set is too broad or misses a specific person, time, object, relationship, or preference.+4. Use queryTaxonomyOptions when live taxonomy vocabulary would make the next search more precise.+5. Keep source grounding internal and summarize relevant results without revealing internal identifiers.+</retrieval_guidelines>`;diff --git a/packages/builtin-tool-memory/src/resolveRestrictedManifest.test.ts b/packages/builtin-tool-memory/src/resolveRestrictedManifest.test.tsnew file mode 100644index 00000000000..47372b04d77--- /dev/null+++ b/packages/builtin-tool-memory/src/resolveRestrictedManifest.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';++import { memoryReadOnlySystemPrompt } from './readOnlySystemRole';+import { resolveMemoryRestrictedManifest } from './resolveRestrictedManifest';+import { MEMORY_READ_API_NAMES, MEMORY_WRITE_API_NAMES, MemoryApiName } from './types';++describe('resolveMemoryRestrictedManifest', () => {+ it('returns the read-only Share manifest for the exact API set regardless of order', () => {+ const manifest = resolveMemoryRestrictedManifest({+ allowedApiNames: [...MEMORY_READ_API_NAMES].reverse(),+ restriction: 'agentShare',+ });++ expect(manifest?.api.map((api) => api.name).sort()).toEqual([...MEMORY_READ_API_NAMES].sort());+ expect(manifest?.systemRole).toBe(memoryReadOnlySystemPrompt);+ });++ it('fails closed for unknown subsets and non-Share restrictions', () => {+ expect(+ resolveMemoryRestrictedManifest({+ allowedApiNames: [MemoryApiName.searchUserMemory],+ restriction: 'agentShare',+ }),+ ).toBeUndefined();+ expect(+ resolveMemoryRestrictedManifest({+ allowedApiNames: [...MEMORY_READ_API_NAMES],+ restriction: 'toolSelection',+ }),+ ).toBeUndefined();+ });++ it('documents retrieval without advertising memory writes', () => {+ for (const apiName of MEMORY_READ_API_NAMES) {+ expect(memoryReadOnlySystemPrompt).toContain(apiName);+ }+ for (const apiName of MEMORY_WRITE_API_NAMES) {+ expect(memoryReadOnlySystemPrompt).not.toContain(apiName);+ }+ });+});diff --git a/packages/builtin-tool-memory/src/resolveRestrictedManifest.ts b/packages/builtin-tool-memory/src/resolveRestrictedManifest.tsnew file mode 100644index 00000000000..101e5c0bf0b--- /dev/null+++ b/packages/builtin-tool-memory/src/resolveRestrictedManifest.ts@@ -0,0 +1,28 @@+import type { BuiltinRestrictedManifestResolver } from '@lobechat/types';++import { MemoryManifest } from './manifest';+import { memoryReadOnlySystemPrompt } from './readOnlySystemRole';+import { MEMORY_READ_API_NAMES } from './types';++const memoryReadApiNames = new Set<string>(MEMORY_READ_API_NAMES);++const matchesExactApiSet = (apiNames: readonly string[], expected: ReadonlySet<string>) => {+ const actual = new Set(apiNames);++ return actual.size === expected.size && [...actual].every((apiName) => expected.has(apiName));+};++export const resolveMemoryRestrictedManifest: BuiltinRestrictedManifestResolver = ({+ allowedApiNames,+ restriction,+}) => {+ if (restriction !== 'agentShare' || !matchesExactApiSet(allowedApiNames, memoryReadApiNames)) {+ return undefined;+ }++ return {+ ...MemoryManifest,+ api: MemoryManifest.api.filter((api) => memoryReadApiNames.has(api.name)),+ systemRole: memoryReadOnlySystemPrompt,+ };+};diff --git a/packages/builtin-tool-memory/src/types.ts b/packages/builtin-tool-memory/src/types.tsindex 6e31b9f54dc..42542aa9080 100644--- a/packages/builtin-tool-memory/src/types.ts+++ b/packages/builtin-tool-memory/src/types.ts@@ -24,6 +24,12 @@ export const MemoryApiName = {export type MemoryApiNameType = (typeof MemoryApiName)[keyof typeof MemoryApiName];+/** APIs available to an Agent Share visitor when the creator grants read access. */+export const MEMORY_READ_API_NAMES: ReadonlySet<MemoryApiNameType> = new Set([+ MemoryApiName.queryTaxonomyOptions,+ MemoryApiName.searchUserMemory,+]);+/*** APIs that mutate the user's memory store. Single source of truth shared by* the Agent Share server gate (which strips them from visitor runsdiff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex 4ffe76578fb..a7d794bf5be 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -1,7 +1,10 @@import { AcceptanceEvidenceManifest } from '@lobechat/builtin-tool-acceptance-evidence';import { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';-import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';+import {+ AgentDocumentsManifest,+ resolveAgentDocumentsRestrictedManifest,+} from '@lobechat/builtin-tool-agent-documents';import {AgentManagementManifest,resolveAgentManagementManifest,@@ -28,7 +31,7 @@ import {LocalSystemManifest,resolveLocalSystemManifest,} from '@lobechat/builtin-tool-local-system';-import { MemoryManifest } from '@lobechat/builtin-tool-memory';+import { MemoryManifest, resolveMemoryRestrictedManifest } from '@lobechat/builtin-tool-memory';import { MessageManifest, resolveMessageManifest } from '@lobechat/builtin-tool-message';import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';@@ -247,7 +250,8 @@ export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([* `apps/server/src/services/aiAgent/shareGate.ts`, for every API and no matter* what the share config says. There is no knowledge-base or agent-file grant* in `AgentShareConfig` at all (see `applyShareGateToAgentConfig`), so a- * visitor run can never reach either store.+ * visitor run can never reach the knowledge-base store. Agent Documents is+ * separately narrowed to share-scoped authoring APIs.** Memory is deliberately NOT here: its grant is conditional on* `allowReadMemory`, so the owner enabling that switch does change what a@@ -262,7 +266,6 @@ export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([*/export const AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS = new Set<string>([KnowledgeBaseManifest.identifier,- AgentDocumentsManifest.identifier,]);const builtinToolRegistry: LobeBuiltinTool[] = [@@ -372,6 +375,7 @@ const builtinToolRegistry: LobeBuiltinTool[] = [hidden: true,identifier: MemoryManifest.identifier,manifest: MemoryManifest,+ resolveRestrictedManifest: resolveMemoryRestrictedManifest,type: 'builtin',},{@@ -389,6 +393,7 @@ const builtinToolRegistry: LobeBuiltinTool[] = [{identifier: AgentDocumentsManifest.identifier,manifest: AgentDocumentsManifest,+ resolveRestrictedManifest: resolveAgentDocumentsRestrictedManifest,type: 'builtin',},{diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.tsindex ad3fe0ddd63..e9a828ab616 100644--- a/packages/database/src/models/__tests__/document.test.ts+++ b/packages/database/src/models/__tests__/document.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { agentShareFileAccessScope } from '@lobechat/types';+import { agentShareDocumentAccessScope, agentShareFileAccessScope } from '@lobechat/types';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -377,6 +377,63 @@ describe('DocumentModel', () => {});describe('findById', () => {+ it('hides a generated Agent Share document from ordinary document reads', async () => {+ const shareDocumentModel = new DocumentModel(+ serverDB,+ userId,+ undefined,+ undefined,+ agentShareDocumentAccessScope({+ shareId: 'share-a',+ topicId: 'topic-a',+ visitorUserId: 'visitor-a',+ }),+ );+ const { id: documentId, slug } = await shareDocumentModel.create({+ content: 'private generated visitor content',+ fileType: 'custom/document',+ filename: 'visitor-note.md',+ source: 'agent-document://agent-a/visitor-note.md',+ sourceType: 'agent',+ title: 'Visitor note',+ totalCharCount: 33,+ totalLineCount: 1,+ });++ await expect(documentModel.query({ sourceTypes: ['agent'] })).resolves.toMatchObject({+ items: [],+ total: 0,+ });+ await expect(documentModel.findById(documentId)).resolves.toBeUndefined();+ await expect(documentModel.findByIds([documentId])).resolves.toEqual([]);+ await expect(documentModel.findBySlug(slug!)).resolves.toBeUndefined();+ await expect(shareDocumentModel.findById(documentId)).resolves.toBeDefined();+ });++ it('strips caller-supplied Agent Share provenance from ordinary document creates', async () => {+ const created = await documentModel.create({+ content: 'ordinary content',+ fileType: 'custom/document',+ filename: 'ordinary.md',+ metadata: {+ agentShare: {+ shareId: 'forged-share',+ topicId: 'forged-topic',+ visitorUserId: 'forged-visitor',+ },+ purpose: 'ordinary',+ },+ source: 'document',+ sourceType: 'api',+ title: 'Ordinary note',+ totalCharCount: 16,+ totalLineCount: 1,+ });++ expect(created.metadata).toEqual({ purpose: 'ordinary' });+ await expect(documentModel.findById(created.id)).resolves.toBeDefined();+ });+it('hides a document derived from an agent-share file from ordinary document reads', async () => {const { id: fileId } = await fileModel.create({fileType: 'application/pdf',diff --git a/packages/database/src/models/__tests__/topicDocument.test.ts b/packages/database/src/models/__tests__/topicDocument.test.tsindex 30766c109ff..bc9e08f6dd7 100644--- a/packages/database/src/models/__tests__/topicDocument.test.ts+++ b/packages/database/src/models/__tests__/topicDocument.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { agentShareDocumentAccessScope } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -229,6 +230,45 @@ describe('TopicDocumentModel', () => {expect(docsForUser2).toHaveLength(0);});+ it('isolates Agent Share documents from ordinary topic reads', async () => {+ const accessScope = agentShareDocumentAccessScope({+ shareId: 'share-topic-documents',+ topicId,+ visitorUserId: 'visitor-topic-documents',+ });+ const shareDocumentModel = new DocumentModel(+ serverDB,+ userId,+ undefined,+ undefined,+ accessScope,+ );+ const shareTopicDocumentModel = new TopicDocumentModel(+ serverDB,+ userId,+ undefined,+ accessScope,+ );+ const otherShareTopicDocumentModel = new TopicDocumentModel(+ serverDB,+ userId,+ undefined,+ agentShareDocumentAccessScope({+ shareId: 'other-share',+ topicId,+ visitorUserId: 'visitor-topic-documents',+ }),+ );+ const doc = await createTestDocument(shareDocumentModel, 'Visitor Document');+ await topicDocumentModel.associate({ documentId: doc.id, topicId });++ await expect(topicDocumentModel.findByTopicId(topicId)).resolves.toEqual([]);+ await expect(otherShareTopicDocumentModel.findByTopicId(topicId)).resolves.toEqual([]);+ await expect(shareTopicDocumentModel.findByTopicId(topicId)).resolves.toMatchObject([+ { id: doc.id, title: 'Visitor Document' },+ ]);+ });+it('drops a doc that was flipped back to private after the association was created', async () => {// Workspace-shared: A associates a public doc with the topic. Then A// flips the doc back to `private`. Other members' subsequent read of thediff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.tsindex 23c4784923d..9730110b02b 100644--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts@@ -4,6 +4,7 @@ import {AGENT_DOCUMENT_SOURCE_TYPE,AGENT_SIGNAL_SOURCE_TYPE,} from '@lobechat/const';+import { agentShareDocumentAccessScope } from '@lobechat/types';import { and, eq } from 'drizzle-orm';import { beforeEach, describe, expect, it } from 'vitest';@@ -343,6 +344,85 @@ describe('AgentDocumentModel', () => {expect(first.documentId).not.toBe(second.documentId);});++ it('stamps server-owned share provenance and isolates the document from ordinary access', async () => {+ const shareModel = new AgentDocumentModel(+ serverDB,+ userId,+ undefined,+ agentShareDocumentAccessScope({+ shareId: 'share-a',+ topicId: 'topic-a',+ visitorUserId: 'visitor-a',+ }),+ );++ const created = await shareModel.create(agentId, 'visitor-note.md', 'draft', {+ metadata: {+ agentShare: {+ shareId: 'forged-share',+ topicId: 'forged-topic',+ visitorUserId: 'forged-visitor',+ },+ purpose: 'handoff',+ },+ });++ expect(created.metadata).toEqual({+ agentShare: {+ shareId: 'share-a',+ topicId: 'topic-a',+ visitorUserId: 'visitor-a',+ },+ purpose: 'handoff',+ });+ await expect(agentDocumentModel.findById(created.id)).resolves.toBeUndefined();+ await expect(agentDocumentModel.findByAgent(agentId)).resolves.toEqual([]);+ await expect(shareModel.findById(created.id)).resolves.toMatchObject({ content: 'draft' });+ });++ it('isolates share documents by share, visitor, and topic', async () => {+ const scope = (shareId: string, visitorUserId: string, topicId: string) =>+ new AgentDocumentModel(+ serverDB,+ userId,+ undefined,+ agentShareDocumentAccessScope({ shareId, topicId, visitorUserId }),+ );+ const owner = scope('share-a', 'visitor-a', 'topic-a');+ const created = await owner.create(agentId, 'scoped.md', 'private to this run');++ await expect(+ scope('share-b', 'visitor-a', 'topic-a').findById(created.id),+ ).resolves.toBeUndefined();+ await expect(+ scope('share-a', 'visitor-b', 'topic-a').findById(created.id),+ ).resolves.toBeUndefined();+ await expect(+ scope('share-a', 'visitor-a', 'topic-b').findById(created.id),+ ).resolves.toBeUndefined();++ await owner.update(created.id, { content: 'updated in scope' });+ await expect(owner.findById(created.id)).resolves.toMatchObject({+ content: 'updated in scope',+ });+ });++ it('strips caller-supplied share provenance from ordinary documents', async () => {+ const created = await agentDocumentModel.create(agentId, 'ordinary.md', 'ordinary', {+ metadata: {+ agentShare: {+ shareId: 'forged-share',+ topicId: 'forged-topic',+ visitorUserId: 'forged-visitor',+ },+ purpose: 'ordinary',+ },+ });++ expect(created.metadata).toEqual({ purpose: 'ordinary' });+ await expect(agentDocumentModel.findById(created.id)).resolves.toBeDefined();+ });});describe('findById and findByFilename', () => {diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex cb6ebb27502..6d1c3ce9510 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -1,9 +1,25 @@import { AGENT_DOCUMENT_FILE_TYPE, AGENT_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';-import { and, asc, desc, eq, inArray, isNotNull, isNull, like, ne, or, sql } from 'drizzle-orm';+import type { DocumentAccessScope } from '@lobechat/types';+import { ordinaryDocumentAccessScope, stripAgentShareDocumentProvenance } from '@lobechat/types';+import {+ and,+ asc,+ desc,+ eq,+ exists,+ inArray,+ isNotNull,+ isNull,+ like,+ ne,+ or,+ sql,+} from 'drizzle-orm';import type { DocumentItem, NewAgentDocument, NewDocument } from '../../schemas';import { AGENT_SKILL_TEMPLATE_ID, agentDocuments, documents } from '../../schemas';import type { LobeChatDatabase, Transaction } from '../../type';+import { documentMatchesAccessScope } from '../../utils/documentVisibility';import { buildWorkspaceWhere } from '../../utils/workspace';import { deriveAgentDocumentFields } from './deriveFields';import { buildDocumentFilename } from './filename';@@ -90,11 +106,18 @@ export class AgentDocumentModel {private userId: string;private workspaceId?: string;private db: LobeChatDatabase;-- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ private documentAccessScope: DocumentAccessScope;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,+ ) {this.userId = userId;this.workspaceId = workspaceId;this.db = db;+ this.documentAccessScope = documentAccessScope;}/**@@ -102,15 +125,28 @@ export class AgentDocumentModel {* Personal mode → `user_id = ? AND workspace_id IS NULL`; workspace mode → `workspace_id = ?`.*/private agentDocOwnership() {- return buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },- agentDocuments,+ return and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentDocuments),+ exists(+ this.db+ .select({ id: documents.id })+ .from(documents)+ .where(+ and(+ eq(documents.id, agentDocuments.documentId),+ documentMatchesAccessScope(documents.metadata, this.documentAccessScope),+ ),+ ),+ ),);}/** Workspace-aware ownership predicate for the backing `documents` rows. */private documentOwnership() {- return buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents);+ return and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),+ documentMatchesAccessScope(documents.metadata, this.documentAccessScope),+ );}private getDocumentStats(content: string) {@@ -137,6 +173,20 @@ export class AgentDocumentModel {return typeof description === 'string' ? description : undefined;}+ private scopeMetadata(metadata?: Record<string, any>): Record<string, any> | undefined {+ const sanitizedMetadata = stripAgentShareDocumentProvenance(metadata);+ if (this.documentAccessScope.type !== 'agentShare') return sanitizedMetadata;++ return {+ ...sanitizedMetadata,+ agentShare: {+ shareId: this.documentAccessScope.shareId,+ topicId: this.documentAccessScope.topicId,+ visitorUserId: this.documentAccessScope.visitorUserId,+ },+ };+ }+private toAgentDocument(settings: typeof agentDocuments.$inferSelect,doc: DocumentItem,@@ -385,11 +435,12 @@ export class AgentDocumentModel {const title = providedTitle?.trim() || filename.replace(/\.[^.]+$/, '');const stats = this.getDocumentStats(content);const normalizedPolicy = normalizePolicy(loadPosition, loadRules, policy);+ const scopedMetadata = this.scopeMetadata(metadata);const documentPayload: NewDocument = {content,createdAt,- description: this.getMetadataDescription(metadata),+ description: this.getMetadataDescription(scopedMetadata),// NOTICE:// Agent documents often carry Markdown `content`, but editor history and restore UI// depend on this serialized editor snapshot. Service callers that derive content from@@ -401,7 +452,7 @@ export class AgentDocumentModel {fileType,filename,parentId,- metadata,+ metadata: scopedMetadata,source: source ?? `agent-document://${agentId}/${encodeURIComponent(filename)}`,sourceType,title,@@ -506,16 +557,17 @@ export class AgentDocumentModel {const stats = this.getDocumentStats(params.content);const updatedAt = new Date();+ const scopedMetadata = this.scopeMetadata(params.metadata);await trx.update(documents).set({content: params.content,- description: this.getMetadataDescription(params.metadata),+ description: this.getMetadataDescription(scopedMetadata),...(params.editorData !== undefined && { editorData: params.editorData }),filename: params.filename,fileType: 'skills/index',- metadata: params.metadata,+ metadata: scopedMetadata,parentId: params.parentId,source: params.source,sourceType: params.sourceType,@@ -641,8 +693,9 @@ export class AgentDocumentModel {}if (metadata !== undefined) {- documentUpdate.metadata = metadata;- documentUpdate.description = this.getMetadataDescription(metadata);+ const scopedMetadata = this.scopeMetadata(metadata);+ documentUpdate.metadata = scopedMetadata;+ documentUpdate.description = this.getMetadataDescription(scopedMetadata);}await trx@@ -699,8 +752,8 @@ export class AgentDocumentModel {.set({...(params.filename !== undefined && { filename: params.filename }),...(params.metadata !== undefined && {- description: this.getMetadataDescription(params.metadata),- metadata: params.metadata,+ description: this.getMetadataDescription(this.scopeMetadata(params.metadata)),+ metadata: this.scopeMetadata(params.metadata),}),...(params.parentId !== undefined && { parentId: params.parentId }),...(params.title !== undefined && { title: params.title }),diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex d07814e38aa..65673d86eac 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -1,6 +1,10 @@import { AGENT_ARTIFACT_SOURCE_TYPES } from '@lobechat/const';-import type { FileAccessScope } from '@lobechat/types';-import { ordinaryFileAccessScope } from '@lobechat/types';+import type { DocumentAccessScope, FileAccessScope } from '@lobechat/types';+import {+ ordinaryDocumentAccessScope,+ ordinaryFileAccessScope,+ stripAgentShareDocumentProvenance,+} from '@lobechat/types';import { and, asc, count, desc, eq, inArray, isNull, ne, notInArray, or, sum } from 'drizzle-orm';import type { DocumentItem, NewDocument } from '../schemas';@@ -15,6 +19,7 @@ import {works,} from '../schemas';import type { LobeChatDatabase } from '../type';+import { documentMatchesAccessScope } from '../utils/documentVisibility';import {fileReferenceMatchesAccessScope,notAgentShareFileReference,@@ -41,6 +46,7 @@ export class DocumentModel {private userId: string;private db: LobeChatDatabase;private workspaceId?: string;+ private documentAccessScope: DocumentAccessScope;/*** Visibility of the agent that owns the calling tool execution, when this* model is instantiated inside a tool runtime. `'public'` tightens@@ -57,11 +63,13 @@ export class DocumentModel {userId: string,workspaceId?: string,callerAgentVisibility?: 'private' | 'public' | null,+ documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,) {this.userId = userId;this.db = db;this.workspaceId = workspaceId;this.callerAgentVisibility = callerAgentVisibility;+ this.documentAccessScope = documentAccessScope;}private ownership = () =>@@ -74,13 +82,31 @@ export class DocumentModel {documents,);- private ordinaryReadScope = () =>- and(this.ownership(), notAgentShareFileReference(this.db, documents.fileId));+ private readScope = () =>+ and(+ this.ownership(),+ documentMatchesAccessScope(documents.metadata, this.documentAccessScope),+ notAgentShareFileReference(this.db, documents.fileId),+ );++ private scopeMetadata = (metadata?: Record<string, any> | null) => {+ const sanitizedMetadata = stripAgentShareDocumentProvenance(metadata);+ if (this.documentAccessScope.type !== 'agentShare') return sanitizedMetadata;++ return {+ ...sanitizedMetadata,+ agentShare: {+ shareId: this.documentAccessScope.shareId,+ topicId: this.documentAccessScope.topicId,+ visitorUserId: this.documentAccessScope.visitorUserId,+ },+ };+ };findOrCreateFolder = async (name: string, parentId?: string): Promise<DocumentItem> => {const existing = await this.db.query.documents.findFirst({where: and(- this.ownership(),+ this.readScope(),eq(documents.fileType, DOCUMENT_FOLDER_TYPE),eq(documents.filename, name),parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),@@ -123,7 +149,11 @@ export class DocumentModel {.values(buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId },- { ...params, ...(visibility ? { visibility } : {}) },+ {+ ...params,+ metadata: this.scopeMetadata(params.metadata),+ ...(visibility ? { visibility } : {}),+ },),).returning()) as DocumentItem[];@@ -132,11 +162,11 @@ export class DocumentModel {};delete = async (id: string) => {- return this.db.delete(documents).where(and(eq(documents.id, id), this.ownership()));+ return this.db.delete(documents).where(and(eq(documents.id, id), this.readScope()));};deleteAll = async () => {- return this.db.delete(documents).where(this.ownership());+ return this.db.delete(documents).where(this.readScope());};query = async ({@@ -150,7 +180,7 @@ export class DocumentModel {total: number;}> => {const offset = current * pageSize;- const conditions = [this.ordinaryReadScope()];+ const conditions = [this.readScope()];if (fileTypes?.length) {conditions.push(inArray(documents.fileType, fileTypes));@@ -245,7 +275,7 @@ export class DocumentModel {const [document] = await this.db.select().from(documents)- .where(and(this.ordinaryReadScope(), eq(documents.id, id)))+ .where(and(this.readScope(), eq(documents.id, id))).limit(1);return document;};@@ -255,7 +285,7 @@ export class DocumentModel {return this.db.select().from(documents)- .where(and(this.ordinaryReadScope(), inArray(documents.id, ids)));+ .where(and(this.readScope(), inArray(documents.id, ids)));};findByFileId = async (fileId: string, accessScope: FileAccessScope = ordinaryFileAccessScope) => {@@ -283,7 +313,7 @@ export class DocumentModel {const [document] = await this.db.select().from(documents)- .where(and(this.ordinaryReadScope(), eq(documents.slug, slug)))+ .where(and(this.readScope(), eq(documents.slug, slug))).limit(1);return document;};@@ -303,11 +333,7 @@ export class DocumentModel {.select().from(documents).where(- and(- this.ordinaryReadScope(),- eq(documents.source, source),- eq(documents.sourceType, sourceType),- ),+ and(this.readScope(), eq(documents.source, source), eq(documents.sourceType, sourceType)),).limit(1);return document;@@ -317,12 +343,16 @@ export class DocumentModel {// visibility is intentionally not updatable via this path. The only legal// transition is `private → public` via `publishToWorkspace`; strip any// incoming value so callers can't sneak around the one-way rule.- const { visibility: _ignored, ...patch } = value;+ const { metadata, visibility: _ignored, ...patch } = value;return this.db.update(documents)- .set({ ...patch, updatedAt: new Date() })- .where(and(this.ownership(), eq(documents.id, id)));+ .set({+ ...patch,+ ...(metadata !== undefined && { metadata: this.scopeMetadata(metadata) }),+ updatedAt: new Date(),+ })+ .where(and(this.readScope(), eq(documents.id, id)));};/**diff --git a/packages/database/src/models/topicDocument.ts b/packages/database/src/models/topicDocument.tsindex ccd4746bfa8..765702d56ff 100644--- a/packages/database/src/models/topicDocument.ts+++ b/packages/database/src/models/topicDocument.ts@@ -1,8 +1,11 @@+import type { DocumentAccessScope } from '@lobechat/types';+import { ordinaryDocumentAccessScope } from '@lobechat/types';import { and, desc, eq } from 'drizzle-orm';import type { DocumentItem, NewTopicDocument } from '../schemas';import { documents, topicDocuments } from '../schemas';import type { LobeChatDatabase } from '../type';+import { documentMatchesAccessScope } from '../utils/documentVisibility';import { buildWorkspaceWhere } from '../utils/workspace';export interface TopicDocumentWithDetails extends DocumentItem {@@ -13,11 +16,18 @@ export class TopicDocumentModel {private userId: string;private db: LobeChatDatabase;private workspaceId?: string;-- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ private documentAccessScope: DocumentAccessScope;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ documentAccessScope: DocumentAccessScope = ordinaryDocumentAccessScope,+ ) {this.userId = userId;this.db = db;this.workspaceId = workspaceId;+ this.documentAccessScope = documentAccessScope;}private ownership = () =>@@ -85,6 +95,7 @@ export class TopicDocumentModel {eq(topicDocuments.topicId, topicId),this.ownership(),buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),+ documentMatchesAccessScope(documents.metadata, this.documentAccessScope),filter?.type ? eq(documents.fileType, filter.type) : undefined,),)diff --git a/packages/database/src/models/work/__tests__/document.test.ts b/packages/database/src/models/work/__tests__/document.test.tsindex 5b6d838ae67..2a8f38ef628 100644--- a/packages/database/src/models/work/__tests__/document.test.ts+++ b/packages/database/src/models/work/__tests__/document.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { agentShareDocumentAccessScope } from '@lobechat/types';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -88,6 +89,38 @@ describe('WorkModel · document', () => {});});+ it('does not register Agent Share documents in the ordinary Work registry', async () => {+ const agentDocumentModel = new AgentDocumentModel(+ serverDB,+ userId,+ undefined,+ agentShareDocumentAccessScope({+ shareId: 'share-work',+ topicId,+ visitorUserId: 'visitor-work',+ }),+ );+ const workModel = new WorkModel(serverDB, userId);+ const doc = await agentDocumentModel.create(agentId, 'visitor-note.md', 'Visitor draft');++ const work = await workModel.registerDocument({+ agentDocumentId: doc.id,+ agentId,+ changeType: 'created',+ documentId: doc.documentId,+ rootOperationId: 'op-share-doc-create',+ toolCallId: 'tool-call-share-doc-create',+ toolIdentifier: 'lobe-agent-documents',+ toolName: 'createDocument',+ topicId,+ });++ expect(work).toBeNull();+ expect(await serverDB.select().from(works).where(eq(works.resourceId, doc.documentId))).toEqual(+ [],+ );+ });+it('uses the document content prefix when document description is empty', async () => {const agentDocumentModel = new AgentDocumentModel(serverDB, userId);const workModel = new WorkModel(serverDB, userId);diff --git a/packages/database/src/models/work/document.ts b/packages/database/src/models/work/document.tsindex d5e46760261..96e3bc7fda7 100644--- a/packages/database/src/models/work/document.ts+++ b/packages/database/src/models/work/document.ts@@ -4,6 +4,7 @@ import { and, eq, isNull } from 'drizzle-orm';import { agentDocuments } from '../../schemas/agentDocuments';import { type DocumentItem, documents } from '../../schemas/file';+import { notAgentShareDocument } from '../../utils/documentVisibility';import { agentDocumentOwnership, documentOwnership, type WorkContext } from './context';import { createDisplayWorkAdapter } from './displayWork';import { truncateSummaryText, type WorkDisplayColumns } from './internal';@@ -43,7 +44,13 @@ const resolveDocument = async (const [doc] = await ctx.db.select().from(documents)- .where(and(documentOwnership(ctx), eq(documents.id, params.documentId)))+ .where(+ and(+ documentOwnership(ctx),+ eq(documents.id, params.documentId),+ notAgentShareDocument(documents.metadata),+ ),+ ).limit(1);if (!doc) return null;diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.tsindex d9987e6ae25..632c9eb5b2b 100644--- a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts@@ -26,6 +26,7 @@ import {userMemories,} from '../../../schemas';import type { LobeChatDatabase } from '../../../type';+import { notAgentShareDocument } from '../../../utils/documentVisibility';import { libraryVisibleFile, notAgentShareFileReference } from '../../../utils/fileVisibility';import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';import { searchableMessage } from '../../../utils/searchableMessage';@@ -612,6 +613,7 @@ export const hydratePages = async (),buildWorkspaceWhere(scope, documents),eq(documents.fileType, 'custom/document'),+ notAgentShareDocument(documents.metadata),notAgentShareFileReference(db, documents.fileId),),);@@ -668,6 +670,7 @@ export const hydrateKnowledgeBaseDocuments = async (),buildWorkspaceWhere(scope, documents),ne(documents.fileType, DOCUMENT_FOLDER_TYPE),+ notAgentShareDocument(documents.metadata),notAgentShareFileReference(db, documents.fileId),),);@@ -703,6 +706,7 @@ export const hydrateKnowledgeBaseDocuments = async (and(inArray(documents.id, selectedDocumentIds),buildWorkspaceWhere(scope, documents),+ notAgentShareDocument(documents.metadata),notAgentShareFileReference(db, documents.fileId),),);diff --git a/packages/database/src/repositories/ftsSearch/postgres/documents.ts b/packages/database/src/repositories/ftsSearch/postgres/documents.tsindex 1bf7028bda2..b917d8824e2 100644--- a/packages/database/src/repositories/ftsSearch/postgres/documents.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/documents.ts@@ -2,6 +2,7 @@ import type { SQLWrapper } from 'drizzle-orm';import { and, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';import { DOCUMENT_FOLDER_TYPE, documents, knowledgeBaseFiles } from '../../../schemas';+import { notAgentShareDocument } from '../../../utils/documentVisibility';import { notAgentShareFileReference } from '../../../utils/fileVisibility';import { buildWorkspaceWhere } from '../../../utils/workspace';import type {@@ -50,6 +51,7 @@ export async function searchFolders(filename: documents.filename,id: documents.id,knowledgeBaseId: documents.knowledgeBaseId,+ metadata: documents.metadata,score: score.as('score'),slug: documents.slug,title: documents.title,@@ -85,6 +87,7 @@ export async function searchFolders(.where(and(context.liftedScopeWhere(hits.workspaceId),+ notAgentShareDocument(hits.metadata),context.liftsExclusionFilter ? excludeKb(hits.knowledgeBaseId) : undefined,),)@@ -143,6 +146,7 @@ export async function searchPages(filename: documents.filename,id: documents.id,knowledgeBaseId: documents.knowledgeBaseId,+ metadata: documents.metadata,score: score.as('score'),title: documents.title,updatedAt: documents.updatedAt,@@ -176,6 +180,7 @@ export async function searchPages(.where(and(context.liftedScopeWhere(hits.workspaceId),+ notAgentShareDocument(hits.metadata),notAgentShareFileReference(db, hits.fileId),context.liftsExclusionFilter ? excludeKb(hits.knowledgeBaseId, hits.fileId) : undefined,),@@ -221,14 +226,15 @@ export async function searchKnowledgeBaseDocuments(const folderClause = ne(documents.fileType, DOCUMENT_FOLDER_TYPE);const userClause = buildWorkspaceWhere(context.scope, documents);- const inlineRowsPromise = db+ const inlineHits = db.select({content: documents.content,fileId: documents.fileId,filename: documents.filename,id: documents.id,knowledgeBaseId: documents.knowledgeBaseId,- score,+ metadata: documents.metadata,+ score: score.as('score'),title: documents.title,updatedAt: documents.updatedAt,})@@ -243,16 +249,34 @@ export async function searchKnowledgeBaseDocuments(),).orderBy(sql`${score} DESC`)+ .limit(context.scanCandidateLimit(limit))+ .as('inline_hits');++ const inlineRowsPromise = db+ .select({+ content: inlineHits.content,+ fileId: inlineHits.fileId,+ filename: inlineHits.filename,+ id: inlineHits.id,+ knowledgeBaseId: inlineHits.knowledgeBaseId,+ score: inlineHits.score,+ title: inlineHits.title,+ updatedAt: inlineHits.updatedAt,+ })+ .from(inlineHits)+ .where(notAgentShareDocument(inlineHits.metadata))+ .orderBy(desc(inlineHits.score)).limit(limit);- const fileBackedRowsPromise = db+ const fileBackedHits = db.select({content: documents.content,fileId: documents.fileId,filename: documents.filename,id: documents.id,knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,- score,+ metadata: documents.metadata,+ score: score.as('score'),title: documents.title,updatedAt: documents.updatedAt,})@@ -269,6 +293,23 @@ export async function searchKnowledgeBaseDocuments(and(userClause, folderClause, notAgentShareFileReference(db, documents.fileId), matchClause),).orderBy(sql`${score} DESC`)+ .limit(context.scanCandidateLimit(limit))+ .as('file_backed_hits');++ const fileBackedRowsPromise = db+ .select({+ content: fileBackedHits.content,+ fileId: fileBackedHits.fileId,+ filename: fileBackedHits.filename,+ id: fileBackedHits.id,+ knowledgeBaseId: fileBackedHits.knowledgeBaseId,+ score: fileBackedHits.score,+ title: fileBackedHits.title,+ updatedAt: fileBackedHits.updatedAt,+ })+ .from(fileBackedHits)+ .where(notAgentShareDocument(fileBackedHits.metadata))+ .orderBy(desc(fileBackedHits.score)).limit(limit);const [inlineRows, fileBackedRows] = await Promise.all([diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.test.ts b/packages/database/src/repositories/ftsSearchDocument/builder.test.tsindex f4c8576a90c..bed872504ae 100644--- a/packages/database/src/repositories/ftsSearchDocument/builder.test.ts+++ b/packages/database/src/repositories/ftsSearchDocument/builder.test.ts@@ -338,7 +338,7 @@ describe('FtsSearchDocumentBuilder', () => {expect(result.map(({ id }) => id)).toEqual(['agent-1']);});- it('omits files carrying agent-share provenance from the search projection', async () => {+ it('omits files and generated documents carrying Agent Share provenance', async () => {await db.insert(files).values({fileType: 'text/plain',id: 'file-agent-share',@@ -364,6 +364,28 @@ describe('FtsSearchDocumentBuilder', () => {userId,});await expect(builder.buildByIds('documents', ['document-agent-share'])).resolves.toEqual([]);++ await db.insert(documents).values({+ content: 'Private generated visitor document',+ fileType: 'custom/document',+ id: 'generated-document-agent-share',+ metadata: {+ agentShare: {+ shareId: 'share-1',+ topicId: 'topic-1',+ visitorUserId: 'visitor-1',+ },+ },+ source: 'agent-document://agent-1/private.md',+ sourceType: 'agent',+ title: 'Private generated visitor document',+ totalCharCount: 34,+ totalLineCount: 1,+ userId,+ });+ await expect(+ builder.buildByIds('documents', ['generated-document-agent-share']),+ ).resolves.toEqual([]);});it('rejects invalid batch limits before querying PostgreSQL', async () => {diff --git a/packages/database/src/repositories/ftsSearchDocument/builder.ts b/packages/database/src/repositories/ftsSearchDocument/builder.tsindex 05f455058d6..5326e10e0ec 100644--- a/packages/database/src/repositories/ftsSearchDocument/builder.ts+++ b/packages/database/src/repositories/ftsSearchDocument/builder.ts@@ -18,6 +18,7 @@ import {userPersonaDocuments,} from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { notAgentShareDocument } from '../../utils/documentVisibility';import { notAgentShareFile, notAgentShareFileReference } from '../../utils/fileVisibility';import { searchableMessage } from '../../utils/searchableMessage';import type {@@ -934,6 +935,7 @@ export class FtsSearchDocumentBuilder {.from(documents).where(and(+ notAgentShareDocument(documents.metadata),notAgentShareFileReference(this.db, documents.fileId),selection.ids? inArray(documents.id, selection.ids)diff --git a/packages/database/src/utils/documentVisibility.ts b/packages/database/src/utils/documentVisibility.tsnew file mode 100644index 00000000000..251b76145c0--- /dev/null+++ b/packages/database/src/utils/documentVisibility.ts@@ -0,0 +1,20 @@+import type { DocumentAccessScope } from '@lobechat/types';+import { and, sql } from 'drizzle-orm';+import type { AnyPgColumn } from 'drizzle-orm/pg-core';++/** Agent Share provenance is an access boundary, not document ownership. */+export const notAgentShareDocument = (metadata: AnyPgColumn) =>+ sql<boolean>`NOT COALESCE(${metadata} ? 'agentShare', false)`;++/** Match a generated document against the caller's explicit access scope. */+export const documentMatchesAccessScope = (+ metadata: AnyPgColumn,+ accessScope: DocumentAccessScope,+) =>+ accessScope.type === 'agentShare'+ ? and(+ sql`${metadata} -> 'agentShare' ->> 'shareId' = ${accessScope.shareId}`,+ sql`${metadata} -> 'agentShare' ->> 'visitorUserId' = ${accessScope.visitorUserId}`,+ sql`${metadata} -> 'agentShare' ->> 'topicId' = ${accessScope.topicId}`,+ )+ : notAgentShareDocument(metadata);diff --git a/packages/types/src/document/access.ts b/packages/types/src/document/access.tsnew file mode 100644index 00000000000..c54b1f2dd26--- /dev/null+++ b/packages/types/src/document/access.ts@@ -0,0 +1,51 @@+import { z } from 'zod';++export const AgentShareDocumentProvenanceSchema = z.object({+ shareId: z.string(),+ topicId: z.string(),+ visitorUserId: z.string(),+});++export type AgentShareDocumentProvenance = z.infer<typeof AgentShareDocumentProvenanceSchema>;++/**+ * Share provenance is an access boundary, not a lifecycle owner. Share-authored documents remain+ * creator-owned and intentionally outlive visitor topics so a creator-facing history can expose+ * them later.+ */+export type DocumentAccessScope =+ ({ type: 'agentShare' } & AgentShareDocumentProvenance) | { type: 'ordinary' };++export const ordinaryDocumentAccessScope = {+ type: 'ordinary',+} as const satisfies DocumentAccessScope;++export const agentShareDocumentAccessScope = (+ provenance: AgentShareDocumentProvenance,+): DocumentAccessScope => ({+ shareId: provenance.shareId,+ topicId: provenance.topicId,+ type: 'agentShare',+ visitorUserId: provenance.visitorUserId,+});++/** Remove server-owned Agent Share provenance from caller-supplied metadata. */+export const stripAgentShareDocumentProvenance = <T>(metadata: T): T => {+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return metadata;++ return Object.fromEntries(+ Object.entries(metadata as Record<string, unknown>).filter(([key]) => key !== 'agentShare'),+ ) as T;+};++/** Read server-written Agent Share provenance without trusting the rest of the JSON metadata. */+export const getAgentShareDocumentProvenance = (+ metadata: unknown,+): AgentShareDocumentProvenance | undefined => {+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return undefined;++ const result = AgentShareDocumentProvenanceSchema.safeParse(+ (metadata as { agentShare?: unknown }).agentShare,+ );+ return result.success ? result.data : undefined;+};diff --git a/packages/types/src/document/index.ts b/packages/types/src/document/index.tsindex 4b4a0cb6f20..27ff0e0db3f 100644--- a/packages/types/src/document/index.ts+++ b/packages/types/src/document/index.ts@@ -1,3 +1,4 @@+export * from './access';export * from './share';/**diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 44a9299745c..cf7d6d7a78a 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -358,6 +358,23 @@ export type BuiltinManifestResolver = (context: BuiltinToolResolveContext,) => BuiltinToolManifest | null;+export interface BuiltinRestrictedManifestResolveContext {+ /** API names left after the runtime has applied its access policy. */+ allowedApiNames: readonly string[];+ /** Policy boundary responsible for the reduced API surface. */+ restriction: 'agentShare' | 'toolSelection';+}++/** Resolve a builtin-owned manifest for a known restricted API surface. */+export type BuiltinRestrictedToolManifest = Omit<BuiltinToolManifest, 'systemRole'> & {+ /** Omit the role when it describes APIs outside the restricted surface. */+ systemRole?: string;+};++export type BuiltinRestrictedManifestResolver = (+ context: BuiltinRestrictedManifestResolveContext,+) => BuiltinRestrictedToolManifest | undefined;+export interface LobeBuiltinTool {/** Identity (hoisted from `manifest.meta`): icon shown in UI lists. */avatar?: string;@@ -378,6 +395,16 @@ export interface LobeBuiltinTool {* a resolver never breaks those synchronous reads.*/resolveManifest?: BuiltinManifestResolver;+ /**+ * Optional manifest for a policy-restricted API subset.+ *+ * This callback stays on the in-process builtin registry rather than the+ * serializable manifest contract. It lets the owning package narrow both+ * instructions and schemas when policy changes their actual semantics.+ * Unknown subsets must return `undefined` so callers fail closed instead of+ * attaching stale capability metadata.+ */+ resolveRestrictedManifest?: BuiltinRestrictedManifestResolver;/** Identity (hoisted from `manifest.meta`): tags shown in UI / discovery. */tags?: string[];/** Identity (hoisted from `manifest.meta`): display name. Falls back to `identifier`. */