🤯 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
♻️ refactor(server): split the 1405-line agentDocumentVfs service into cohesive modules (#21128)
Arvin Xudc52afe6dab2
diff --git a/apps/server/src/services/agentDocumentVfs/deps.ts b/apps/server/src/services/agentDocumentVfs/deps.tsnew file mode 100644index 00000000000..304de945df4--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/deps.ts@@ -0,0 +1,20 @@+import type { AgentDocumentModel } from '@/database/models/agentDocuments';++import type { FileService } from '../file';+import type { SkillMount } from './mounts/skills/SkillMount';++/**+ * Collaborators the `AgentDocumentVfsService` sub-domain modules read.+ *+ * Use when:+ * - A module under `agentDocumentVfs/` needs the per-user document model, the skill mount,+ * or the file service that the service instance owns+ *+ * Expects:+ * - `getFileService` stays lazy so browsing never initializes object storage+ */+export interface AgentDocumentVfsDeps {+ agentDocumentModel: AgentDocumentModel;+ getFileService: () => FileService;+ skillMount: SkillMount;+}diff --git a/apps/server/src/services/agentDocumentVfs/index.move.test.ts b/apps/server/src/services/agentDocumentVfs/index.move.test.tsnew file mode 100644index 00000000000..0361882cbb9--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/index.move.test.ts@@ -0,0 +1,378 @@+// @vitest-environment node+import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentAccess } from '@/database/models/agentDocuments';++import { FileService } from '../file';+import { AgentDocumentVfsService } from './index';+import { db, mockAgentDocumentModel, mockSkillMount, resetVfsMocks, userId } from './testUtils';++vi.mock('@/database/models/agentDocuments', () => ({+ AgentAccess: {+ DELETE: 16,+ EXECUTE: 1,+ LIST: 8,+ READ: 2,+ WRITE: 4,+ },+ AgentDocumentModel: vi.fn(),+ buildDocumentFilename: vi.fn(function (title: string) {+ return title;+ }),+}));++vi.mock('./mounts/skills/createSkillMount', () => ({+ createSkillMount: vi.fn(),+}));++const removeUnreferencedFile = vi.hoisted(() => vi.fn());+vi.mock('../file', () => ({+ FileService: vi.fn(function () {+ return { removeUnreferencedFile };+ }),+}));++const folderDoc = (filename: string, documentId: string, parentId: string | null = null) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId,+ fileType: 'custom/folder',+ filename,+ id: `agent-${documentId}`,+ parentId,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+});++const fileDoc = (+ filename: string,+ documentId: string,+ parentId: string | null = null,+ content = 'hello',+) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content,+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId,+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename,+ id: `agent-${documentId}`,+ parentId,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+});++describe('AgentDocumentVfsService', () => {+ beforeEach(() => {+ vi.mocked(FileService).mockClear();+ removeUnreferencedFile.mockReset().mockResolvedValue(undefined);+ resetVfsMocks();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('rejects copying a directory into its own subtree', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'folder-doc-1',+ fileType: 'custom/folder',+ filename: 'notes',+ id: 'folder-agent-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });++ const service = new AgentDocumentVfsService(db, userId);++ await expect(+ service.copy('./notes', './notes/archive', { agentId: 'agent-1' }),+ ).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();+ });++ it('rejects renaming a directory into its own subtree', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'folder-doc-1',+ fileType: 'custom/folder',+ filename: 'notes',+ id: 'folder-agent-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });++ const service = new AgentDocumentVfsService(db, userId);++ await expect(+ service.rename('./notes', './notes/archive', { agentId: 'agent-1' }),+ ).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();+ });++ it('renames ordinary files by moving the original document path in place', async () => {+ const sourceFile = {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'hello',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'old.md',+ id: 'agent-doc-1',+ parentId: null,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ };+ const movedFile = {+ ...sourceFile,+ filename: 'new.md',+ parentId: 'folder-doc-1',+ };++ mockAgentDocumentModel.listByParentAndFilename.mockImplementation(+ async (_agentId, parentId, filename) => {+ if (parentId === null && filename === 'old.md') return [sourceFile];+ if (parentId === null && filename === 'folder') {+ return [+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ documentId: 'folder-doc-1',+ fileType: 'custom/folder',+ filename: 'folder',+ id: 'folder-agent-doc-1',+ parentId: null,+ },+ ];+ }+ return [];+ },+ );+ mockAgentDocumentModel.movePath.mockResolvedValue(movedFile);++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.rename('./old.md', './folder/new.md', { agentId: 'agent-1' });++ expect(mockAgentDocumentModel.movePath).toHaveBeenCalledWith('agent-doc-1', {+ filename: 'new.md',+ parentId: 'folder-doc-1',+ });+ expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();+ expect(mockAgentDocumentModel.delete).not.toHaveBeenCalled();+ expect(node).toEqual(+ expect.objectContaining({+ agentDocumentId: 'agent-doc-1',+ documentId: 'documents-1',+ path: './folder/new.md',+ }),+ );+ });++ it('rejects recursive directory copy when direct children exceed the safety cap', async () => {+ const sourceFolder = {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'folder-doc-1',+ fileType: 'custom/folder',+ filename: 'notes',+ id: 'folder-agent-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ };+ mockAgentDocumentModel.listByParentAndFilename.mockImplementation(+ async (_agentId, _parentId, filename) => (filename === 'notes' ? [sourceFolder] : []),+ );+ mockAgentDocumentModel.create.mockResolvedValue({+ ...sourceFolder,+ documentId: 'archive-doc-1',+ filename: 'archive',+ id: 'archive-agent-doc-1',+ });+ mockAgentDocumentModel.listByParent.mockResolvedValue(+ Array.from({ length: 5001 }, (_, index) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: `file ${index}`,+ documentId: `doc-${index}`,+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: `file-${index}.md`,+ id: `agent-doc-${index}`,+ })),+ );++ const service = new AgentDocumentVfsService(db, userId);++ await expect(+ service.copy('./notes', './archive', { agentId: 'agent-1' }),+ ).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledWith('agent-1', 'folder-doc-1', {+ limit: 5001,+ });+ });++ it('copies an ordinary directory recursively through mkdir and write', async () => {+ const docs: any[] = [folderDoc('notes', 'notes-doc'), fileDoc('a.md', 'a-doc', 'notes-doc')];+ mockAgentDocumentModel.listByParentAndFilename.mockImplementation(+ async (_agentId, parentId, filename) =>+ docs.filter((doc) => doc.parentId === parentId && doc.filename === filename),+ );+ mockAgentDocumentModel.findByParentAndFilename.mockImplementation(+ async (_agentId, parentId, filename) =>+ docs.find((doc) => doc.parentId === parentId && doc.filename === filename),+ );+ mockAgentDocumentModel.listByParent.mockImplementation(async (_agentId, parentId) =>+ docs.filter((doc) => doc.parentId === parentId),+ );+ mockAgentDocumentModel.create.mockImplementation(+ async (_agentId, filename, content, options) => {+ const doc = {+ ...(options.fileType === 'custom/folder'+ ? folderDoc(filename, `${filename}-copy`, options.parentId)+ : fileDoc(filename, `${filename}-copy`, options.parentId, content)),+ };+ docs.push(doc);+ return doc;+ },+ );++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.copy('./notes', './archive', { agentId: 'agent-1' });++ expect(+ mockAgentDocumentModel.create.mock.calls.map((call) => [call[1], call[3].parentId]),+ ).toEqual([+ ['archive', null],+ ['a.md', 'archive-copy'],+ ]);+ expect(mockAgentDocumentModel.create.mock.calls[1][2]).toContain('hello');+ expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledWith('agent-1', 'notes-doc', {+ limit: 5001,+ });+ expect(node).toEqual(expect.objectContaining({ path: './archive', type: 'directory' }));+ });++ it('rejects copying onto an existing path unless overwrite is set', async () => {+ mockAgentDocumentModel.listByParentAndFilename.mockImplementation(+ async (_agentId, parentId, filename) =>+ parentId === null && (filename === 'a.md' || filename === 'b.md')+ ? [fileDoc(filename, `${filename}-doc`)]+ : [],+ );+ mockAgentDocumentModel.update.mockResolvedValue(undefined);++ const service = new AgentDocumentVfsService(db, userId);++ await expect(service.copy('./a.md', './b.md', { agentId: 'agent-1' })).rejects.toThrow(+ 'Path already exists: ./b.md',+ );++ const node = await service.copy(+ './a.md',+ './b.md',+ { agentId: 'agent-1' },+ { overwrite: true },+ );++ expect(mockAgentDocumentModel.update).toHaveBeenCalledWith(+ 'agent-b.md-doc',+ expect.objectContaining({ content: expect.stringContaining('hello') }),+ );+ expect(node).toEqual(expect.objectContaining({ path: './b.md' }));+ });++ it('moves a mounted skill into the ordinary tree by copying then deleting the source', async () => {+ mockSkillMount.get.mockResolvedValue({+ content: '# Writer',+ name: 'SKILL.md',+ namespace: 'agent',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ type: 'file',+ });+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([]);+ mockAgentDocumentModel.create.mockResolvedValue(fileDoc('writer.md', 'writer-doc'));++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.rename('./lobe/skills/agent/skills/writer', './writer.md', {+ agentId: 'agent-1',+ });++ expect(mockSkillMount.get).toHaveBeenCalledWith({+ agentId: 'agent-1',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ topicId: undefined,+ });+ expect(mockAgentDocumentModel.create).toHaveBeenCalledWith(+ 'agent-1',+ 'writer.md',+ expect.stringContaining('Writer'),+ expect.objectContaining({ parentId: null }),+ );+ expect(mockSkillMount.delete).toHaveBeenCalledWith({+ agentId: 'agent-1',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ topicId: undefined,+ });+ expect(node).toEqual(expect.objectContaining({ path: './writer.md' }));+ });++ it('returns the existing node when renaming a path onto itself', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(fileDoc('a.md', 'doc-1'));++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.rename('./a.md', '/a.md', { agentId: 'agent-1' });++ expect(node).toEqual(expect.objectContaining({ path: './a.md' }));+ expect(mockAgentDocumentModel.movePath).not.toHaveBeenCalled();++ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);+ await expect(service.rename('./b.md', './b.md', { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });++ it('guards ordinary renames against reserved, existing and directory destinations', async () => {+ mockAgentDocumentModel.listByParentAndFilename.mockImplementation(+ async (_agentId, parentId, filename) => {+ if (parentId !== null) return [];+ if (filename === 'a.md') return [fileDoc('a.md', 'a-doc')];+ if (filename === 'b.md') return [fileDoc('b.md', 'b-doc')];+ if (filename === 'dir') return [folderDoc('dir', 'dir-doc')];+ return [];+ },+ );+ mockAgentDocumentModel.listByParent.mockResolvedValue([]);+ mockAgentDocumentModel.movePath.mockResolvedValue(fileDoc('b.md', 'a-doc'));++ const service = new AgentDocumentVfsService(db, userId);+ const ctx = { agentId: 'agent-1' };++ await expect(service.rename('./a.md', './lobe/a.md', ctx)).rejects.toThrow(+ 'Cannot rename to reserved path: ./lobe/a.md',+ );+ await expect(service.rename('./a.md', './b.md', ctx)).rejects.toThrow(+ 'Path already exists: ./b.md',+ );+ await expect(service.rename('./a.md', './dir', ctx, { overwrite: true })).rejects.toThrow(+ 'Cannot overwrite directory path: ./dir',+ );+ await expect(service.rename('./a.md', './missing/a.md', ctx)).rejects.toThrow(+ 'Parent path not found: ./missing',+ );++ const node = await service.rename('./a.md', './b.md', ctx, { overwrite: true });++ expect(mockAgentDocumentModel.delete).toHaveBeenCalledWith('agent-b-doc', 'user-delete');+ expect(mockAgentDocumentModel.movePath).toHaveBeenCalledWith('agent-a-doc', {+ filename: 'b.md',+ parentId: null,+ });+ expect(node).toEqual(expect.objectContaining({ path: './b.md' }));+ });+});diff --git a/apps/server/src/services/agentDocumentVfs/index.read.test.ts b/apps/server/src/services/agentDocumentVfs/index.read.test.tsnew file mode 100644index 00000000000..1c844d8e239--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/index.read.test.ts@@ -0,0 +1,474 @@+// @vitest-environment node+import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentAccess } from '@/database/models/agentDocuments';++import { FileService } from '../file';+import { AgentDocumentVfsService } from './index';+import { db, mockAgentDocumentModel, mockSkillMount, resetVfsMocks, userId } from './testUtils';++vi.mock('@/database/models/agentDocuments', () => ({+ AgentAccess: {+ DELETE: 16,+ EXECUTE: 1,+ LIST: 8,+ READ: 2,+ WRITE: 4,+ },+ AgentDocumentModel: vi.fn(),+ buildDocumentFilename: vi.fn(function (title: string) {+ return title;+ }),+}));++vi.mock('./mounts/skills/createSkillMount', () => ({+ createSkillMount: vi.fn(),+}));++const removeUnreferencedFile = vi.hoisted(() => vi.fn());+vi.mock('../file', () => ({+ FileService: vi.fn(function () {+ return { removeUnreferencedFile };+ }),+}));++const folderDoc = (filename: string, documentId: string, parentId: string | null = null) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId,+ fileType: 'custom/folder',+ filename,+ id: `agent-${documentId}`,+ parentId,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+});++const fileDoc = (+ filename: string,+ documentId: string,+ parentId: string | null = null,+ content = 'hello',+) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content,+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId,+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename,+ id: `agent-${documentId}`,+ parentId,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+});++describe('AgentDocumentVfsService', () => {+ beforeEach(() => {+ vi.mocked(FileService).mockClear();+ removeUnreferencedFile.mockReset().mockResolvedValue(undefined);+ resetVfsMocks();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ /** @example Native VFS browsing remains available without object storage. */+ it('does not initialize storage when listing native documents', async () => {+ mockAgentDocumentModel.listByParent.mockResolvedValue([]);+ const service = new AgentDocumentVfsService(db, userId);+ await service.list('./', { agentId: 'agent-1' });+ /** @example Browsing a document tree has no storage configuration prerequisite. */+ expect(FileService).not.toHaveBeenCalled();+ });++ it('lists ordinary root nodes plus the synthetic lobe directory', async () => {+ mockAgentDocumentModel.listByParent.mockResolvedValue([+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'hello',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'SOUL.md',+ id: 'agent-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ },+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'newer duplicate',+ createdAt: new Date('2024-01-02T00:00:00.000Z'),+ documentId: 'documents-duplicate',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'SOUL.md',+ id: 'agent-doc-duplicate',+ updatedAt: new Date('2024-01-03T00:00:00.000Z'),+ },+ ]);++ const service = new AgentDocumentVfsService(db, userId);+ const nodes = await service.list('./', { agentId: 'agent-1' });++ expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledWith('agent-1', null, {+ cursor: undefined,+ });+ expect(nodes).toEqual([+ expect.objectContaining({+ agentDocumentId: 'agent-doc-1',+ documentId: 'documents-1',+ mode: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ name: 'SOUL.md',+ path: './SOUL.md',+ type: 'file',+ }),+ expect.objectContaining({+ id: 'synthetic:./lobe',+ name: 'lobe',+ path: './lobe',+ type: 'directory',+ }),+ ]);+ expect(nodes).toHaveLength(2);+ });++ it('stats the unified VFS root as a synthetic directory', async () => {+ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.stat('./', { agentId: 'agent-1' });++ expect(node).toEqual(+ expect.objectContaining({+ id: 'synthetic:./',+ path: './',+ type: 'directory',+ }),+ );+ });++ it('routes mounted skill listings through unified skill paths', async () => {+ mockSkillMount.list.mockResolvedValue([+ {+ name: 'writer',+ namespace: 'builtin',+ path: './lobe/skills/builtin/skills/writer',+ readOnly: true,+ type: 'directory',+ },+ ]);++ const service = new AgentDocumentVfsService(db, userId);+ const nodes = await service.list('./lobe/skills/builtin/skills', { agentId: 'agent-1' });++ expect(mockSkillMount.list).toHaveBeenCalledWith({+ agentId: 'agent-1',+ path: './lobe/skills/builtin/skills',+ topicId: undefined,+ });+ expect(nodes).toEqual([+ expect.objectContaining({+ mount: expect.objectContaining({+ driver: 'skills',+ namespace: 'builtin',+ source: 'builtin',+ }),+ name: 'writer',+ path: './lobe/skills/builtin/skills/writer',+ type: 'directory',+ }),+ ]);+ });++ it('resolves ordinary file stats through parentId + filename segments', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.LIST,+ content: '# Soul',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'SOUL.md',+ id: 'agent-doc-1',+ metadata: { category: 'system' },+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.stat('./SOUL.md', { agentId: 'agent-1' });++ expect(mockAgentDocumentModel.listByParentAndFilename).toHaveBeenCalledWith(+ 'agent-1',+ null,+ 'SOUL.md',+ {},+ );+ expect(node).toEqual(+ expect.objectContaining({+ documentId: 'documents-1',+ metadata: { category: 'system' },+ path: './SOUL.md',+ type: 'file',+ }),+ );+ });++ it('reads an ordinary file line range with loc metadata', async () => {+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([+ {+ accessSelf: AgentAccess.READ | AgentAccess.LIST,+ content: ['line 0', 'line 1', 'line 2', 'line 3'].join('\n'),+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'SOUL.md',+ id: 'agent-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ },+ ]);++ const service = new AgentDocumentVfsService(db, userId);+ const result = await service.read('./SOUL.md', { agentId: 'agent-1' }, { loc: [1, 3] });++ expect(result).toEqual(+ expect.objectContaining({+ content: 'line 1\nline 2',+ lineCount: 2,+ loc: [1, 3],+ path: './SOUL.md',+ totalLineCount: 4,+ }),+ );+ });++ it('reads a mounted skill file line range with loc metadata', async () => {+ mockSkillMount.get.mockResolvedValue({+ content: ['# Skill', '', 'Use this skill.', 'Extra notes.'].join('\n'),+ contentType: 'text/markdown',+ name: 'SKILL.md',+ namespace: 'agent',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ readOnly: false,+ type: 'file',+ });++ const service = new AgentDocumentVfsService(db, userId);+ const result = await service.read(+ './lobe/skills/agent/skills/writer/SKILL.md',+ {+ agentId: 'agent-1',+ },+ { loc: [2, 4] },+ );++ expect(result).toEqual(+ expect.objectContaining({+ content: 'Use this skill.\nExtra notes.',+ contentType: 'text/markdown',+ lineCount: 2,+ loc: [2, 4],+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ totalLineCount: 4,+ }),+ );+ });++ it('resolves deep ordinary paths one segment at a time without directory traversal', async () => {+ mockAgentDocumentModel.findByParentAndFilename+ .mockResolvedValueOnce({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ documentId: 'folder-a',+ fileType: 'custom/folder',+ filename: 'a',+ id: 'agent-doc-a',+ })+ .mockResolvedValueOnce({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ documentId: 'folder-b',+ fileType: 'custom/folder',+ filename: 'b',+ id: 'agent-doc-b',+ })+ .mockResolvedValueOnce({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '# Leaf',+ documentId: 'file-c',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'c.md',+ id: 'agent-doc-c',+ });++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.stat('./a/b/c.md', { agentId: 'agent-1' });++ expect(node).toEqual(expect.objectContaining({ path: './a/b/c.md', type: 'file' }));+ expect(mockAgentDocumentModel.listByParentAndFilename).toHaveBeenCalledTimes(3);+ expect(mockAgentDocumentModel.listByParent).not.toHaveBeenCalled();+ });++ it('lists wide directories with one direct-child query and no subtree walk', async () => {+ mockAgentDocumentModel.listByParent.mockResolvedValue(+ Array.from({ length: 1000 }, (_, index) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: `file ${index}`,+ documentId: `doc-${index}`,+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: `file-${index}.md`,+ id: `agent-doc-${index}`,+ })),+ );++ const service = new AgentDocumentVfsService(db, userId);+ const nodes = await service.list('./', { agentId: 'agent-1' });++ expect(nodes).toHaveLength(101);+ expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledTimes(1);+ expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledWith('agent-1', null, {+ cursor: undefined,+ });+ expect(mockAgentDocumentModel.findByParentAndFilename).not.toHaveBeenCalled();+ });++ it.each([+ [0, 1],+ [2.9, 2],+ [10_000, 500],+ ])('clamps a list limit of %s to %s ordinary entries', async (limit, expected) => {+ mockAgentDocumentModel.listByParent.mockResolvedValue(+ Array.from({ length: 1000 }, (_, index) =>+ fileDoc(`file-${String(index).padStart(4, '0')}.md`, `doc-${index}`),+ ),+ );++ const service = new AgentDocumentVfsService(db, userId);+ const nodes = await service.list('./', { agentId: 'agent-1' }, { limit });++ expect(nodes).toHaveLength(expected + 1);+ expect(nodes.at(-1)).toEqual(expect.objectContaining({ path: './lobe' }));+ });++ it.each(['./a/../b', './a/./b', './a/..'])('rejects the traversal path %s', async (path) => {+ const service = new AgentDocumentVfsService(db, userId);++ await expect(service.stat(path, { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });++ it.each([+ ['/notes.md', './notes.md'],+ ['notes.md', './notes.md'],+ ['.//notes.md/', './notes.md'],+ ])('normalizes %s to %s before resolving', async (input, expected) => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(fileDoc('notes.md', 'doc-1'));++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.stat(input, { agentId: 'agent-1' });++ expect(node).toEqual(expect.objectContaining({ path: expected, type: 'file' }));+ });++ it('lists synthetic skill directories without touching storage', async () => {+ const service = new AgentDocumentVfsService(db, userId);+ const ctx = { agentId: 'agent-1' };++ expect((await service.list('./lobe', ctx)).map((node) => node.path)).toEqual(['./lobe/skills']);+ expect((await service.list('./lobe/skills', ctx)).map((node) => node.path)).toEqual([+ './lobe/skills/builtin',+ './lobe/skills/installed',+ './lobe/skills/agent',+ ]);+ expect((await service.list('./lobe/skills/installed', ctx)).map((node) => node.path)).toEqual([+ './lobe/skills/installed/all',+ './lobe/skills/installed/active',+ ]);+ expect(await service.list('./lobe/skills/installed/active', ctx)).toEqual([+ expect.objectContaining({+ mount: { driver: 'skills', namespace: 'installed-active', source: 'installed' },+ path: './lobe/skills/installed/active/skills',+ type: 'directory',+ }),+ ]);+ expect(await service.stat('./lobe/skills/builtin/skills', ctx)).toEqual(+ expect.objectContaining({+ mount: { driver: 'skills', namespace: 'builtin', source: 'builtin' },+ name: 'skills',+ type: 'directory',+ }),+ );+ expect(mockAgentDocumentModel.listByParent).not.toHaveBeenCalled();+ expect(mockSkillMount.list).not.toHaveBeenCalled();+ });++ it('rejects listing a missing path or an ordinary file', async () => {+ const service = new AgentDocumentVfsService(db, userId);++ await expect(service.list('./missing', { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });++ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(fileDoc('a.md', 'doc-1'));++ await expect(service.list('./a.md', { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });++ it('rejects reading a missing path, a directory, or a mounted directory', async () => {+ const service = new AgentDocumentVfsService(db, userId);++ await expect(service.read('./missing.md', { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });++ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(folderDoc('notes', 'f-1'));+ await expect(service.read('./notes', { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });++ mockSkillMount.get.mockResolvedValue({+ name: 'writer',+ namespace: 'agent',+ path: './lobe/skills/agent/skills/writer',+ type: 'directory',+ });+ await expect(+ service.read('./lobe/skills/agent/skills/writer', { agentId: 'agent-1' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it.each([+ ['agent', 2 | 8 | 4 | 16, 'documents'],+ ['builtin', 2 | 8, 'builtin'],+ ['installed-all', 2 | 8, 'installed'],+ ])('maps mounted %s skill stats to mode %s from source %s', async (namespace, mode, source) => {+ mockSkillMount.get.mockResolvedValue({+ content: 'body',+ contentType: 'text/markdown',+ name: 'SKILL.md',+ namespace,+ path: `./lobe/skills/${namespace}/skills/x/SKILL.md`,+ type: 'file',+ });++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.stat(`./lobe/skills/${namespace}/skills/x/SKILL.md`, {+ agentId: 'agent-1',+ topicId: 'topic-1',+ });++ expect(mockSkillMount.get).toHaveBeenCalledWith({+ agentId: 'agent-1',+ path: `./lobe/skills/${namespace}/skills/x/SKILL.md`,+ topicId: 'topic-1',+ });+ expect(node).toEqual({+ contentType: 'text/markdown',+ id: `skills:${namespace}:./lobe/skills/${namespace}/skills/x/SKILL.md`,+ mode,+ mount: { driver: 'skills', namespace, source },+ name: 'SKILL.md',+ path: `./lobe/skills/${namespace}/skills/x/SKILL.md`,+ size: 4,+ type: 'file',+ });+ });+});diff --git a/apps/server/src/services/agentDocumentVfs/index.test.ts b/apps/server/src/services/agentDocumentVfs/index.test.tsdeleted file mode 100644index 62e5da29d19..00000000000--- a/apps/server/src/services/agentDocumentVfs/index.test.ts+++ /dev/null@@ -1,921 +0,0 @@-// @vitest-environment node-import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';-import { FileSource } from '@lobechat/types';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { AgentAccess, AgentDocumentModel } from '@/database/models/agentDocuments';-import type { LobeChatDatabase } from '@/database/type';--import * as headlessEditor from '../agentDocuments/headlessEditor';-import { FileService } from '../file';-import { AgentDocumentVfsService } from './index';-import { createSkillMount } from './mounts/skills/createSkillMount';--vi.mock('@/database/models/agentDocuments', () => ({- AgentAccess: {- DELETE: 16,- EXECUTE: 1,- LIST: 8,- READ: 2,- WRITE: 4,- },- AgentDocumentModel: vi.fn(),- buildDocumentFilename: vi.fn(function (title: string) {- return title;- }),-}));--vi.mock('./mounts/skills/createSkillMount', () => ({- createSkillMount: vi.fn(),-}));--const removeUnreferencedFile = vi.hoisted(() => vi.fn());-vi.mock('../file', () => ({- FileService: vi.fn(function () {- return { removeUnreferencedFile };- }),-}));--describe('AgentDocumentVfsService', () => {- const db = {} as LobeChatDatabase;- const userId = 'user-1';- const mockAgentDocumentModel = {- create: vi.fn(),- findByDocumentId: vi.fn(),- findByIdWithOptions: vi.fn(),- findByParentAndFilename: vi.fn(),- listByParentAndFilename: vi.fn(),- listByParent: vi.fn(),- listDeletedByAgent: vi.fn(),- movePath: vi.fn(),- permanentlyDelete: vi.fn(),- restore: vi.fn(),- delete: vi.fn(),- update: vi.fn(),- };- const mockSkillMount = {- create: vi.fn(),- get: vi.fn(),- list: vi.fn(),- update: vi.fn(),- };-- beforeEach(() => {- vi.mocked(FileService).mockClear();- removeUnreferencedFile.mockReset().mockResolvedValue(undefined);- for (const method of Object.values(mockAgentDocumentModel)) {- method.mockReset();- }- mockAgentDocumentModel.permanentlyDelete.mockResolvedValue([]);- for (const method of Object.values(mockSkillMount)) {- method.mockReset();- }- (AgentDocumentModel as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {- return mockAgentDocumentModel;- });- (createSkillMount as unknown as ReturnType<typeof vi.fn>).mockReturnValue(mockSkillMount);- mockAgentDocumentModel.listByParentAndFilename.mockImplementation(async (...args) => {- const result = await mockAgentDocumentModel.findByParentAndFilename(...args);- return result ? [result] : [];- });- });-- /** @example Native VFS browsing remains available without object storage. */- it('does not initialize storage when listing native documents', async () => {- mockAgentDocumentModel.listByParent.mockResolvedValue([]);- const service = new AgentDocumentVfsService(db, userId);- await service.list('./', { agentId: 'agent-1' });- /** @example Browsing a document tree has no storage configuration prerequisite. */- expect(FileService).not.toHaveBeenCalled();- });-- afterEach(() => {- vi.restoreAllMocks();- });-- it('lists ordinary root nodes plus the synthetic lobe directory', async () => {- mockAgentDocumentModel.listByParent.mockResolvedValue([- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'hello',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'documents-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'SOUL.md',- id: 'agent-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- },- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'newer duplicate',- createdAt: new Date('2024-01-02T00:00:00.000Z'),- documentId: 'documents-duplicate',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'SOUL.md',- id: 'agent-doc-duplicate',- updatedAt: new Date('2024-01-03T00:00:00.000Z'),- },- ]);-- const service = new AgentDocumentVfsService(db, userId);- const nodes = await service.list('./', { agentId: 'agent-1' });-- expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledWith('agent-1', null, {- cursor: undefined,- });- expect(nodes).toEqual([- expect.objectContaining({- agentDocumentId: 'agent-doc-1',- documentId: 'documents-1',- mode: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- name: 'SOUL.md',- path: './SOUL.md',- type: 'file',- }),- expect.objectContaining({- id: 'synthetic:./lobe',- name: 'lobe',- path: './lobe',- type: 'directory',- }),- ]);- expect(nodes).toHaveLength(2);- });-- it('stats the unified VFS root as a synthetic directory', async () => {- const service = new AgentDocumentVfsService(db, userId);- const node = await service.stat('./', { agentId: 'agent-1' });-- expect(node).toEqual(- expect.objectContaining({- id: 'synthetic:./',- path: './',- type: 'directory',- }),- );- });-- it('routes mounted skill listings through unified skill paths', async () => {- mockSkillMount.list.mockResolvedValue([- {- name: 'writer',- namespace: 'builtin',- path: './lobe/skills/builtin/skills/writer',- readOnly: true,- type: 'directory',- },- ]);-- const service = new AgentDocumentVfsService(db, userId);- const nodes = await service.list('./lobe/skills/builtin/skills', { agentId: 'agent-1' });-- expect(mockSkillMount.list).toHaveBeenCalledWith({- agentId: 'agent-1',- path: './lobe/skills/builtin/skills',- topicId: undefined,- });- expect(nodes).toEqual([- expect.objectContaining({- mount: expect.objectContaining({- driver: 'skills',- namespace: 'builtin',- source: 'builtin',- }),- name: 'writer',- path: './lobe/skills/builtin/skills/writer',- type: 'directory',- }),- ]);- });-- it('resolves ordinary file stats through parentId + filename segments', async () => {- mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.LIST,- content: '# Soul',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'documents-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'SOUL.md',- id: 'agent-doc-1',- metadata: { category: 'system' },- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });-- const service = new AgentDocumentVfsService(db, userId);- const node = await service.stat('./SOUL.md', { agentId: 'agent-1' });-- expect(mockAgentDocumentModel.listByParentAndFilename).toHaveBeenCalledWith(- 'agent-1',- null,- 'SOUL.md',- {},- );- expect(node).toEqual(- expect.objectContaining({- documentId: 'documents-1',- metadata: { category: 'system' },- path: './SOUL.md',- type: 'file',- }),- );- });-- it('reads an ordinary file line range with loc metadata', async () => {- mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([- {- accessSelf: AgentAccess.READ | AgentAccess.LIST,- content: ['line 0', 'line 1', 'line 2', 'line 3'].join('\n'),- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'documents-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'SOUL.md',- id: 'agent-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- },- ]);-- const service = new AgentDocumentVfsService(db, userId);- const result = await service.read('./SOUL.md', { agentId: 'agent-1' }, { loc: [1, 3] });-- expect(result).toEqual(- expect.objectContaining({- content: 'line 1\nline 2',- lineCount: 2,- loc: [1, 3],- path: './SOUL.md',- totalLineCount: 4,- }),- );- });-- it('reads a mounted skill file line range with loc metadata', async () => {- mockSkillMount.get.mockResolvedValue({- content: ['# Skill', '', 'Use this skill.', 'Extra notes.'].join('\n'),- contentType: 'text/markdown',- name: 'SKILL.md',- namespace: 'agent',- path: './lobe/skills/agent/skills/writer/SKILL.md',- readOnly: false,- type: 'file',- });-- const service = new AgentDocumentVfsService(db, userId);- const result = await service.read(- './lobe/skills/agent/skills/writer/SKILL.md',- {- agentId: 'agent-1',- },- { loc: [2, 4] },- );-- expect(result).toEqual(- expect.objectContaining({- content: 'Use this skill.\nExtra notes.',- contentType: 'text/markdown',- lineCount: 2,- loc: [2, 4],- path: './lobe/skills/agent/skills/writer/SKILL.md',- totalLineCount: 4,- }),- );- });-- it('creates a new ordinary file through write when the path is missing', async () => {- mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);- mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([]);- mockAgentDocumentModel.create.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'hello',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'documents-2',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'notes.md',- id: 'agent-doc-2',- metadata: null,- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });-- const service = new AgentDocumentVfsService(db, userId);- const node = await service.write('./notes.md', 'hello', { agentId: 'agent-1' });-- expect(mockAgentDocumentModel.create).toHaveBeenCalledWith(- 'agent-1',- 'notes.md',- expect.any(String),- expect.objectContaining({- editorData: expect.any(Object),- parentId: null,- title: 'notes.md',- }),- );- expect(node).toEqual(- expect.objectContaining({- documentId: 'documents-2',- path: './notes.md',- type: 'file',- }),- );- });-- it('stores raw ordinary file content without Markdown serialization', async () => {- const content = `<knowledge_base_files totalCount="1">-<file id="file-1" name="raw.txt">-${'lossless tool result\n'.repeat(100)}-</file>-</knowledge_base_files>`;- mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);- mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([]);- mockAgentDocumentModel.create.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content,- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'documents-raw',- fileType: 'text/plain',- filename: 'archive.txt',- id: 'agent-doc-raw',- metadata: null,- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });- const createSnapshotSpy = vi.spyOn(headlessEditor, 'createAgentMarkdownSnapshot');- const service = new AgentDocumentVfsService(db, userId);- const node = await service.write(- './archive.txt',- content,- { agentId: 'agent-1' },- {- contentFormat: 'raw',- },- );-- expect(createSnapshotSpy).not.toHaveBeenCalled();- expect(node.contentType).toBe('text/plain');- expect(mockAgentDocumentModel.create).toHaveBeenCalledWith('agent-1', 'archive.txt', content, {- fileType: 'text/plain',- parentId: null,- title: 'archive.txt',- });- });-- it('overwrites raw ordinary file content without Markdown serialization', async () => {- const existing = {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'old content',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'documents-raw',- fileType: 'text/plain',- filename: 'archive.txt',- id: 'agent-doc-raw',- metadata: null,- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- };- mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(existing);- mockAgentDocumentModel.update.mockImplementation(async (_id, params) => {- Object.assign(existing, params);- });- const createSnapshotSpy = vi.spyOn(headlessEditor, 'createAgentMarkdownSnapshot');- const service = new AgentDocumentVfsService(db, userId);-- await service.write(- './archive.txt',- 'new raw content',- { agentId: 'agent-1' },- {- contentFormat: 'raw',- },- );-- expect(createSnapshotSpy).not.toHaveBeenCalled();- expect(mockAgentDocumentModel.update).toHaveBeenCalledWith('agent-doc-raw', {- content: 'new raw content',- editorData: null,- fileType: 'text/plain',- });- });-- it('resolves duplicate ordinary path segments to the oldest sibling', async () => {- mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'first',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'documents-first',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'notes.md',- id: 'agent-doc-first',- },- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'second',- createdAt: new Date('2024-01-02T00:00:00.000Z'),- documentId: 'documents-second',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'notes.md',- id: 'agent-doc-second',- },- ]);-- const service = new AgentDocumentVfsService(db, userId);- const stats = await service.stat('./notes.md', { agentId: 'agent-1' });-- if (!stats) throw new Error('Expected ./notes.md stats to resolve');-- expect(stats.documentId).toBe('documents-first');- expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();- });-- it('updates an existing mounted skill through write', async () => {- mockSkillMount.get.mockResolvedValue({- content: '# Draft',- name: 'SKILL.md',- namespace: 'agent',- path: './lobe/skills/agent/skills/writer/SKILL.md',- readOnly: false,- type: 'file',- });- mockSkillMount.update.mockResolvedValue({- content: '# Final',- name: 'SKILL.md',- namespace: 'agent',- path: './lobe/skills/agent/skills/writer/SKILL.md',- readOnly: false,- type: 'file',- });-- const service = new AgentDocumentVfsService(db, userId);- const node = await service.write('./lobe/skills/agent/skills/writer/SKILL.md', '# Final', {- agentId: 'agent-1',- });-- expect(mockSkillMount.update).toHaveBeenCalledWith({- agentId: 'agent-1',- content: '# Final',- path: './lobe/skills/agent/skills/writer/SKILL.md',- topicId: undefined,- });- expect(node).toEqual(- expect.objectContaining({- mount: expect.objectContaining({ driver: 'skills', namespace: 'agent' }),- size: '# Final'.length,- }),- );- });-- it('creates nested directories through mkdir when recursive is enabled', async () => {- mockAgentDocumentModel.findByParentAndFilename- .mockResolvedValueOnce(undefined)- .mockResolvedValueOnce(undefined);- mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([]);- mockAgentDocumentModel.create- .mockResolvedValueOnce({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'folder-doc-1',- fileType: 'custom/folder',- filename: 'notes',- id: 'folder-agent-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- })- .mockResolvedValueOnce({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'folder-doc-2',- fileType: 'custom/folder',- filename: 'archive',- id: 'folder-agent-doc-2',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });-- const service = new AgentDocumentVfsService(db, userId);- const node = await service.mkdir(- './notes/archive',- { agentId: 'agent-1' },- { recursive: true },- );-- expect(mockAgentDocumentModel.create).toHaveBeenNthCalledWith(- 1,- 'agent-1',- 'notes',- '',- expect.objectContaining({- fileType: 'custom/folder',- parentId: null,- }),- );- expect(mockAgentDocumentModel.create).toHaveBeenNthCalledWith(- 2,- 'agent-1',- 'archive',- '',- expect.objectContaining({- fileType: 'custom/folder',- parentId: 'folder-doc-1',- }),- );- expect(node).toEqual(- expect.objectContaining({- path: './notes/archive',- type: 'directory',- }),- );- });-- it('soft-deletes an ordinary subtree through delete', async () => {- mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'folder-doc-1',- fileType: 'custom/folder',- filename: 'notes',- id: 'folder-agent-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });- mockAgentDocumentModel.listByParent- .mockResolvedValueOnce([- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'hello',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'child-doc-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'todo.md',- id: 'child-agent-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- },- ])- .mockResolvedValueOnce([]);-- const service = new AgentDocumentVfsService(db, userId);- await service.delete('./notes', { agentId: 'agent-1' }, { recursive: true });-- expect(mockAgentDocumentModel.delete).toHaveBeenCalledWith(- 'folder-agent-doc-1',- 'recursive-delete',- );- expect(mockAgentDocumentModel.delete).toHaveBeenCalledWith('child-agent-doc-1', 'user-delete');- });-- it('rejects copying a directory into its own subtree', async () => {- mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'folder-doc-1',- fileType: 'custom/folder',- filename: 'notes',- id: 'folder-agent-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });-- const service = new AgentDocumentVfsService(db, userId);-- await expect(- service.copy('./notes', './notes/archive', { agentId: 'agent-1' }),- ).rejects.toMatchObject({- code: 'BAD_REQUEST',- });- expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();- });-- it('rejects renaming a directory into its own subtree', async () => {- mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'folder-doc-1',- fileType: 'custom/folder',- filename: 'notes',- id: 'folder-agent-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });-- const service = new AgentDocumentVfsService(db, userId);-- await expect(- service.rename('./notes', './notes/archive', { agentId: 'agent-1' }),- ).rejects.toMatchObject({- code: 'BAD_REQUEST',- });- expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();- });-- it('renames ordinary files by moving the original document path in place', async () => {- const sourceFile = {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'hello',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'documents-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'old.md',- id: 'agent-doc-1',- parentId: null,- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- };- const movedFile = {- ...sourceFile,- filename: 'new.md',- parentId: 'folder-doc-1',- };-- mockAgentDocumentModel.listByParentAndFilename.mockImplementation(- async (_agentId, parentId, filename) => {- if (parentId === null && filename === 'old.md') return [sourceFile];- if (parentId === null && filename === 'folder') {- return [- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- documentId: 'folder-doc-1',- fileType: 'custom/folder',- filename: 'folder',- id: 'folder-agent-doc-1',- parentId: null,- },- ];- }- return [];- },- );- mockAgentDocumentModel.movePath.mockResolvedValue(movedFile);-- const service = new AgentDocumentVfsService(db, userId);- const node = await service.rename('./old.md', './folder/new.md', { agentId: 'agent-1' });-- expect(mockAgentDocumentModel.movePath).toHaveBeenCalledWith('agent-doc-1', {- filename: 'new.md',- parentId: 'folder-doc-1',- });- expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();- expect(mockAgentDocumentModel.delete).not.toHaveBeenCalled();- expect(node).toEqual(- expect.objectContaining({- agentDocumentId: 'agent-doc-1',- documentId: 'documents-1',- path: './folder/new.md',- }),- );- });-- it('rejects recursive directory copy when direct children exceed the safety cap', async () => {- const sourceFolder = {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'folder-doc-1',- fileType: 'custom/folder',- filename: 'notes',- id: 'folder-agent-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- };- mockAgentDocumentModel.listByParentAndFilename.mockImplementation(- async (_agentId, _parentId, filename) => (filename === 'notes' ? [sourceFolder] : []),- );- mockAgentDocumentModel.create.mockResolvedValue({- ...sourceFolder,- documentId: 'archive-doc-1',- filename: 'archive',- id: 'archive-agent-doc-1',- });- mockAgentDocumentModel.listByParent.mockResolvedValue(- Array.from({ length: 5001 }, (_, index) => ({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: `file ${index}`,- documentId: `doc-${index}`,- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: `file-${index}.md`,- id: `agent-doc-${index}`,- })),- );-- const service = new AgentDocumentVfsService(db, userId);-- await expect(- service.copy('./notes', './archive', { agentId: 'agent-1' }),- ).rejects.toMatchObject({- code: 'BAD_REQUEST',- });- expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledWith('agent-1', 'folder-doc-1', {- limit: 5001,- });- });-- it('restores trash entries when a live sibling already owns the same filename', async () => {- mockAgentDocumentModel.findByIdWithOptions.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'deleted',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- deletedAt: new Date('2024-01-03T00:00:00.000Z'),- documentId: 'deleted-doc-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'draft.md',- id: 'deleted-agent-doc-1',- parentId: null,- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });- mockAgentDocumentModel.listByParent.mockResolvedValue([]);- mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'live',- createdAt: new Date('2024-01-04T00:00:00.000Z'),- documentId: 'live-doc-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'draft.md',- id: 'live-agent-doc-1',- parentId: null,- updatedAt: new Date('2024-01-04T00:00:00.000Z'),- });- mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'deleted',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- documentId: 'deleted-doc-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'draft.md',- id: 'deleted-agent-doc-1',- parentId: null,- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- },- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'live',- createdAt: new Date('2024-01-04T00:00:00.000Z'),- documentId: 'live-doc-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'draft.md',- id: 'live-agent-doc-1',- parentId: null,- updatedAt: new Date('2024-01-04T00:00:00.000Z'),- },- ]);-- const service = new AgentDocumentVfsService(db, userId);-- const stats = await service.restoreFromTrash('deleted-agent-doc-1', { agentId: 'agent-1' });-- expect(stats.documentId).toBe('deleted-doc-1');- expect(mockAgentDocumentModel.restore).toHaveBeenCalledWith('deleted-agent-doc-1');- });-- it('permanently deletes ordinary directory subtrees child-first', async () => {- // ROOT CAUSE:- // Permanent deletion removed document rows without reclaiming hidden backing uploads.- // Returned file IDs now go through reference-safe cleanup after each committed deletion.- mockAgentDocumentModel.permanentlyDelete- .mockResolvedValueOnce(['child-file'])- .mockResolvedValueOnce([]);- mockAgentDocumentModel.findByIdWithOptions.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- deletedAt: new Date('2024-01-03T00:00:00.000Z'),- documentId: 'folder-doc-1',- fileType: 'custom/folder',- filename: 'notes',- id: 'folder-agent-doc-1',- parentId: null,- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });- mockAgentDocumentModel.listByParent- .mockResolvedValueOnce([- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'hello',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- deletedAt: new Date('2024-01-03T00:00:00.000Z'),- documentId: 'child-doc-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'todo.md',- id: 'child-agent-doc-1',- parentId: 'folder-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- },- ])- .mockResolvedValueOnce([]);-- const service = new AgentDocumentVfsService(db, userId);- await service.deletePermanently('folder-agent-doc-1', { agentId: 'agent-1' });-- expect(mockAgentDocumentModel.permanentlyDelete).toHaveBeenNthCalledWith(- 1,- 'child-agent-doc-1',- );- expect(mockAgentDocumentModel.permanentlyDelete).toHaveBeenNthCalledWith(- 2,- 'folder-agent-doc-1',- );- /** @example The child upload is reclaimed using the dedicated source policy. */- expect(removeUnreferencedFile.mock.calls).toEqual([['child-file', FileSource.AgentDocument]]);- });-- it('opts read-only mounted skill paths out of trash deletes', async () => {- const service = new AgentDocumentVfsService(db, userId);-- await expect(- service.delete('./lobe/skills/builtin/skills/lobehub/SKILL.md', { agentId: 'agent-1' }),- ).rejects.toMatchObject({ code: 'FORBIDDEN' });- });-- it('resolves deep ordinary paths one segment at a time without directory traversal', async () => {- mockAgentDocumentModel.findByParentAndFilename- .mockResolvedValueOnce({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- documentId: 'folder-a',- fileType: 'custom/folder',- filename: 'a',- id: 'agent-doc-a',- })- .mockResolvedValueOnce({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- documentId: 'folder-b',- fileType: 'custom/folder',- filename: 'b',- id: 'agent-doc-b',- })- .mockResolvedValueOnce({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '# Leaf',- documentId: 'file-c',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'c.md',- id: 'agent-doc-c',- });-- const service = new AgentDocumentVfsService(db, userId);- const node = await service.stat('./a/b/c.md', { agentId: 'agent-1' });-- expect(node).toEqual(expect.objectContaining({ path: './a/b/c.md', type: 'file' }));- expect(mockAgentDocumentModel.listByParentAndFilename).toHaveBeenCalledTimes(3);- expect(mockAgentDocumentModel.listByParent).not.toHaveBeenCalled();- });-- it('lists wide directories with one direct-child query and no subtree walk', async () => {- mockAgentDocumentModel.listByParent.mockResolvedValue(- Array.from({ length: 1000 }, (_, index) => ({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: `file ${index}`,- documentId: `doc-${index}`,- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: `file-${index}.md`,- id: `agent-doc-${index}`,- })),- );-- const service = new AgentDocumentVfsService(db, userId);- const nodes = await service.list('./', { agentId: 'agent-1' });-- expect(nodes).toHaveLength(101);- expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledTimes(1);- expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledWith('agent-1', null, {- cursor: undefined,- });- expect(mockAgentDocumentModel.findByParentAndFilename).not.toHaveBeenCalled();- });-- it('lists trash entries with reconstructed VFS paths', async () => {- mockAgentDocumentModel.listDeletedByAgent.mockResolvedValue([- {- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: 'hello',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- deleteReason: 'user-delete',- deletedAt: new Date('2024-01-03T00:00:00.000Z'),- documentId: 'child-doc-1',- fileType: AGENT_DOCUMENT_FILE_TYPE,- filename: 'todo.md',- id: 'child-agent-doc-1',- parentId: 'folder-doc-1',- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- },- ]);- mockAgentDocumentModel.findByDocumentId.mockResolvedValue({- accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,- content: '',- createdAt: new Date('2024-01-01T00:00:00.000Z'),- deleteReason: 'recursive-delete',- deletedAt: new Date('2024-01-03T00:00:00.000Z'),- documentId: 'folder-doc-1',- fileType: 'custom/folder',- filename: 'notes',- id: 'folder-agent-doc-1',- parentId: null,- updatedAt: new Date('2024-01-02T00:00:00.000Z'),- });-- const service = new AgentDocumentVfsService(db, userId);- const entries = await service.listTrash({ agentId: 'agent-1' });-- expect(entries).toEqual([- expect.objectContaining({- deleteReason: 'user-delete',- deletedAt: new Date('2024-01-03T00:00:00.000Z'),- path: './notes/todo.md',- }),- ]);- });-});diff --git a/apps/server/src/services/agentDocumentVfs/index.trash.test.ts b/apps/server/src/services/agentDocumentVfs/index.trash.test.tsnew file mode 100644index 00000000000..f879fcb903d--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/index.trash.test.ts@@ -0,0 +1,389 @@+// @vitest-environment node+import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import { FileSource } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentAccess } from '@/database/models/agentDocuments';++import { FileService } from '../file';+import { AgentDocumentVfsService } from './index';+import { db, mockAgentDocumentModel, mockSkillMount, resetVfsMocks, userId } from './testUtils';++vi.mock('@/database/models/agentDocuments', () => ({+ AgentAccess: {+ DELETE: 16,+ EXECUTE: 1,+ LIST: 8,+ READ: 2,+ WRITE: 4,+ },+ AgentDocumentModel: vi.fn(),+ buildDocumentFilename: vi.fn(function (title: string) {+ return title;+ }),+}));++vi.mock('./mounts/skills/createSkillMount', () => ({+ createSkillMount: vi.fn(),+}));++const removeUnreferencedFile = vi.hoisted(() => vi.fn());+vi.mock('../file', () => ({+ FileService: vi.fn(function () {+ return { removeUnreferencedFile };+ }),+}));++const folderDoc = (filename: string, documentId: string, parentId: string | null = null) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId,+ fileType: 'custom/folder',+ filename,+ id: `agent-${documentId}`,+ parentId,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+});++const fileDoc = (+ filename: string,+ documentId: string,+ parentId: string | null = null,+ content = 'hello',+) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content,+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId,+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename,+ id: `agent-${documentId}`,+ parentId,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+});++describe('AgentDocumentVfsService', () => {+ beforeEach(() => {+ vi.mocked(FileService).mockClear();+ removeUnreferencedFile.mockReset().mockResolvedValue(undefined);+ resetVfsMocks();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('soft-deletes an ordinary subtree through delete', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'folder-doc-1',+ fileType: 'custom/folder',+ filename: 'notes',+ id: 'folder-agent-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });+ mockAgentDocumentModel.listByParent+ .mockResolvedValueOnce([+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'hello',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'child-doc-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'todo.md',+ id: 'child-agent-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ },+ ])+ .mockResolvedValueOnce([]);++ const service = new AgentDocumentVfsService(db, userId);+ await service.delete('./notes', { agentId: 'agent-1' }, { recursive: true });++ expect(mockAgentDocumentModel.delete).toHaveBeenCalledWith(+ 'folder-agent-doc-1',+ 'recursive-delete',+ );+ expect(mockAgentDocumentModel.delete).toHaveBeenCalledWith('child-agent-doc-1', 'user-delete');+ });++ it('restores trash entries when a live sibling already owns the same filename', async () => {+ mockAgentDocumentModel.findByIdWithOptions.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'deleted',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ deletedAt: new Date('2024-01-03T00:00:00.000Z'),+ documentId: 'deleted-doc-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'draft.md',+ id: 'deleted-agent-doc-1',+ parentId: null,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });+ mockAgentDocumentModel.listByParent.mockResolvedValue([]);+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'live',+ createdAt: new Date('2024-01-04T00:00:00.000Z'),+ documentId: 'live-doc-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'draft.md',+ id: 'live-agent-doc-1',+ parentId: null,+ updatedAt: new Date('2024-01-04T00:00:00.000Z'),+ });+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'deleted',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'deleted-doc-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'draft.md',+ id: 'deleted-agent-doc-1',+ parentId: null,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ },+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'live',+ createdAt: new Date('2024-01-04T00:00:00.000Z'),+ documentId: 'live-doc-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'draft.md',+ id: 'live-agent-doc-1',+ parentId: null,+ updatedAt: new Date('2024-01-04T00:00:00.000Z'),+ },+ ]);++ const service = new AgentDocumentVfsService(db, userId);++ const stats = await service.restoreFromTrash('deleted-agent-doc-1', { agentId: 'agent-1' });++ expect(stats.documentId).toBe('deleted-doc-1');+ expect(mockAgentDocumentModel.restore).toHaveBeenCalledWith('deleted-agent-doc-1');+ });++ it('permanently deletes ordinary directory subtrees child-first', async () => {+ // ROOT CAUSE:+ // Permanent deletion removed document rows without reclaiming hidden backing uploads.+ // Returned file IDs now go through reference-safe cleanup after each committed deletion.+ mockAgentDocumentModel.permanentlyDelete+ .mockResolvedValueOnce(['child-file'])+ .mockResolvedValueOnce([]);+ mockAgentDocumentModel.findByIdWithOptions.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ deletedAt: new Date('2024-01-03T00:00:00.000Z'),+ documentId: 'folder-doc-1',+ fileType: 'custom/folder',+ filename: 'notes',+ id: 'folder-agent-doc-1',+ parentId: null,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });+ mockAgentDocumentModel.listByParent+ .mockResolvedValueOnce([+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'hello',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ deletedAt: new Date('2024-01-03T00:00:00.000Z'),+ documentId: 'child-doc-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'todo.md',+ id: 'child-agent-doc-1',+ parentId: 'folder-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ },+ ])+ .mockResolvedValueOnce([]);++ const service = new AgentDocumentVfsService(db, userId);+ await service.deletePermanently('folder-agent-doc-1', { agentId: 'agent-1' });++ expect(mockAgentDocumentModel.permanentlyDelete).toHaveBeenNthCalledWith(+ 1,+ 'child-agent-doc-1',+ );+ expect(mockAgentDocumentModel.permanentlyDelete).toHaveBeenNthCalledWith(+ 2,+ 'folder-agent-doc-1',+ );+ /** @example The child upload is reclaimed using the dedicated source policy. */+ expect(removeUnreferencedFile.mock.calls).toEqual([['child-file', FileSource.AgentDocument]]);+ });++ it('opts read-only mounted skill paths out of trash deletes', async () => {+ const service = new AgentDocumentVfsService(db, userId);++ await expect(+ service.delete('./lobe/skills/builtin/skills/lobehub/SKILL.md', { agentId: 'agent-1' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it('lists trash entries with reconstructed VFS paths', async () => {+ mockAgentDocumentModel.listDeletedByAgent.mockResolvedValue([+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'hello',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ deleteReason: 'user-delete',+ deletedAt: new Date('2024-01-03T00:00:00.000Z'),+ documentId: 'child-doc-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'todo.md',+ id: 'child-agent-doc-1',+ parentId: 'folder-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ },+ ]);+ mockAgentDocumentModel.findByDocumentId.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ deleteReason: 'recursive-delete',+ deletedAt: new Date('2024-01-03T00:00:00.000Z'),+ documentId: 'folder-doc-1',+ fileType: 'custom/folder',+ filename: 'notes',+ id: 'folder-agent-doc-1',+ parentId: null,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });++ const service = new AgentDocumentVfsService(db, userId);+ const entries = await service.listTrash({ agentId: 'agent-1' });++ expect(entries).toEqual([+ expect.objectContaining({+ deleteReason: 'user-delete',+ deletedAt: new Date('2024-01-03T00:00:00.000Z'),+ path: './notes/todo.md',+ }),+ ]);+ });++ it('requires recursive=true to delete a directory', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(folderDoc('notes', 'f-1'));+ mockAgentDocumentModel.listByParent.mockResolvedValue([]);++ const service = new AgentDocumentVfsService(db, userId);++ await expect(service.delete('./notes', { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });++ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);+ await expect(service.delete('./missing', { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mockAgentDocumentModel.delete).not.toHaveBeenCalled();+ });++ it('deletes an agent skill through its SKILL.md path', async () => {+ const service = new AgentDocumentVfsService(db, userId);++ await service.delete('./lobe/skills/agent/skills/writer', {+ agentId: 'agent-1',+ topicId: 'topic-1',+ });++ expect(mockSkillMount.delete).toHaveBeenCalledWith({+ agentId: 'agent-1',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ topicId: 'topic-1',+ });+ await expect(+ service.delete('./lobe/skills/agent/skills', { agentId: 'agent-1' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('filters trash entries by path prefix', async () => {+ mockAgentDocumentModel.listDeletedByAgent.mockResolvedValue([+ { ...fileDoc('todo.md', 'todo-doc'), deletedAt: new Date('2024-01-03T00:00:00.000Z') },+ { ...fileDoc('todo.md', 'nested-doc', 'notes-doc'), deletedAt: null },+ ]);+ mockAgentDocumentModel.findByDocumentId.mockResolvedValue(folderDoc('notes', 'notes-doc'));++ const service = new AgentDocumentVfsService(db, userId);+ const entries = await service.listTrash({ agentId: 'agent-1' }, '/notes');++ expect(entries).toEqual([+ expect.objectContaining({ deletedAt: new Date(0), path: './notes/todo.md' }),+ ]);+ });++ it('resolves trash entries by path for restore and permanent delete', async () => {+ const deleted = {+ ...fileDoc('draft.md', 'draft-doc'),+ deletedAt: new Date('2024-01-03T00:00:00.000Z'),+ };+ mockAgentDocumentModel.listDeletedByAgent.mockResolvedValue([deleted]);+ mockAgentDocumentModel.findByIdWithOptions.mockResolvedValue(deleted);+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(deleted);++ const service = new AgentDocumentVfsService(db, userId);+ const ctx = { agentId: 'agent-1' };++ await expect(service.restoreFromTrashByPath('./other.md', ctx)).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(service.deletePermanentlyByPath('./other.md', ctx)).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });++ const restored = await service.restoreFromTrashByPath('./draft.md', ctx);+ expect(mockAgentDocumentModel.findByIdWithOptions).toHaveBeenCalledWith('agent-draft-doc', {+ includeDeleted: true,+ });+ expect(mockAgentDocumentModel.restore).toHaveBeenCalledWith('agent-draft-doc');+ expect(restored).toEqual(expect.objectContaining({ path: './draft.md' }));++ await service.deletePermanentlyByPath('./draft.md', ctx);+ expect(mockAgentDocumentModel.permanentlyDelete).toHaveBeenCalledWith('agent-draft-doc');+ });++ it('restores deleted ancestors before the subtree and rejects live entries', async () => {+ const root = {+ ...fileDoc('todo.md', 'todo-doc', 'notes-doc'),+ deletedAt: new Date('2024-01-03T00:00:00.000Z'),+ };+ const parent = { ...folderDoc('notes', 'notes-doc'), deletedAt: new Date('2024-01-03') };+ mockAgentDocumentModel.findByIdWithOptions.mockResolvedValueOnce(root);+ mockAgentDocumentModel.findByDocumentId.mockResolvedValue(parent);+ mockAgentDocumentModel.listByParentAndFilename.mockImplementation(+ async (_agentId, parentId, filename) => {+ if (parentId === null && filename === 'notes') return [parent];+ if (parentId === 'notes-doc' && filename === 'todo.md') return [root];+ return [];+ },+ );++ const service = new AgentDocumentVfsService(db, userId);+ const restored = await service.restoreFromTrash('agent-todo-doc', { agentId: 'agent-1' });++ expect(mockAgentDocumentModel.restore.mock.calls).toEqual([+ ['agent-notes-doc'],+ ['agent-todo-doc'],+ ]);+ expect(restored).toEqual(expect.objectContaining({ path: './notes/todo.md' }));++ mockAgentDocumentModel.findByIdWithOptions.mockResolvedValueOnce({+ ...root,+ deletedAt: null,+ });+ await expect(+ service.restoreFromTrash('agent-todo-doc', { agentId: 'agent-1' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ mockAgentDocumentModel.findByIdWithOptions.mockResolvedValueOnce(undefined);+ await expect(+ service.deletePermanently('agent-todo-doc', { agentId: 'agent-1' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+});diff --git a/apps/server/src/services/agentDocumentVfs/index.ts b/apps/server/src/services/agentDocumentVfs/index.tsindex 58ffa73ebb6..ae261863fad 100644--- a/apps/server/src/services/agentDocumentVfs/index.ts+++ b/apps/server/src/services/agentDocumentVfs/index.ts@@ -1,86 +1,65 @@import type { LobeChatDatabase } from '@lobechat/database';-import { FileSource } from '@lobechat/types';import type { AgentDocument } from '@/database/models/agentDocuments';-import {- AgentAccess,- AgentDocumentModel,- buildDocumentFilename,-} from '@/database/models/agentDocuments';+import { AgentDocumentModel } from '@/database/models/agentDocuments';import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';-import {- getAgentDocumentContentType,- RAW_TEXT_DOCUMENT_FILE_TYPE,-} from '../agentDocuments/contentFormat';-import { createAgentMarkdownSnapshot } from '../agentDocuments/headlessEditor';+import { getAgentDocumentContentType } from '../agentDocuments/contentFormat';import { FileService } from '../file';+import type { AgentDocumentVfsDeps } from './deps';import { AgentDocumentVfsError } from './errors';+import { deleteMountedSkill, writeMountedSkill } from './mountedSkills';import { createSkillMount } from './mounts/skills/createSkillMount';-import {- getUnifiedSkillNamespaceParentPath,- getUnifiedSkillNamespaceRootPath,- isUnifiedSkillPath as isSkillPath,- SKILL_NAMESPACES,- type SkillNamespace,-} from './mounts/skills/path';+import { isUnifiedSkillPath as isSkillPath } from './mounts/skills/path';import type { SkillMount } from './mounts/skills/SkillMount';-import type { SkillMountNode } from './mounts/skills/types';+import {+ createSyntheticDirectoryNode,+ getSyntheticNode,+ listSyntheticChildren,+ toMountedNode,+ toMountedStats,+ toOrdinaryNode,+ toOrdinaryStats,+} from './nodes';+import { collectOrdinarySubtree, listOrdinaryNodes, resolveOrdinaryPath } from './ordinaryTree';+import { renameOrdinaryPath, writeOrdinaryDocument } from './ordinaryWrites';+import {+ applyListLimit,+ assertNotSelfReferentialCopy,+ buildOrdinaryPath,+ LOBE_PATH,+ normalizeAgentDocumentPath,+ sliceReadContent,+ splitAgentDocumentPath,+} from './paths';+import { resolveReadablePath } from './skillPaths';+import {+ deletePermanently,+ deletePermanentlyByPath,+ listTrash,+ restoreFromTrash,+ restoreFromTrashByPath,+} from './trash';import type {+ AgentDocumentCopyOptions,+ AgentDocumentDeleteOptions,AgentDocumentListOptions,+ AgentDocumentMkdirOptions,AgentDocumentNode,AgentDocumentReadOptions,AgentDocumentReadResult,AgentDocumentStats,AgentDocumentTrashEntry,+ AgentDocumentVfsContext,+ AgentDocumentWriteOptions,} from './types';-const LOBE_PATH = './lobe';-const LOBE_SKILLS_PATH = './lobe/skills';-/**- * Default cap for VFS directory reads while the public API still returns arrays.- * Keep this near path constants because it is part of the VFS surface, not storage policy.- */-const DEFAULT_LIST_LIMIT = 100;-/**- * Maximum one-call VFS directory read size.- * Prevents accidental wide-directory materialization from CLI or tool callers.- */-const MAX_LIST_LIMIT = 500;/*** Internal recursive copy safety cap.* This is intentionally separate from public listing pagination so `rename()` never drops children.*/const MAX_RECURSIVE_COPY_CHILDREN = 5000;-const SYNTHETIC_DIRECTORY_MODE = AgentAccess.LIST | AgentAccess.READ;--interface AgentDocumentVfsContext {- agentId: string;- topicId?: string;-}--interface AgentDocumentWriteOptions {- /**- * Raw writes bypass the Markdown editor snapshot because arbitrary tool or code output may- * contain markup that the editor legitimately normalizes or discards.- */- contentFormat?: 'markdown' | 'raw';- createMode?: 'always-new' | 'if-missing' | 'must-exist';-}--interface AgentDocumentMkdirOptions {- recursive?: boolean;-}--interface AgentDocumentDeleteOptions {- recursive?: boolean;-}--interface AgentDocumentCopyOptions {- overwrite?: boolean;-}-/*** Unified filesystem view for ordinary agent documents plus mounted subtrees.*@@ -108,6 +87,8 @@ export class AgentDocumentVfsService {private skillMount: SkillMount;private fileServiceInstance?: FileService;+ private readonly deps: AgentDocumentVfsDeps;+constructor(private readonly db: LobeChatDatabase,private readonly userId: string,@@ -115,6 +96,11 @@ export class AgentDocumentVfsService {) {this.agentDocumentModel = new AgentDocumentModel(db, userId, workspaceId);this.skillMount = createSkillMount(db, userId, workspaceId);+ this.deps = {+ agentDocumentModel: this.agentDocumentModel,+ getFileService: () => this.fileService,+ skillMount: this.skillMount,+ };}/** Defers storage configuration until a permanent deletion actually has uploads to reclaim. */@@ -149,14 +135,14 @@ export class AgentDocumentVfsService {if (normalizedPath === './') {const [ordinaryNodes, lobeNode] = await Promise.all([- this.listOrdinaryNodes(ctx.agentId, null, './', options),- Promise.resolve(this.createSyntheticDirectoryNode(LOBE_PATH, 'lobe')),+ listOrdinaryNodes(this.deps, ctx.agentId, null, './', options),+ Promise.resolve(createSyntheticDirectoryNode(LOBE_PATH, 'lobe')),]);return [...ordinaryNodes, lobeNode];}- const syntheticChildren = this.listSyntheticChildren(normalizedPath);+ const syntheticChildren = listSyntheticChildren(normalizedPath);if (syntheticChildren) return syntheticChildren;@@ -168,12 +154,12 @@ export class AgentDocumentVfsService {});return applyListLimit(- nodes.map((node) => this.toMountedNode(node)),+ nodes.map((node) => toMountedNode(node)),options,);}- const parentNode = await this.resolveOrdinaryPath(normalizedPath, ctx.agentId);+ const parentNode = await resolveOrdinaryPath(this.deps, normalizedPath, ctx.agentId);if (!parentNode) {throw new AgentDocumentVfsError(`Path not found: ${normalizedPath}`, 'NOT_FOUND');@@ -183,7 +169,13 @@ export class AgentDocumentVfsService {throw new AgentDocumentVfsError(`Path is not a directory: ${normalizedPath}`, 'BAD_REQUEST');}- return this.listOrdinaryNodes(ctx.agentId, parentNode.documentId, normalizedPath, options);+ return listOrdinaryNodes(+ this.deps,+ ctx.agentId,+ parentNode.documentId,+ normalizedPath,+ options,+ );}/**@@ -198,7 +190,7 @@ export class AgentDocumentVfsService {*/async stat(path: string, ctx: AgentDocumentVfsContext): Promise<AgentDocumentStats | undefined> {const normalizedPath = normalizeAgentDocumentPath(path);- const syntheticNode = this.getSyntheticNode(normalizedPath);+ const syntheticNode = getSyntheticNode(normalizedPath);if (syntheticNode) return syntheticNode;@@ -209,11 +201,11 @@ export class AgentDocumentVfsService {topicId: ctx.topicId,});- return this.toMountedStats(node);+ return toMountedStats(node);}- const ordinaryNode = await this.resolveOrdinaryPath(normalizedPath, ctx.agentId);- return ordinaryNode ? this.toOrdinaryStats(ordinaryNode, normalizedPath) : undefined;+ const ordinaryNode = await resolveOrdinaryPath(this.deps, normalizedPath, ctx.agentId);+ return ordinaryNode ? toOrdinaryStats(ordinaryNode, normalizedPath) : undefined;}/**@@ -250,7 +242,7 @@ export class AgentDocumentVfsService {};}- const node = await this.resolveOrdinaryPath(normalizedPath, ctx.agentId);+ const node = await resolveOrdinaryPath(this.deps, normalizedPath, ctx.agentId);if (!node) {throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');@@ -290,10 +282,11 @@ export class AgentDocumentVfsService {const createMode = options.createMode ?? 'if-missing';if (isSkillPath(normalizedPath)) {- return this.writeMountedSkill(normalizedPath, content, ctx, createMode);+ return writeMountedSkill(this.deps, normalizedPath, content, ctx, createMode);}- return this.writeOrdinaryDocument(+ return writeOrdinaryDocument(+ this.deps,normalizedPath,content,ctx,@@ -380,7 +373,7 @@ export class AgentDocumentVfsService {throw new AgentDocumentVfsError(`Invalid directory path: ${path}`, 'BAD_REQUEST');}- return this.toOrdinaryStats(currentNode, normalizedPath);+ return toOrdinaryStats(currentNode, normalizedPath);}/**@@ -420,7 +413,9 @@ export class AgentDocumentVfsService {assertNotSelfReferentialCopy(sourcePath, destinationPath, sourceNode);if (!isSkillPath(sourcePath) && !isSkillPath(destinationPath)) {- return this.renameOrdinaryPath(sourcePath, destinationPath, ctx, options);+ return renameOrdinaryPath(this.deps, sourcePath, destinationPath, ctx, options, (path, ctx) =>+ this.delete(path, ctx),+ );}const copied = await this.copy(sourcePath, destinationPath, ctx, options);@@ -502,17 +497,17 @@ export class AgentDocumentVfsService {const normalizedPath = normalizeAgentDocumentPath(path);if (isSkillPath(normalizedPath)) {- await this.deleteMountedSkill(normalizedPath, ctx);+ await deleteMountedSkill(this.deps, normalizedPath, ctx);return;}- const node = await this.resolveOrdinaryPath(normalizedPath, ctx.agentId);+ const node = await resolveOrdinaryPath(this.deps, normalizedPath, ctx.agentId);if (!node) {throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');}- const subtree = await this.collectOrdinarySubtree(node, ctx.agentId, true);+ const subtree = await collectOrdinarySubtree(this.deps, node, ctx.agentId, true);if (node.fileType === DOCUMENT_FOLDER_TYPE && !options.recursive) {throw new AgentDocumentVfsError(@@ -539,24 +534,7 @@ export class AgentDocumentVfsService {* - Flat trash entries with reconstructed paths*/async listTrash(ctx: AgentDocumentVfsContext, path?: string): Promise<AgentDocumentTrashEntry[]> {- const deletedDocs = await this.agentDocumentModel.listDeletedByAgent(ctx.agentId);- const entries = await Promise.all(- deletedDocs.map(async (doc) => {- const path = await this.buildOrdinaryPathFromNode(doc, ctx.agentId);- return {- ...this.toOrdinaryStats(doc, path),- deleteReason: doc.deleteReason,- deletedAt: doc.deletedAt ?? new Date(0),- } satisfies AgentDocumentTrashEntry;- }),- );-- if (!path) return entries;-- const normalizedPath = normalizeAgentDocumentPath(path);- return entries.filter(- (entry) => entry.path === normalizedPath || entry.path.startsWith(`${normalizedPath}/`),- );+ return listTrash(this.deps, ctx, path);}/**@@ -572,42 +550,7 @@ export class AgentDocumentVfsService {agentDocumentId: string,ctx: AgentDocumentVfsContext,): Promise<AgentDocumentStats> {- const root = await this.agentDocumentModel.findByIdWithOptions(agentDocumentId, {- includeDeleted: true,- });-- if (!root?.deletedAt) {- throw new AgentDocumentVfsError(`Trash entry not found: ${agentDocumentId}`, 'NOT_FOUND');- }-- const ancestors = await this.collectDeletedAncestors(root, ctx.agentId);- const subtree = await this.collectOrdinarySubtree(root, ctx.agentId, true);-- for (const ancestor of ancestors.reverse()) {- if (ancestor.deletedAt) {- await this.agentDocumentModel.restore(ancestor.id);- }- }-- for (const item of subtree) {- if (item.deletedAt) {- await this.agentDocumentModel.restore(item.id);- }- }-- const restored = await this.resolveOrdinaryPath(- await this.buildOrdinaryPathFromNode(root, ctx.agentId),- ctx.agentId,- );-- if (!restored) {- throw new AgentDocumentVfsError(`Failed to restore path: ${agentDocumentId}`, 'BAD_REQUEST');- }-- return this.toOrdinaryStats(- restored,- await this.buildOrdinaryPathFromNode(restored, ctx.agentId),- );+ return restoreFromTrash(this.deps, agentDocumentId, ctx);}/**@@ -620,106 +563,25 @@ export class AgentDocumentVfsService {* - Void*/async deletePermanently(agentDocumentId: string, ctx: AgentDocumentVfsContext): Promise<void> {- const root = await this.agentDocumentModel.findByIdWithOptions(agentDocumentId, {- includeDeleted: true,- });-- if (!root?.deletedAt) {- throw new AgentDocumentVfsError(`Trash entry not found: ${agentDocumentId}`, 'NOT_FOUND');- }-- const subtree = await this.collectOrdinarySubtree(root, ctx.agentId, true);-- for (const item of subtree.reverse()) {- const fileIds = await this.agentDocumentModel.permanentlyDelete(item.id);- for (const fileId of fileIds) {- await this.fileService.removeUnreferencedFile(fileId, FileSource.AgentDocument);- }- }+ return deletePermanently(this.deps, agentDocumentId, ctx);}async restoreFromTrashByPath(path: string,ctx: AgentDocumentVfsContext,): Promise<AgentDocumentStats> {- const entry = await this.findTrashEntryByPath(path, ctx);-- if (!entry) {- throw new AgentDocumentVfsError(`Trash entry not found: ${path}`, 'NOT_FOUND');- }-- return this.restoreFromTrash(entry.agentDocumentId!, ctx);+ return restoreFromTrashByPath(this.deps, path, ctx);}async deletePermanentlyByPath(path: string, ctx: AgentDocumentVfsContext): Promise<void> {- const entry = await this.findTrashEntryByPath(path, ctx);-- if (!entry) {- throw new AgentDocumentVfsError(`Trash entry not found: ${path}`, 'NOT_FOUND');- }-- await this.deletePermanently(entry.agentDocumentId!, ctx);- }-- private async listOrdinaryNodes(- agentId: string,- parentId: string | null,- parentPath: string,- options: AgentDocumentListOptions = {},- ): Promise<AgentDocumentNode[]> {- const docs = await this.agentDocumentModel.listByParent(agentId, parentId, {- cursor: options.cursor,- });- const visibleDocs = selectOldestByFilename(docs);- return applyListLimit(- visibleDocs.map((doc) =>- this.toOrdinaryNode(doc, buildOrdinaryPath(parentPath, doc.filename)),- ),- options,- );- }-- private async resolveOrdinaryPath(- path: string,- agentId: string,- ): Promise<AgentDocument | undefined> {- return this.resolveOrdinaryPathWithOptions(path, agentId);- }-- private async resolveOrdinaryPathWithOptions(- path: string,- agentId: string,- options?: { includeDeleted?: boolean },- ): Promise<AgentDocument | undefined> {- if (path === './') return undefined;-- const segments = splitAgentDocumentPath(path);- let parentId: string | null = null;- let current: AgentDocument | undefined;-- for (const segment of segments) {- const candidates = await this.agentDocumentModel.listByParentAndFilename(- agentId,- parentId,- segment,- {- ...options,- },- );-- current = selectOldestAgentDocument(candidates);- if (!current) return undefined;- parentId = current.documentId;- }-- return current;+ return deletePermanentlyByPath(this.deps, path, ctx);}private async listChildrenForRecursiveCopy(path: string,ctx: AgentDocumentVfsContext,): Promise<AgentDocumentNode[]> {- const syntheticChildren = this.listSyntheticChildren(path);+ const syntheticChildren = listSyntheticChildren(path);if (syntheticChildren) return syntheticChildren;@@ -730,10 +592,10 @@ export class AgentDocumentVfsService {topicId: ctx.topicId,});- return nodes.map((node) => this.toMountedNode(node));+ return nodes.map((node) => toMountedNode(node));}- const parentNode = await this.resolveOrdinaryPath(path, ctx.agentId);+ const parentNode = await resolveOrdinaryPath(this.deps, path, ctx.agentId);if (!parentNode) {throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');@@ -754,652 +616,6 @@ export class AgentDocumentVfsService {);}- return docs.map((doc) => this.toOrdinaryNode(doc, buildOrdinaryPath(path, doc.filename)));- }-- private async writeMountedSkill(- path: string,- content: string,- ctx: AgentDocumentVfsContext,- createMode: NonNullable<AgentDocumentWriteOptions['createMode']>,- ): Promise<AgentDocumentStats> {- const existing = await this.skillMount- .get({- agentId: ctx.agentId,- path,- topicId: ctx.topicId,- })- .catch((error) => {- if (error instanceof AgentDocumentVfsError && error.code === 'NOT_FOUND') return undefined;- throw error;- });-- if (!existing && createMode === 'must-exist') {- throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');- }-- if (existing && createMode === 'always-new') {- throw new AgentDocumentVfsError(`Path already exists: ${path}`, 'CONFLICT');- }-- let nextNode: SkillMountNode;-- if (existing) {- nextNode = await this.skillMount.update({- agentId: ctx.agentId,- content,- path,- topicId: ctx.topicId,- });- } else {- const { namespace, skillName } = inferMountedSkillIdentity(path);- nextNode = await this.skillMount.create({- agentId: ctx.agentId,- content,- skillName,- targetNamespace: namespace,- topicId: ctx.topicId,- });- }-- return this.toMountedStats(nextNode);- }-- private async writeOrdinaryDocument(- path: string,- content: string,- ctx: AgentDocumentVfsContext,- createMode: NonNullable<AgentDocumentWriteOptions['createMode']>,- contentFormat: NonNullable<AgentDocumentWriteOptions['contentFormat']>,- ): Promise<AgentDocumentStats> {- if (path === './' || path === LOBE_PATH || path.startsWith(`${LOBE_PATH}/`)) {- throw new AgentDocumentVfsError(`Cannot write reserved path: ${path}`, 'BAD_REQUEST');- }-- const exactExisting = await this.resolveOrdinaryPath(path, ctx.agentId);- const writablePath = exactExisting ? path : normalizeOrdinaryDocumentPath(path);- const existing = exactExisting ?? (await this.resolveOrdinaryPath(writablePath, ctx.agentId));-- if (existing) {- if (existing.fileType === DOCUMENT_FOLDER_TYPE) {- throw new AgentDocumentVfsError(`Path is not a file: ${writablePath}`, 'BAD_REQUEST');- }-- if (createMode === 'always-new') {- throw new AgentDocumentVfsError(`Path already exists: ${writablePath}`, 'BAD_REQUEST');- }-- if (contentFormat === 'raw') {- await this.agentDocumentModel.update(existing.id, {- content,- editorData: null,- fileType: RAW_TEXT_DOCUMENT_FILE_TYPE,- });- } else {- const snapshot = await createAgentMarkdownSnapshot(content);- await this.agentDocumentModel.update(existing.id, {- content: snapshot.content,- editorData: snapshot.editorData,- });- }-- const updated = await this.resolveOrdinaryPath(writablePath, ctx.agentId);-- if (!updated) {- throw new AgentDocumentVfsError(- `Failed to reload updated path: ${writablePath}`,- 'BAD_REQUEST',- );- }-- return this.toOrdinaryStats(updated, writablePath);- }-- if (createMode === 'must-exist') {- throw new AgentDocumentVfsError(`Path not found: ${writablePath}`, 'NOT_FOUND');- }-- const segments = splitAgentDocumentPath(writablePath);- const filename = segments.at(-1);-- if (!filename) {- throw new AgentDocumentVfsError(`Invalid VFS path: ${writablePath}`, 'BAD_REQUEST');- }-- const parentPath = segments.length === 1 ? './' : `./${segments.slice(0, -1).join('/')}`;- const parentNode =- parentPath === './' ? undefined : await this.resolveOrdinaryPath(parentPath, ctx.agentId);-- if (parentPath !== './' && !parentNode) {- throw new AgentDocumentVfsError(`Parent path not found: ${parentPath}`, 'BAD_REQUEST');- }-- if (parentNode && parentNode.fileType !== DOCUMENT_FOLDER_TYPE) {- throw new AgentDocumentVfsError(- `Parent path is not a directory: ${parentPath}`,- 'BAD_REQUEST',- );- }-- const normalizedFilename = buildDocumentFilename(filename);- if (contentFormat === 'raw') {- const created = await this.agentDocumentModel.create(- ctx.agentId,- normalizedFilename,- content,- {- fileType: RAW_TEXT_DOCUMENT_FILE_TYPE,- parentId: parentNode?.documentId ?? null,- title: normalizedFilename,- },- );-- return this.toOrdinaryStats(created, buildOrdinaryPath(parentPath, normalizedFilename));- }-- const snapshot = await createAgentMarkdownSnapshot(content);- const created = await this.agentDocumentModel.create(- ctx.agentId,- normalizedFilename,- snapshot.content,- {- editorData: snapshot.editorData,- parentId: parentNode?.documentId ?? null,- title: normalizedFilename,- },- );-- return this.toOrdinaryStats(created, buildOrdinaryPath(parentPath, normalizedFilename));- }-- private async renameOrdinaryPath(- sourcePath: string,- destinationPath: string,- ctx: AgentDocumentVfsContext,- options: AgentDocumentCopyOptions,- ): Promise<AgentDocumentStats> {- if (- destinationPath === './' ||- destinationPath === LOBE_PATH ||- destinationPath.startsWith(`${LOBE_PATH}/`)- ) {- throw new AgentDocumentVfsError(- `Cannot rename to reserved path: ${destinationPath}`,- 'BAD_REQUEST',- );- }-- const sourceNode = await this.resolveOrdinaryPath(sourcePath, ctx.agentId);-- if (!sourceNode) {- throw new AgentDocumentVfsError(`Path not found: ${sourcePath}`, 'NOT_FOUND');- }-- const existingDestination = await this.resolveOrdinaryPath(destinationPath, ctx.agentId);-- if (existingDestination) {- if (!options.overwrite) {- throw new AgentDocumentVfsError(`Path already exists: ${destinationPath}`, 'BAD_REQUEST');- }-- if (existingDestination.fileType === DOCUMENT_FOLDER_TYPE) {- throw new AgentDocumentVfsError(- `Cannot overwrite directory path: ${destinationPath}`,- 'BAD_REQUEST',- );- }-- await this.delete(destinationPath, ctx);- }-- const segments = splitAgentDocumentPath(destinationPath);- const filename = segments.at(-1);-- if (!filename) {- throw new AgentDocumentVfsError(`Invalid VFS path: ${destinationPath}`, 'BAD_REQUEST');- }-- const parentPath = segments.length === 1 ? './' : `./${segments.slice(0, -1).join('/')}`;- const parentNode =- parentPath === './' ? undefined : await this.resolveOrdinaryPath(parentPath, ctx.agentId);-- if (parentPath !== './' && !parentNode) {- throw new AgentDocumentVfsError(`Parent path not found: ${parentPath}`, 'BAD_REQUEST');- }-- if (parentNode && parentNode.fileType !== DOCUMENT_FOLDER_TYPE) {- throw new AgentDocumentVfsError(- `Parent path is not a directory: ${parentPath}`,- 'BAD_REQUEST',- );- }-- const parentId = parentNode?.documentId ?? null;- const moved = await this.agentDocumentModel.movePath(sourceNode.id, {- filename,- parentId,- });-- if (!moved) {- throw new AgentDocumentVfsError(`Failed to rename path: ${sourcePath}`, 'BAD_REQUEST');- }-- return this.toOrdinaryStats(moved, destinationPath);- }-- private toOrdinaryNode(doc: AgentDocument, path: string): AgentDocumentNode {- return {- agentDocumentId: doc.id,- createdAt: doc.createdAt,- documentId: doc.documentId,- id: doc.id,- mode: doc.accessSelf,- mount: {- driver: 'agent-documents',- source: 'documents',- },- name: doc.filename,- path,- size: doc.content.length,- type: doc.fileType === DOCUMENT_FOLDER_TYPE ? 'directory' : 'file',- updatedAt: doc.updatedAt,- };- }-- private toOrdinaryStats(doc: AgentDocument, path: string): AgentDocumentStats {- return {- ...this.toOrdinaryNode(doc, path),- contentType:- doc.fileType === DOCUMENT_FOLDER_TYPE ? undefined : getAgentDocumentContentType(doc),- deleteReason: doc.deleteReason,- deletedAt: doc.deletedAt,- metadata: doc.metadata ?? undefined,- };- }-- private toMountedNode(node: SkillMountNode): AgentDocumentNode {- return {- id: `skills:${node.namespace}:${node.path}`,- mode: skillNodeToMode(node),- mount: {- driver: 'skills',- namespace: node.namespace,- source: resolveSkillMountSource(node.namespace),- },- name: node.name,- path: node.path,- size: node.size ?? (node.type === 'file' ? node.content?.length : undefined),- type: node.type,- };- }-- private toMountedStats(node: SkillMountNode): AgentDocumentStats {- return {- ...this.toMountedNode(node),- contentType: node.contentType,- };- }-- private createSyntheticDirectoryNode(path: string, name: string): AgentDocumentNode {- return {- id: `synthetic:${path}`,- mode: SYNTHETIC_DIRECTORY_MODE,- mount: {- driver: 'synthetic',- source: 'virtual',- },- name,- path,- type: 'directory',- };- }-- private getSyntheticNode(path: string): AgentDocumentStats | undefined {- if (path === './') return { ...this.createSyntheticDirectoryNode('./', '') };- if (path === LOBE_PATH) return { ...this.createSyntheticDirectoryNode(LOBE_PATH, 'lobe') };- if (path === LOBE_SKILLS_PATH) {- return { ...this.createSyntheticDirectoryNode(LOBE_SKILLS_PATH, 'skills') };- }-- const namespace = getSkillNamespaceDirectory(path);-- if (namespace) {- const name = path.split('/').at(-1)!;- return {- ...this.createSyntheticDirectoryNode(path, name),- mount: buildSkillMountInfo(namespace),- };- }-- return undefined;- }-- private listSyntheticChildren(path: string): AgentDocumentNode[] | undefined {- if (path === LOBE_PATH) {- return [this.createSyntheticDirectoryNode(LOBE_SKILLS_PATH, 'skills')];- }-- if (path === LOBE_SKILLS_PATH) {- return [- this.createSyntheticDirectoryNode('./lobe/skills/builtin', 'builtin'),- this.createSyntheticDirectoryNode('./lobe/skills/installed', 'installed'),- this.createSyntheticDirectoryNode('./lobe/skills/agent', 'agent'),- ];- }-- if (path === './lobe/skills/installed') {- return [- this.createSyntheticDirectoryNode('./lobe/skills/installed/all', 'all'),- this.createSyntheticDirectoryNode('./lobe/skills/installed/active', 'active'),- ];- }-- const namespace = getSkillNamespaceCollectionParent(path);-- if (namespace) {- return [- {- ...this.createSyntheticDirectoryNode(- getUnifiedSkillNamespaceRootPath(namespace),- 'skills',- ),- mount: buildSkillMountInfo(namespace),- },- ];- }-- return undefined;- }-- private async collectOrdinarySubtree(- root: AgentDocument,- agentId: string,- includeDeleted: boolean,- ): Promise<AgentDocument[]> {- const nodes = [root];-- if (root.fileType !== DOCUMENT_FOLDER_TYPE) return nodes;-- const queue: AgentDocument[] = [root];-- while (queue.length > 0) {- const current = queue.shift()!;- const children = await this.agentDocumentModel.listByParent(agentId, current.documentId, {- includeDeleted,- });-- for (const child of children) {- nodes.push(child);- if (child.fileType === DOCUMENT_FOLDER_TYPE) {- queue.push(child);- }- }- }-- return nodes;- }-- private async collectDeletedAncestors(- node: AgentDocument,- agentId: string,- ): Promise<AgentDocument[]> {- const ancestors: AgentDocument[] = [];- let parentId = node.parentId;-- while (parentId) {- const parent = await this.agentDocumentModel.findByDocumentId(agentId, parentId, {- includeDeleted: true,- });-- if (!parent) break;- ancestors.push(parent);- parentId = parent.parentId;- }-- return ancestors;- }-- private async buildOrdinaryPathFromNode(node: AgentDocument, agentId: string): Promise<string> {- const segments = [node.filename];- let parentId = node.parentId;-- while (parentId) {- const parent = await this.agentDocumentModel.findByDocumentId(agentId, parentId, {- includeDeleted: true,- });-- if (!parent) break;- segments.unshift(parent.filename);- parentId = parent.parentId;- }-- return `./${segments.join('/')}`;- }-- private async deleteMountedSkill(path: string, ctx: AgentDocumentVfsContext) {- const { namespace, skillName } = inferMountedSkillIdentity(resolveWritableMountedPath(path));-- if (namespace !== 'agent') {- throw new AgentDocumentVfsError(`Path is read-only: ${path}`, 'FORBIDDEN');- }-- await this.skillMount.delete({- agentId: ctx.agentId,- path: `${getUnifiedSkillNamespaceRootPath(namespace)}/${skillName}/SKILL.md`,- topicId: ctx.topicId,- });- }-- private async findTrashEntryByPath(path: string, ctx: AgentDocumentVfsContext) {- const normalizedPath = normalizeAgentDocumentPath(path);- const entries = await this.listTrash(ctx);- return entries.find((entry) => entry.path === normalizedPath);+ return docs.map((doc) => toOrdinaryNode(doc, buildOrdinaryPath(path, doc.filename)));}}--const normalizeAgentDocumentPath = (path: string) => {- const raw = path.trim();- const withDot =- raw === '/' ? './' : raw.startsWith('./') ? raw : raw.startsWith('/') ? `.${raw}` : `./${raw}`;- const collapsed = withDot.replaceAll(/\/+/g, '/');-- if (collapsed.includes('/./') || collapsed.includes('/../') || collapsed.endsWith('/..')) {- throw new AgentDocumentVfsError(`Invalid VFS path: ${path}`, 'BAD_REQUEST');- }-- const normalized = collapsed === './' ? './' : collapsed.replace(/\/$/, '');- return normalized;-};--const splitAgentDocumentPath = (path: string) =>- path.replace(/^\.\//, '').split('/').filter(Boolean);--const buildOrdinaryPath = (parentPath: string, filename: string) =>- parentPath === './' ? `./${filename}` : `${parentPath}/${filename}`;--const normalizeOrdinaryDocumentPath = (path: string): string => {- const segments = splitAgentDocumentPath(path);- const filename = segments.at(-1);- if (!filename) return path;-- const parentPath = segments.length === 1 ? './' : `./${segments.slice(0, -1).join('/')}`;- const normalizedFilename = buildDocumentFilename(filename);- return buildOrdinaryPath(parentPath, normalizedFilename);-};--const normalizeListLimit = (limit?: number) => {- if (limit === undefined) return DEFAULT_LIST_LIMIT;-- // Clamp caller-provided limits so path APIs stay bounded even when invoked by tools.- return Math.min(Math.max(Math.trunc(limit), 1), MAX_LIST_LIMIT);-};--const applyListLimit = <T>(items: T[], options: AgentDocumentListOptions) =>- items.slice(0, normalizeListLimit(options.limit));--const compareAgentDocumentAge = (left: AgentDocument, right: AgentDocument) => {- const leftCreatedAt = left.createdAt?.getTime?.() ?? 0;- const rightCreatedAt = right.createdAt?.getTime?.() ?? 0;-- if (leftCreatedAt !== rightCreatedAt) return leftCreatedAt - rightCreatedAt;-- return left.id.localeCompare(right.id);-};--const selectOldestAgentDocument = (documents: AgentDocument[]) =>- [...documents].sort(compareAgentDocumentAge)[0];--const selectOldestByFilename = (documents: AgentDocument[]) => {- const visibleByFilename = new Map<string, AgentDocument>();-- for (const document of [...documents].sort(compareAgentDocumentAge)) {- if (visibleByFilename.has(document.filename)) continue;- visibleByFilename.set(document.filename, document);- }-- return [...visibleByFilename.values()];-};--const isDescendantPath = (parentPath: string, childPath: string) =>- childPath !== parentPath && childPath.startsWith(`${parentPath}/`);--const assertNotSelfReferentialCopy = (- sourcePath: string,- destinationPath: string,- sourceNode: AgentDocumentStats,-) => {- if (sourcePath === destinationPath) {- throw new AgentDocumentVfsError(`Cannot copy path onto itself: ${sourcePath}`, 'BAD_REQUEST');- }-- if (sourceNode.type === 'directory' && isDescendantPath(sourcePath, destinationPath)) {- throw new AgentDocumentVfsError(- `Cannot copy directory into its own subtree: ${sourcePath} -> ${destinationPath}`,- 'BAD_REQUEST',- );- }-};--const sliceReadContent = (- content: string,- loc?: [number, number],-): Omit<AgentDocumentReadResult, 'contentType' | 'path'> => {- const lines = content.split('\n');- const totalLineCount = lines.length;- const totalCharCount = content.length;- const actualLoc: [number, number] = loc ?? [0, totalLineCount];- const [startLine, endLine] = actualLoc;- const selectedLines = lines.slice(startLine, endLine);- const selectedContent = selectedLines.join('\n');-- return {- charCount: selectedContent.length,- content: selectedContent,- lineCount: selectedLines.length,- loc: actualLoc,- totalCharCount,- totalLineCount,- };-};--const inferMountedSkillIdentity = (path: string) => {- for (const namespace of ['agent'] as const) {- const prefix = getUnifiedSkillNamespaceRootPath(namespace);-- if (path === prefix || !path.startsWith(`${prefix}/`)) continue;-- const relativePath = path.slice(prefix.length + 1);- const [skillName] = relativePath.split('/');-- if (!skillName) {- throw new AgentDocumentVfsError(- `Expected a skill path, but received namespace root: ${path}`,- 'BAD_REQUEST',- );- }-- return { namespace, skillName };- }-- throw new AgentDocumentVfsError(`Namespace is not writable: ${path}`, 'FORBIDDEN');-};--const getSkillNamespaceDirectory = (path: string): SkillNamespace | undefined => {- for (const namespace of SKILL_NAMESPACES) {- const parentPath = getUnifiedSkillNamespaceParentPath(namespace);- const rootPath = getUnifiedSkillNamespaceRootPath(namespace);-- if (path === parentPath || path === rootPath) return namespace;- }-- return undefined;-};--const getSkillNamespaceCollectionParent = (path: string): SkillNamespace | undefined => {- for (const namespace of SKILL_NAMESPACES) {- if (path === getUnifiedSkillNamespaceParentPath(namespace)) return namespace;- }-- return undefined;-};--const buildSkillMountInfo = (namespace: SkillNamespace) => ({- driver: 'skills',- namespace,- source: resolveSkillMountSource(namespace),-});--const resolveSkillMountSource = (namespace: SkillNamespace) => {- if (namespace === 'builtin') return 'builtin';- if (namespace === 'installed-active' || namespace === 'installed-all') return 'installed';- return 'documents';-};--const SKILL_MOUNT_ACCESS = {- 'agent': AgentAccess.READ | AgentAccess.LIST | AgentAccess.WRITE | AgentAccess.DELETE,- 'builtin': AgentAccess.READ | AgentAccess.LIST,- 'installed-active': AgentAccess.READ | AgentAccess.LIST,- 'installed-all': AgentAccess.READ | AgentAccess.LIST,-} as const satisfies Record<SkillNamespace, AgentAccess>;--const skillNodeToMode = (node: SkillMountNode): AgentAccess => {- return SKILL_MOUNT_ACCESS[node.namespace];-};--const resolveWritableMountedPath = (path: string) => {- if (!isSkillPath(path)) return path;-- for (const namespace of ['agent', 'builtin', 'installed-active', 'installed-all'] as const) {- const prefix = getUnifiedSkillNamespaceRootPath(namespace);-- if (path === prefix) {- throw new AgentDocumentVfsError(- `Expected a skill path, but received namespace root: ${path}`,- 'BAD_REQUEST',- );- }-- if (!path.startsWith(`${prefix}/`)) continue;-- const relativePath = path.slice(prefix.length + 1);- const [skillName, ...rest] = relativePath.split('/');-- if (!skillName) {- throw new AgentDocumentVfsError(- `Expected a skill path, but received namespace root: ${path}`,- 'BAD_REQUEST',- );- }-- if (rest.length === 0) {- return `${prefix}/${skillName}/SKILL.md`;- }-- return path;- }-- return path;-};--const resolveReadablePath = (path: string) =>- isSkillPath(path) ? resolveWritableMountedPath(path) : path;diff --git a/apps/server/src/services/agentDocumentVfs/index.write.test.ts b/apps/server/src/services/agentDocumentVfs/index.write.test.tsnew file mode 100644index 00000000000..81fa3b9ceb0--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/index.write.test.ts@@ -0,0 +1,429 @@+// @vitest-environment node+import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentAccess } from '@/database/models/agentDocuments';++import * as headlessEditor from '../agentDocuments/headlessEditor';+import { FileService } from '../file';+import { AgentDocumentVfsService } from './index';+import { db, mockAgentDocumentModel, mockSkillMount, resetVfsMocks, userId } from './testUtils';++vi.mock('@/database/models/agentDocuments', () => ({+ AgentAccess: {+ DELETE: 16,+ EXECUTE: 1,+ LIST: 8,+ READ: 2,+ WRITE: 4,+ },+ AgentDocumentModel: vi.fn(),+ buildDocumentFilename: vi.fn(function (title: string) {+ return title;+ }),+}));++vi.mock('./mounts/skills/createSkillMount', () => ({+ createSkillMount: vi.fn(),+}));++const removeUnreferencedFile = vi.hoisted(() => vi.fn());+vi.mock('../file', () => ({+ FileService: vi.fn(function () {+ return { removeUnreferencedFile };+ }),+}));++const folderDoc = (filename: string, documentId: string, parentId: string | null = null) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId,+ fileType: 'custom/folder',+ filename,+ id: `agent-${documentId}`,+ parentId,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+});++const fileDoc = (+ filename: string,+ documentId: string,+ parentId: string | null = null,+ content = 'hello',+) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content,+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId,+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename,+ id: `agent-${documentId}`,+ parentId,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+});++describe('AgentDocumentVfsService', () => {+ beforeEach(() => {+ vi.mocked(FileService).mockClear();+ removeUnreferencedFile.mockReset().mockResolvedValue(undefined);+ resetVfsMocks();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('creates a new ordinary file through write when the path is missing', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([]);+ mockAgentDocumentModel.create.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'hello',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-2',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'notes.md',+ id: 'agent-doc-2',+ metadata: null,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.write('./notes.md', 'hello', { agentId: 'agent-1' });++ expect(mockAgentDocumentModel.create).toHaveBeenCalledWith(+ 'agent-1',+ 'notes.md',+ expect.any(String),+ expect.objectContaining({+ editorData: expect.any(Object),+ parentId: null,+ title: 'notes.md',+ }),+ );+ expect(node).toEqual(+ expect.objectContaining({+ documentId: 'documents-2',+ path: './notes.md',+ type: 'file',+ }),+ );+ });++ it('stores raw ordinary file content without Markdown serialization', async () => {+ const content = `<knowledge_base_files totalCount="1">+<file id="file-1" name="raw.txt">+${'lossless tool result\n'.repeat(100)}+</file>+</knowledge_base_files>`;+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([]);+ mockAgentDocumentModel.create.mockResolvedValue({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content,+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-raw',+ fileType: 'text/plain',+ filename: 'archive.txt',+ id: 'agent-doc-raw',+ metadata: null,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });+ const createSnapshotSpy = vi.spyOn(headlessEditor, 'createAgentMarkdownSnapshot');+ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.write(+ './archive.txt',+ content,+ { agentId: 'agent-1' },+ {+ contentFormat: 'raw',+ },+ );++ expect(createSnapshotSpy).not.toHaveBeenCalled();+ expect(node.contentType).toBe('text/plain');+ expect(mockAgentDocumentModel.create).toHaveBeenCalledWith('agent-1', 'archive.txt', content, {+ fileType: 'text/plain',+ parentId: null,+ title: 'archive.txt',+ });+ });++ it('overwrites raw ordinary file content without Markdown serialization', async () => {+ const existing = {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'old content',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-raw',+ fileType: 'text/plain',+ filename: 'archive.txt',+ id: 'agent-doc-raw',+ metadata: null,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ };+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(existing);+ mockAgentDocumentModel.update.mockImplementation(async (_id, params) => {+ Object.assign(existing, params);+ });+ const createSnapshotSpy = vi.spyOn(headlessEditor, 'createAgentMarkdownSnapshot');+ const service = new AgentDocumentVfsService(db, userId);++ await service.write(+ './archive.txt',+ 'new raw content',+ { agentId: 'agent-1' },+ {+ contentFormat: 'raw',+ },+ );++ expect(createSnapshotSpy).not.toHaveBeenCalled();+ expect(mockAgentDocumentModel.update).toHaveBeenCalledWith('agent-doc-raw', {+ content: 'new raw content',+ editorData: null,+ fileType: 'text/plain',+ });+ });++ it('resolves duplicate ordinary path segments to the oldest sibling', async () => {+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'first',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-first',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'notes.md',+ id: 'agent-doc-first',+ },+ {+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: 'second',+ createdAt: new Date('2024-01-02T00:00:00.000Z'),+ documentId: 'documents-second',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'notes.md',+ id: 'agent-doc-second',+ },+ ]);++ const service = new AgentDocumentVfsService(db, userId);+ const stats = await service.stat('./notes.md', { agentId: 'agent-1' });++ if (!stats) throw new Error('Expected ./notes.md stats to resolve');++ expect(stats.documentId).toBe('documents-first');+ expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();+ });++ it('updates an existing mounted skill through write', async () => {+ mockSkillMount.get.mockResolvedValue({+ content: '# Draft',+ name: 'SKILL.md',+ namespace: 'agent',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ readOnly: false,+ type: 'file',+ });+ mockSkillMount.update.mockResolvedValue({+ content: '# Final',+ name: 'SKILL.md',+ namespace: 'agent',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ readOnly: false,+ type: 'file',+ });++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.write('./lobe/skills/agent/skills/writer/SKILL.md', '# Final', {+ agentId: 'agent-1',+ });++ expect(mockSkillMount.update).toHaveBeenCalledWith({+ agentId: 'agent-1',+ content: '# Final',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ topicId: undefined,+ });+ expect(node).toEqual(+ expect.objectContaining({+ mount: expect.objectContaining({ driver: 'skills', namespace: 'agent' }),+ size: '# Final'.length,+ }),+ );+ });++ it('creates nested directories through mkdir when recursive is enabled', async () => {+ mockAgentDocumentModel.findByParentAndFilename+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce(undefined);+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([]);+ mockAgentDocumentModel.create+ .mockResolvedValueOnce({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'folder-doc-1',+ fileType: 'custom/folder',+ filename: 'notes',+ id: 'folder-agent-doc-1',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ })+ .mockResolvedValueOnce({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content: '',+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'folder-doc-2',+ fileType: 'custom/folder',+ filename: 'archive',+ id: 'folder-agent-doc-2',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ });++ const service = new AgentDocumentVfsService(db, userId);+ const node = await service.mkdir(+ './notes/archive',+ { agentId: 'agent-1' },+ { recursive: true },+ );++ expect(mockAgentDocumentModel.create).toHaveBeenNthCalledWith(+ 1,+ 'agent-1',+ 'notes',+ '',+ expect.objectContaining({+ fileType: 'custom/folder',+ parentId: null,+ }),+ );+ expect(mockAgentDocumentModel.create).toHaveBeenNthCalledWith(+ 2,+ 'agent-1',+ 'archive',+ '',+ expect.objectContaining({+ fileType: 'custom/folder',+ parentId: 'folder-doc-1',+ }),+ );+ expect(node).toEqual(+ expect.objectContaining({+ path: './notes/archive',+ type: 'directory',+ }),+ );+ });++ it.each(['./', './lobe', './lobe/notes.md'])(+ 'rejects writes to the reserved path %s',+ async (path) => {+ const service = new AgentDocumentVfsService(db, userId);++ await expect(service.write(path, 'x', { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ await expect(service.mkdir(path, { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();+ },+ );++ it('enforces createMode for ordinary writes', async () => {+ const service = new AgentDocumentVfsService(db, userId);++ await expect(+ service.write('./missing.md', 'x', { agentId: 'agent-1' }, { createMode: 'must-exist' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(fileDoc('a.md', 'doc-1'));+ await expect(+ service.write('./a.md', 'x', { agentId: 'agent-1' }, { createMode: 'always-new' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(folderDoc('dir', 'f-1'));+ await expect(service.write('./dir', 'x', { agentId: 'agent-1' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(mockAgentDocumentModel.update).not.toHaveBeenCalled();+ expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();+ });++ it('rejects ordinary writes whose parent is missing or is a file', async () => {+ const service = new AgentDocumentVfsService(db, userId);++ await expect(service.write('./missing/a.md', 'x', { agentId: 'agent-1' })).rejects.toThrow(+ 'Parent path not found: ./missing',+ );++ mockAgentDocumentModel.listByParentAndFilename.mockImplementation(+ async (_agentId, parentId, filename) =>+ parentId === null && filename === 'file.md' ? [fileDoc('file.md', 'doc-1')] : [],+ );+ await expect(service.write('./file.md/a.md', 'x', { agentId: 'agent-1' })).rejects.toThrow(+ 'Parent path is not a directory: ./file.md',+ );+ });++ it('rejects mkdir through a missing parent unless recursive is set', async () => {+ const service = new AgentDocumentVfsService(db, userId);++ await expect(service.mkdir('./a/b', { agentId: 'agent-1' })).rejects.toThrow(+ 'Parent path not found: ./a',+ );+ expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();++ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(fileDoc('a', 'doc-1'));+ await expect(+ service.mkdir('./a/b', { agentId: 'agent-1' }, { recursive: true }),+ ).rejects.toThrow('Path segment is not a directory: ./a');+ await expect(+ service.mkdir('./lobe/skills/agent/skills/x', { agentId: 'agent-1' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('creates a missing agent skill through write and enforces mounted createMode', async () => {+ const { AgentDocumentVfsError } = await import('./errors');+ mockSkillMount.get.mockRejectedValue(new AgentDocumentVfsError('missing', 'NOT_FOUND'));+ mockSkillMount.create.mockResolvedValue({+ content: '# New',+ name: 'SKILL.md',+ namespace: 'agent',+ path: './lobe/skills/agent/skills/writer/SKILL.md',+ type: 'file',+ });++ const service = new AgentDocumentVfsService(db, userId);+ const ctx = { agentId: 'agent-1', topicId: 'topic-1' };++ await expect(+ service.write('./lobe/skills/agent/skills/writer/SKILL.md', '# New', ctx, {+ createMode: 'must-exist',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ const node = await service.write('./lobe/skills/agent/skills/writer/SKILL.md', '# New', ctx);++ expect(mockSkillMount.create).toHaveBeenCalledWith({+ agentId: 'agent-1',+ content: '# New',+ skillName: 'writer',+ targetNamespace: 'agent',+ topicId: 'topic-1',+ });+ expect(node).toEqual(expect.objectContaining({ id: expect.stringMatching(/^skills:agent:/) }));++ await expect(+ service.write('./lobe/skills/builtin/skills/lobehub/SKILL.md', 'x', ctx),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ mockSkillMount.get.mockResolvedValue({ name: 'SKILL.md', namespace: 'agent', type: 'file' });+ await expect(+ service.write('./lobe/skills/agent/skills/writer/SKILL.md', 'x', ctx, {+ createMode: 'always-new',+ }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ });+});diff --git a/apps/server/src/services/agentDocumentVfs/mountedSkills.ts b/apps/server/src/services/agentDocumentVfs/mountedSkills.tsnew file mode 100644index 00000000000..7a458c0e3f2--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/mountedSkills.ts@@ -0,0 +1,78 @@+import type { AgentDocumentVfsDeps } from './deps';+import { AgentDocumentVfsError } from './errors';+import { getUnifiedSkillNamespaceRootPath } from './mounts/skills/path';+import type { SkillMountNode } from './mounts/skills/types';+import { toMountedStats } from './nodes';+import { inferMountedSkillIdentity, resolveWritableMountedPath } from './skillPaths';+import type {+ AgentDocumentStats,+ AgentDocumentVfsContext,+ AgentDocumentWriteOptions,+} from './types';++export async function writeMountedSkill(+ deps: AgentDocumentVfsDeps,+ path: string,+ content: string,+ ctx: AgentDocumentVfsContext,+ createMode: NonNullable<AgentDocumentWriteOptions['createMode']>,+): Promise<AgentDocumentStats> {+ const existing = await deps.skillMount+ .get({+ agentId: ctx.agentId,+ path,+ topicId: ctx.topicId,+ })+ .catch((error) => {+ if (error instanceof AgentDocumentVfsError && error.code === 'NOT_FOUND') return undefined;+ throw error;+ });++ if (!existing && createMode === 'must-exist') {+ throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');+ }++ if (existing && createMode === 'always-new') {+ throw new AgentDocumentVfsError(`Path already exists: ${path}`, 'CONFLICT');+ }++ let nextNode: SkillMountNode;++ if (existing) {+ nextNode = await deps.skillMount.update({+ agentId: ctx.agentId,+ content,+ path,+ topicId: ctx.topicId,+ });+ } else {+ const { namespace, skillName } = inferMountedSkillIdentity(path);+ nextNode = await deps.skillMount.create({+ agentId: ctx.agentId,+ content,+ skillName,+ targetNamespace: namespace,+ topicId: ctx.topicId,+ });+ }++ return toMountedStats(nextNode);+}++export async function deleteMountedSkill(+ deps: AgentDocumentVfsDeps,+ path: string,+ ctx: AgentDocumentVfsContext,+) {+ const { namespace, skillName } = inferMountedSkillIdentity(resolveWritableMountedPath(path));++ if (namespace !== 'agent') {+ throw new AgentDocumentVfsError(`Path is read-only: ${path}`, 'FORBIDDEN');+ }++ await deps.skillMount.delete({+ agentId: ctx.agentId,+ path: `${getUnifiedSkillNamespaceRootPath(namespace)}/${skillName}/SKILL.md`,+ topicId: ctx.topicId,+ });+}diff --git a/apps/server/src/services/agentDocumentVfs/nodes.ts b/apps/server/src/services/agentDocumentVfs/nodes.tsnew file mode 100644index 00000000000..a641f9acbce--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/nodes.ts@@ -0,0 +1,139 @@+import type { AgentDocument } from '@/database/models/agentDocuments';+import { AgentAccess } from '@/database/models/agentDocuments';+import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';++import { getAgentDocumentContentType } from '../agentDocuments/contentFormat';+import { getUnifiedSkillNamespaceRootPath } from './mounts/skills/path';+import type { SkillMountNode } from './mounts/skills/types';+import { LOBE_PATH, LOBE_SKILLS_PATH } from './paths';+import {+ buildSkillMountInfo,+ getSkillNamespaceCollectionParent,+ getSkillNamespaceDirectory,+ resolveSkillMountSource,+ skillNodeToMode,+} from './skillPaths';+import type { AgentDocumentNode, AgentDocumentStats } from './types';++const SYNTHETIC_DIRECTORY_MODE = AgentAccess.LIST | AgentAccess.READ;++export function toOrdinaryNode(doc: AgentDocument, path: string): AgentDocumentNode {+ return {+ agentDocumentId: doc.id,+ createdAt: doc.createdAt,+ documentId: doc.documentId,+ id: doc.id,+ mode: doc.accessSelf,+ mount: {+ driver: 'agent-documents',+ source: 'documents',+ },+ name: doc.filename,+ path,+ size: doc.content.length,+ type: doc.fileType === DOCUMENT_FOLDER_TYPE ? 'directory' : 'file',+ updatedAt: doc.updatedAt,+ };+}++export function toOrdinaryStats(doc: AgentDocument, path: string): AgentDocumentStats {+ return {+ ...toOrdinaryNode(doc, path),+ contentType:+ doc.fileType === DOCUMENT_FOLDER_TYPE ? undefined : getAgentDocumentContentType(doc),+ deleteReason: doc.deleteReason,+ deletedAt: doc.deletedAt,+ metadata: doc.metadata ?? undefined,+ };+}++export function toMountedNode(node: SkillMountNode): AgentDocumentNode {+ return {+ id: `skills:${node.namespace}:${node.path}`,+ mode: skillNodeToMode(node),+ mount: {+ driver: 'skills',+ namespace: node.namespace,+ source: resolveSkillMountSource(node.namespace),+ },+ name: node.name,+ path: node.path,+ size: node.size ?? (node.type === 'file' ? node.content?.length : undefined),+ type: node.type,+ };+}++export function toMountedStats(node: SkillMountNode): AgentDocumentStats {+ return {+ ...toMountedNode(node),+ contentType: node.contentType,+ };+}++export function createSyntheticDirectoryNode(path: string, name: string): AgentDocumentNode {+ return {+ id: `synthetic:${path}`,+ mode: SYNTHETIC_DIRECTORY_MODE,+ mount: {+ driver: 'synthetic',+ source: 'virtual',+ },+ name,+ path,+ type: 'directory',+ };+}++export function getSyntheticNode(path: string): AgentDocumentStats | undefined {+ if (path === './') return { ...createSyntheticDirectoryNode('./', '') };+ if (path === LOBE_PATH) return { ...createSyntheticDirectoryNode(LOBE_PATH, 'lobe') };+ if (path === LOBE_SKILLS_PATH) {+ return { ...createSyntheticDirectoryNode(LOBE_SKILLS_PATH, 'skills') };+ }++ const namespace = getSkillNamespaceDirectory(path);++ if (namespace) {+ const name = path.split('/').at(-1)!;+ return {+ ...createSyntheticDirectoryNode(path, name),+ mount: buildSkillMountInfo(namespace),+ };+ }++ return undefined;+}++export function listSyntheticChildren(path: string): AgentDocumentNode[] | undefined {+ if (path === LOBE_PATH) {+ return [createSyntheticDirectoryNode(LOBE_SKILLS_PATH, 'skills')];+ }++ if (path === LOBE_SKILLS_PATH) {+ return [+ createSyntheticDirectoryNode('./lobe/skills/builtin', 'builtin'),+ createSyntheticDirectoryNode('./lobe/skills/installed', 'installed'),+ createSyntheticDirectoryNode('./lobe/skills/agent', 'agent'),+ ];+ }++ if (path === './lobe/skills/installed') {+ return [+ createSyntheticDirectoryNode('./lobe/skills/installed/all', 'all'),+ createSyntheticDirectoryNode('./lobe/skills/installed/active', 'active'),+ ];+ }++ const namespace = getSkillNamespaceCollectionParent(path);++ if (namespace) {+ return [+ {+ ...createSyntheticDirectoryNode(getUnifiedSkillNamespaceRootPath(namespace), 'skills'),+ mount: buildSkillMountInfo(namespace),+ },+ ];+ }++ return undefined;+}diff --git a/apps/server/src/services/agentDocumentVfs/ordinaryTree.ts b/apps/server/src/services/agentDocumentVfs/ordinaryTree.tsnew file mode 100644index 00000000000..f0e84334582--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/ordinaryTree.ts@@ -0,0 +1,156 @@+import type { AgentDocument } from '@/database/models/agentDocuments';+import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';++import type { AgentDocumentVfsDeps } from './deps';+import { toOrdinaryNode } from './nodes';+import { applyListLimit, buildOrdinaryPath, splitAgentDocumentPath } from './paths';+import type { AgentDocumentListOptions, AgentDocumentNode } from './types';++const compareAgentDocumentAge = (left: AgentDocument, right: AgentDocument) => {+ const leftCreatedAt = left.createdAt?.getTime?.() ?? 0;+ const rightCreatedAt = right.createdAt?.getTime?.() ?? 0;++ if (leftCreatedAt !== rightCreatedAt) return leftCreatedAt - rightCreatedAt;++ return left.id.localeCompare(right.id);+};++export const selectOldestAgentDocument = (documents: AgentDocument[]) =>+ [...documents].sort(compareAgentDocumentAge)[0];++export const selectOldestByFilename = (documents: AgentDocument[]) => {+ const visibleByFilename = new Map<string, AgentDocument>();++ for (const document of [...documents].sort(compareAgentDocumentAge)) {+ if (visibleByFilename.has(document.filename)) continue;+ visibleByFilename.set(document.filename, document);+ }++ return [...visibleByFilename.values()];+};++export async function listOrdinaryNodes(+ deps: AgentDocumentVfsDeps,+ agentId: string,+ parentId: string | null,+ parentPath: string,+ options: AgentDocumentListOptions = {},+): Promise<AgentDocumentNode[]> {+ const docs = await deps.agentDocumentModel.listByParent(agentId, parentId, {+ cursor: options.cursor,+ });+ const visibleDocs = selectOldestByFilename(docs);+ return applyListLimit(+ visibleDocs.map((doc) => toOrdinaryNode(doc, buildOrdinaryPath(parentPath, doc.filename))),+ options,+ );+}++export async function resolveOrdinaryPath(+ deps: AgentDocumentVfsDeps,+ path: string,+ agentId: string,+): Promise<AgentDocument | undefined> {+ return resolveOrdinaryPathWithOptions(deps, path, agentId);+}++export async function resolveOrdinaryPathWithOptions(+ deps: AgentDocumentVfsDeps,+ path: string,+ agentId: string,+ options?: { includeDeleted?: boolean },+): Promise<AgentDocument | undefined> {+ if (path === './') return undefined;++ const segments = splitAgentDocumentPath(path);+ let parentId: string | null = null;+ let current: AgentDocument | undefined;++ for (const segment of segments) {+ const candidates = await deps.agentDocumentModel.listByParentAndFilename(+ agentId,+ parentId,+ segment,+ {+ ...options,+ },+ );++ current = selectOldestAgentDocument(candidates);+ if (!current) return undefined;+ parentId = current.documentId;+ }++ return current;+}++export async function collectOrdinarySubtree(+ deps: AgentDocumentVfsDeps,+ root: AgentDocument,+ agentId: string,+ includeDeleted: boolean,+): Promise<AgentDocument[]> {+ const nodes = [root];++ if (root.fileType !== DOCUMENT_FOLDER_TYPE) return nodes;++ const queue: AgentDocument[] = [root];++ while (queue.length > 0) {+ const current = queue.shift()!;+ const children = await deps.agentDocumentModel.listByParent(agentId, current.documentId, {+ includeDeleted,+ });++ for (const child of children) {+ nodes.push(child);+ if (child.fileType === DOCUMENT_FOLDER_TYPE) {+ queue.push(child);+ }+ }+ }++ return nodes;+}++export async function collectDeletedAncestors(+ deps: AgentDocumentVfsDeps,+ node: AgentDocument,+ agentId: string,+): Promise<AgentDocument[]> {+ const ancestors: AgentDocument[] = [];+ let parentId = node.parentId;++ while (parentId) {+ const parent = await deps.agentDocumentModel.findByDocumentId(agentId, parentId, {+ includeDeleted: true,+ });++ if (!parent) break;+ ancestors.push(parent);+ parentId = parent.parentId;+ }++ return ancestors;+}++export async function buildOrdinaryPathFromNode(+ deps: AgentDocumentVfsDeps,+ node: AgentDocument,+ agentId: string,+): Promise<string> {+ const segments = [node.filename];+ let parentId = node.parentId;++ while (parentId) {+ const parent = await deps.agentDocumentModel.findByDocumentId(agentId, parentId, {+ includeDeleted: true,+ });++ if (!parent) break;+ segments.unshift(parent.filename);+ parentId = parent.parentId;+ }++ return `./${segments.join('/')}`;+}diff --git a/apps/server/src/services/agentDocumentVfs/ordinaryWrites.ts b/apps/server/src/services/agentDocumentVfs/ordinaryWrites.tsnew file mode 100644index 00000000000..4c6ef1f60c7--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/ordinaryWrites.ts@@ -0,0 +1,195 @@+import { buildDocumentFilename } from '@/database/models/agentDocuments';+import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';++import { RAW_TEXT_DOCUMENT_FILE_TYPE } from '../agentDocuments/contentFormat';+import { createAgentMarkdownSnapshot } from '../agentDocuments/headlessEditor';+import type { AgentDocumentVfsDeps } from './deps';+import { AgentDocumentVfsError } from './errors';+import { toOrdinaryStats } from './nodes';+import { resolveOrdinaryPath } from './ordinaryTree';+import {+ buildOrdinaryPath,+ LOBE_PATH,+ normalizeOrdinaryDocumentPath,+ splitAgentDocumentPath,+} from './paths';+import type {+ AgentDocumentCopyOptions,+ AgentDocumentStats,+ AgentDocumentVfsContext,+ AgentDocumentWriteOptions,+} from './types';++export async function writeOrdinaryDocument(+ deps: AgentDocumentVfsDeps,+ path: string,+ content: string,+ ctx: AgentDocumentVfsContext,+ createMode: NonNullable<AgentDocumentWriteOptions['createMode']>,+ contentFormat: NonNullable<AgentDocumentWriteOptions['contentFormat']>,+): Promise<AgentDocumentStats> {+ if (path === './' || path === LOBE_PATH || path.startsWith(`${LOBE_PATH}/`)) {+ throw new AgentDocumentVfsError(`Cannot write reserved path: ${path}`, 'BAD_REQUEST');+ }++ const exactExisting = await resolveOrdinaryPath(deps, path, ctx.agentId);+ const writablePath = exactExisting ? path : normalizeOrdinaryDocumentPath(path);+ const existing = exactExisting ?? (await resolveOrdinaryPath(deps, writablePath, ctx.agentId));++ if (existing) {+ if (existing.fileType === DOCUMENT_FOLDER_TYPE) {+ throw new AgentDocumentVfsError(`Path is not a file: ${writablePath}`, 'BAD_REQUEST');+ }++ if (createMode === 'always-new') {+ throw new AgentDocumentVfsError(`Path already exists: ${writablePath}`, 'BAD_REQUEST');+ }++ if (contentFormat === 'raw') {+ await deps.agentDocumentModel.update(existing.id, {+ content,+ editorData: null,+ fileType: RAW_TEXT_DOCUMENT_FILE_TYPE,+ });+ } else {+ const snapshot = await createAgentMarkdownSnapshot(content);+ await deps.agentDocumentModel.update(existing.id, {+ content: snapshot.content,+ editorData: snapshot.editorData,+ });+ }++ const updated = await resolveOrdinaryPath(deps, writablePath, ctx.agentId);++ if (!updated) {+ throw new AgentDocumentVfsError(+ `Failed to reload updated path: ${writablePath}`,+ 'BAD_REQUEST',+ );+ }++ return toOrdinaryStats(updated, writablePath);+ }++ if (createMode === 'must-exist') {+ throw new AgentDocumentVfsError(`Path not found: ${writablePath}`, 'NOT_FOUND');+ }++ const segments = splitAgentDocumentPath(writablePath);+ const filename = segments.at(-1);++ if (!filename) {+ throw new AgentDocumentVfsError(`Invalid VFS path: ${writablePath}`, 'BAD_REQUEST');+ }++ const parentPath = segments.length === 1 ? './' : `./${segments.slice(0, -1).join('/')}`;+ const parentNode =+ parentPath === './' ? undefined : await resolveOrdinaryPath(deps, parentPath, ctx.agentId);++ if (parentPath !== './' && !parentNode) {+ throw new AgentDocumentVfsError(`Parent path not found: ${parentPath}`, 'BAD_REQUEST');+ }++ if (parentNode && parentNode.fileType !== DOCUMENT_FOLDER_TYPE) {+ throw new AgentDocumentVfsError(`Parent path is not a directory: ${parentPath}`, 'BAD_REQUEST');+ }++ const normalizedFilename = buildDocumentFilename(filename);+ if (contentFormat === 'raw') {+ const created = await deps.agentDocumentModel.create(ctx.agentId, normalizedFilename, content, {+ fileType: RAW_TEXT_DOCUMENT_FILE_TYPE,+ parentId: parentNode?.documentId ?? null,+ title: normalizedFilename,+ });++ return toOrdinaryStats(created, buildOrdinaryPath(parentPath, normalizedFilename));+ }++ const snapshot = await createAgentMarkdownSnapshot(content);+ const created = await deps.agentDocumentModel.create(+ ctx.agentId,+ normalizedFilename,+ snapshot.content,+ {+ editorData: snapshot.editorData,+ parentId: parentNode?.documentId ?? null,+ title: normalizedFilename,+ },+ );++ return toOrdinaryStats(created, buildOrdinaryPath(parentPath, normalizedFilename));+}++export async function renameOrdinaryPath(+ deps: AgentDocumentVfsDeps,+ sourcePath: string,+ destinationPath: string,+ ctx: AgentDocumentVfsContext,+ options: AgentDocumentCopyOptions,+ deletePath: (path: string, ctx: AgentDocumentVfsContext) => Promise<void>,+): Promise<AgentDocumentStats> {+ if (+ destinationPath === './' ||+ destinationPath === LOBE_PATH ||+ destinationPath.startsWith(`${LOBE_PATH}/`)+ ) {+ throw new AgentDocumentVfsError(+ `Cannot rename to reserved path: ${destinationPath}`,+ 'BAD_REQUEST',+ );+ }++ const sourceNode = await resolveOrdinaryPath(deps, sourcePath, ctx.agentId);++ if (!sourceNode) {+ throw new AgentDocumentVfsError(`Path not found: ${sourcePath}`, 'NOT_FOUND');+ }++ const existingDestination = await resolveOrdinaryPath(deps, destinationPath, ctx.agentId);++ if (existingDestination) {+ if (!options.overwrite) {+ throw new AgentDocumentVfsError(`Path already exists: ${destinationPath}`, 'BAD_REQUEST');+ }++ if (existingDestination.fileType === DOCUMENT_FOLDER_TYPE) {+ throw new AgentDocumentVfsError(+ `Cannot overwrite directory path: ${destinationPath}`,+ 'BAD_REQUEST',+ );+ }++ await deletePath(destinationPath, ctx);+ }++ const segments = splitAgentDocumentPath(destinationPath);+ const filename = segments.at(-1);++ if (!filename) {+ throw new AgentDocumentVfsError(`Invalid VFS path: ${destinationPath}`, 'BAD_REQUEST');+ }++ const parentPath = segments.length === 1 ? './' : `./${segments.slice(0, -1).join('/')}`;+ const parentNode =+ parentPath === './' ? undefined : await resolveOrdinaryPath(deps, parentPath, ctx.agentId);++ if (parentPath !== './' && !parentNode) {+ throw new AgentDocumentVfsError(`Parent path not found: ${parentPath}`, 'BAD_REQUEST');+ }++ if (parentNode && parentNode.fileType !== DOCUMENT_FOLDER_TYPE) {+ throw new AgentDocumentVfsError(`Parent path is not a directory: ${parentPath}`, 'BAD_REQUEST');+ }++ const parentId = parentNode?.documentId ?? null;+ const moved = await deps.agentDocumentModel.movePath(sourceNode.id, {+ filename,+ parentId,+ });++ if (!moved) {+ throw new AgentDocumentVfsError(`Failed to rename path: ${sourcePath}`, 'BAD_REQUEST');+ }++ return toOrdinaryStats(moved, destinationPath);+}diff --git a/apps/server/src/services/agentDocumentVfs/paths.ts b/apps/server/src/services/agentDocumentVfs/paths.tsnew file mode 100644index 00000000000..a71aabfd383--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/paths.ts@@ -0,0 +1,103 @@+import { buildDocumentFilename } from '@/database/models/agentDocuments';++import { AgentDocumentVfsError } from './errors';+import type {+ AgentDocumentListOptions,+ AgentDocumentReadResult,+ AgentDocumentStats,+} from './types';++export const LOBE_PATH = './lobe';+export const LOBE_SKILLS_PATH = './lobe/skills';+/**+ * Default cap for VFS directory reads while the public API still returns arrays.+ * Keep this near path constants because it is part of the VFS surface, not storage policy.+ */+export const DEFAULT_LIST_LIMIT = 100;+/**+ * Maximum one-call VFS directory read size.+ * Prevents accidental wide-directory materialization from CLI or tool callers.+ */+export const MAX_LIST_LIMIT = 500;++export const normalizeAgentDocumentPath = (path: string) => {+ const raw = path.trim();+ const withDot =+ raw === '/' ? './' : raw.startsWith('./') ? raw : raw.startsWith('/') ? `.${raw}` : `./${raw}`;+ const collapsed = withDot.replaceAll(/\/+/g, '/');++ if (collapsed.includes('/./') || collapsed.includes('/../') || collapsed.endsWith('/..')) {+ throw new AgentDocumentVfsError(`Invalid VFS path: ${path}`, 'BAD_REQUEST');+ }++ const normalized = collapsed === './' ? './' : collapsed.replace(/\/$/, '');+ return normalized;+};++export const splitAgentDocumentPath = (path: string) =>+ path.replace(/^\.\//, '').split('/').filter(Boolean);++export const buildOrdinaryPath = (parentPath: string, filename: string) =>+ parentPath === './' ? `./${filename}` : `${parentPath}/${filename}`;++export const normalizeOrdinaryDocumentPath = (path: string): string => {+ const segments = splitAgentDocumentPath(path);+ const filename = segments.at(-1);+ if (!filename) return path;++ const parentPath = segments.length === 1 ? './' : `./${segments.slice(0, -1).join('/')}`;+ const normalizedFilename = buildDocumentFilename(filename);+ return buildOrdinaryPath(parentPath, normalizedFilename);+};++export const normalizeListLimit = (limit?: number) => {+ if (limit === undefined) return DEFAULT_LIST_LIMIT;++ // Clamp caller-provided limits so path APIs stay bounded even when invoked by tools.+ return Math.min(Math.max(Math.trunc(limit), 1), MAX_LIST_LIMIT);+};++export const applyListLimit = <T>(items: T[], options: AgentDocumentListOptions) =>+ items.slice(0, normalizeListLimit(options.limit));++export const isDescendantPath = (parentPath: string, childPath: string) =>+ childPath !== parentPath && childPath.startsWith(`${parentPath}/`);++export const assertNotSelfReferentialCopy = (+ sourcePath: string,+ destinationPath: string,+ sourceNode: AgentDocumentStats,+) => {+ if (sourcePath === destinationPath) {+ throw new AgentDocumentVfsError(`Cannot copy path onto itself: ${sourcePath}`, 'BAD_REQUEST');+ }++ if (sourceNode.type === 'directory' && isDescendantPath(sourcePath, destinationPath)) {+ throw new AgentDocumentVfsError(+ `Cannot copy directory into its own subtree: ${sourcePath} -> ${destinationPath}`,+ 'BAD_REQUEST',+ );+ }+};++export const sliceReadContent = (+ content: string,+ loc?: [number, number],+): Omit<AgentDocumentReadResult, 'contentType' | 'path'> => {+ const lines = content.split('\n');+ const totalLineCount = lines.length;+ const totalCharCount = content.length;+ const actualLoc: [number, number] = loc ?? [0, totalLineCount];+ const [startLine, endLine] = actualLoc;+ const selectedLines = lines.slice(startLine, endLine);+ const selectedContent = selectedLines.join('\n');++ return {+ charCount: selectedContent.length,+ content: selectedContent,+ lineCount: selectedLines.length,+ loc: actualLoc,+ totalCharCount,+ totalLineCount,+ };+};diff --git a/apps/server/src/services/agentDocumentVfs/skillPaths.ts b/apps/server/src/services/agentDocumentVfs/skillPaths.tsnew file mode 100644index 00000000000..75dc93b2c06--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/skillPaths.ts@@ -0,0 +1,113 @@+import { AgentAccess } from '@/database/models/agentDocuments';++import { AgentDocumentVfsError } from './errors';+import {+ getUnifiedSkillNamespaceParentPath,+ getUnifiedSkillNamespaceRootPath,+ isUnifiedSkillPath as isSkillPath,+ SKILL_NAMESPACES,+ type SkillNamespace,+} from './mounts/skills/path';+import type { SkillMountNode } from './mounts/skills/types';++export const inferMountedSkillIdentity = (path: string) => {+ for (const namespace of ['agent'] as const) {+ const prefix = getUnifiedSkillNamespaceRootPath(namespace);++ if (path === prefix || !path.startsWith(`${prefix}/`)) continue;++ const relativePath = path.slice(prefix.length + 1);+ const [skillName] = relativePath.split('/');++ if (!skillName) {+ throw new AgentDocumentVfsError(+ `Expected a skill path, but received namespace root: ${path}`,+ 'BAD_REQUEST',+ );+ }++ return { namespace, skillName };+ }++ throw new AgentDocumentVfsError(`Namespace is not writable: ${path}`, 'FORBIDDEN');+};++export const getSkillNamespaceDirectory = (path: string): SkillNamespace | undefined => {+ for (const namespace of SKILL_NAMESPACES) {+ const parentPath = getUnifiedSkillNamespaceParentPath(namespace);+ const rootPath = getUnifiedSkillNamespaceRootPath(namespace);++ if (path === parentPath || path === rootPath) return namespace;+ }++ return undefined;+};++export const getSkillNamespaceCollectionParent = (path: string): SkillNamespace | undefined => {+ for (const namespace of SKILL_NAMESPACES) {+ if (path === getUnifiedSkillNamespaceParentPath(namespace)) return namespace;+ }++ return undefined;+};++export const buildSkillMountInfo = (namespace: SkillNamespace) => ({+ driver: 'skills',+ namespace,+ source: resolveSkillMountSource(namespace),+});++export const resolveSkillMountSource = (namespace: SkillNamespace) => {+ if (namespace === 'builtin') return 'builtin';+ if (namespace === 'installed-active' || namespace === 'installed-all') return 'installed';+ return 'documents';+};++export const SKILL_MOUNT_ACCESS = {+ 'agent': AgentAccess.READ | AgentAccess.LIST | AgentAccess.WRITE | AgentAccess.DELETE,+ 'builtin': AgentAccess.READ | AgentAccess.LIST,+ 'installed-active': AgentAccess.READ | AgentAccess.LIST,+ 'installed-all': AgentAccess.READ | AgentAccess.LIST,+} as const satisfies Record<SkillNamespace, AgentAccess>;++export const skillNodeToMode = (node: SkillMountNode): AgentAccess => {+ return SKILL_MOUNT_ACCESS[node.namespace];+};++export const resolveWritableMountedPath = (path: string) => {+ if (!isSkillPath(path)) return path;++ for (const namespace of ['agent', 'builtin', 'installed-active', 'installed-all'] as const) {+ const prefix = getUnifiedSkillNamespaceRootPath(namespace);++ if (path === prefix) {+ throw new AgentDocumentVfsError(+ `Expected a skill path, but received namespace root: ${path}`,+ 'BAD_REQUEST',+ );+ }++ if (!path.startsWith(`${prefix}/`)) continue;++ const relativePath = path.slice(prefix.length + 1);+ const [skillName, ...rest] = relativePath.split('/');++ if (!skillName) {+ throw new AgentDocumentVfsError(+ `Expected a skill path, but received namespace root: ${path}`,+ 'BAD_REQUEST',+ );+ }++ if (rest.length === 0) {+ return `${prefix}/${skillName}/SKILL.md`;+ }++ return path;+ }++ return path;+};++export const resolveReadablePath = (path: string) =>+ isSkillPath(path) ? resolveWritableMountedPath(path) : path;diff --git a/apps/server/src/services/agentDocumentVfs/testUtils.ts b/apps/server/src/services/agentDocumentVfs/testUtils.tsnew file mode 100644index 00000000000..7b08f11c843--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/testUtils.ts@@ -0,0 +1,58 @@+import { vi } from 'vitest';++import { AgentDocumentModel } from '@/database/models/agentDocuments';+import type { LobeChatDatabase } from '@/database/type';++import { createSkillMount } from './mounts/skills/createSkillMount';++/**+ * Shared fixtures for the `AgentDocumentVfsService` scenario tests.+ *+ * Each test file keeps its own `vi.mock` calls for `@/database/models/agentDocuments`,+ * `./mounts/skills/createSkillMount` and `../file`; these helpers only wire the mocked+ * constructors to the shared mock instances below.+ */+export const db = {} as LobeChatDatabase;+export const userId = 'user-1';++export const mockAgentDocumentModel = {+ create: vi.fn(),+ findByDocumentId: vi.fn(),+ findByIdWithOptions: vi.fn(),+ findByParentAndFilename: vi.fn(),+ listByParentAndFilename: vi.fn(),+ listByParent: vi.fn(),+ listDeletedByAgent: vi.fn(),+ movePath: vi.fn(),+ permanentlyDelete: vi.fn(),+ restore: vi.fn(),+ delete: vi.fn(),+ update: vi.fn(),+};++export const mockSkillMount = {+ create: vi.fn(),+ delete: vi.fn(),+ get: vi.fn(),+ list: vi.fn(),+ update: vi.fn(),+};++/** Resets the shared model and skill-mount mocks; call from each file's `beforeEach`. */+export const resetVfsMocks = () => {+ for (const method of Object.values(mockAgentDocumentModel)) {+ method.mockReset();+ }+ mockAgentDocumentModel.permanentlyDelete.mockResolvedValue([]);+ for (const method of Object.values(mockSkillMount)) {+ method.mockReset();+ }+ (AgentDocumentModel as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {+ return mockAgentDocumentModel;+ });+ (createSkillMount as unknown as ReturnType<typeof vi.fn>).mockReturnValue(mockSkillMount);+ mockAgentDocumentModel.listByParentAndFilename.mockImplementation(async (...args) => {+ const result = await mockAgentDocumentModel.findByParentAndFilename(...args);+ return result ? [result] : [];+ });+};diff --git a/apps/server/src/services/agentDocumentVfs/trash.ts b/apps/server/src/services/agentDocumentVfs/trash.tsnew file mode 100644index 00000000000..5ff8e737ad7--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/trash.ts@@ -0,0 +1,171 @@+import { FileSource } from '@lobechat/types';+import pMap from 'p-map';++import type { AgentDocumentVfsDeps } from './deps';+import { AgentDocumentVfsError } from './errors';+import { toOrdinaryStats } from './nodes';+import {+ buildOrdinaryPathFromNode,+ collectDeletedAncestors,+ collectOrdinarySubtree,+ resolveOrdinaryPath,+} from './ordinaryTree';+import { normalizeAgentDocumentPath } from './paths';+import type { AgentDocumentStats, AgentDocumentTrashEntry, AgentDocumentVfsContext } from './types';++/**+ * Lists agent-scoped trash entries.+ *+ * Use when:+ * - CLI `trash ls` needs a recovery-oriented view+ *+ * Returns:+ * - Flat trash entries with reconstructed paths+ */+export async function listTrash(+ deps: AgentDocumentVfsDeps,+ ctx: AgentDocumentVfsContext,+ path?: string,+): Promise<AgentDocumentTrashEntry[]> {+ const deletedDocs = await deps.agentDocumentModel.listDeletedByAgent(ctx.agentId);+ // Each path reconstruction issues DB reads; cap the fan-out per agent trash size.+ const entries = await pMap(+ deletedDocs,+ async (doc) => {+ const path = await buildOrdinaryPathFromNode(deps, doc, ctx.agentId);+ return {+ ...toOrdinaryStats(doc, path),+ deleteReason: doc.deleteReason,+ deletedAt: doc.deletedAt ?? new Date(0),+ } satisfies AgentDocumentTrashEntry;+ },+ { concurrency: 10 },+ );++ if (!path) return entries;++ const normalizedPath = normalizeAgentDocumentPath(path);+ return entries.filter(+ (entry) => entry.path === normalizedPath || entry.path.startsWith(`${normalizedPath}/`),+ );+}++/**+ * Restores a trash entry back into the live VFS tree.+ *+ * Use when:+ * - CLI `trash restore` needs to reactivate a soft-deleted path+ *+ * Returns:+ * - The restored node state+ */+export async function restoreFromTrash(+ deps: AgentDocumentVfsDeps,+ agentDocumentId: string,+ ctx: AgentDocumentVfsContext,+): Promise<AgentDocumentStats> {+ const root = await deps.agentDocumentModel.findByIdWithOptions(agentDocumentId, {+ includeDeleted: true,+ });++ if (!root?.deletedAt) {+ throw new AgentDocumentVfsError(`Trash entry not found: ${agentDocumentId}`, 'NOT_FOUND');+ }++ const ancestors = await collectDeletedAncestors(deps, root, ctx.agentId);+ const subtree = await collectOrdinarySubtree(deps, root, ctx.agentId, true);++ for (const ancestor of ancestors.reverse()) {+ if (ancestor.deletedAt) {+ await deps.agentDocumentModel.restore(ancestor.id);+ }+ }++ for (const item of subtree) {+ if (item.deletedAt) {+ await deps.agentDocumentModel.restore(item.id);+ }+ }++ const restored = await resolveOrdinaryPath(+ deps,+ await buildOrdinaryPathFromNode(deps, root, ctx.agentId),+ ctx.agentId,+ );++ if (!restored) {+ throw new AgentDocumentVfsError(`Failed to restore path: ${agentDocumentId}`, 'BAD_REQUEST');+ }++ return toOrdinaryStats(restored, await buildOrdinaryPathFromNode(deps, restored, ctx.agentId));+}++/**+ * Permanently removes a trash entry and its subtree.+ *+ * Use when:+ * - CLI `trash rm` should erase recoverable state+ *+ * Returns:+ * - Void+ */+export async function deletePermanently(+ deps: AgentDocumentVfsDeps,+ agentDocumentId: string,+ ctx: AgentDocumentVfsContext,+): Promise<void> {+ const root = await deps.agentDocumentModel.findByIdWithOptions(agentDocumentId, {+ includeDeleted: true,+ });++ if (!root?.deletedAt) {+ throw new AgentDocumentVfsError(`Trash entry not found: ${agentDocumentId}`, 'NOT_FOUND');+ }++ const subtree = await collectOrdinarySubtree(deps, root, ctx.agentId, true);++ for (const item of subtree.reverse()) {+ const fileIds = await deps.agentDocumentModel.permanentlyDelete(item.id);+ for (const fileId of fileIds) {+ await deps.getFileService().removeUnreferencedFile(fileId, FileSource.AgentDocument);+ }+ }+}++export async function restoreFromTrashByPath(+ deps: AgentDocumentVfsDeps,+ path: string,+ ctx: AgentDocumentVfsContext,+): Promise<AgentDocumentStats> {+ const entry = await findTrashEntryByPath(deps, path, ctx);++ if (!entry) {+ throw new AgentDocumentVfsError(`Trash entry not found: ${path}`, 'NOT_FOUND');+ }++ return restoreFromTrash(deps, entry.agentDocumentId!, ctx);+}++export async function deletePermanentlyByPath(+ deps: AgentDocumentVfsDeps,+ path: string,+ ctx: AgentDocumentVfsContext,+): Promise<void> {+ const entry = await findTrashEntryByPath(deps, path, ctx);++ if (!entry) {+ throw new AgentDocumentVfsError(`Trash entry not found: ${path}`, 'NOT_FOUND');+ }++ await deletePermanently(deps, entry.agentDocumentId!, ctx);+}++export async function findTrashEntryByPath(+ deps: AgentDocumentVfsDeps,+ path: string,+ ctx: AgentDocumentVfsContext,+) {+ const normalizedPath = normalizeAgentDocumentPath(path);+ const entries = await listTrash(deps, ctx);+ return entries.find((entry) => entry.path === normalizedPath);+}diff --git a/apps/server/src/services/agentDocumentVfs/types.ts b/apps/server/src/services/agentDocumentVfs/types.tsindex 14a46f12a4e..05cefa85371 100644--- a/apps/server/src/services/agentDocumentVfs/types.ts+++ b/apps/server/src/services/agentDocumentVfs/types.ts@@ -190,3 +190,32 @@ export const isAgentDocumentFile = (export const isAgentDocumentDirectory = (node: Pick<AgentDocumentNode, 'type'>,): node is Pick<AgentDocumentNode, 'type'> & { type: 'directory' } => node.type === 'directory';++/**+ * Agent scope for one VFS call.+ */+export interface AgentDocumentVfsContext {+ agentId: string;+ topicId?: string;+}++export interface AgentDocumentWriteOptions {+ /**+ * Raw writes bypass the Markdown editor snapshot because arbitrary tool or code output may+ * contain markup that the editor legitimately normalizes or discards.+ */+ contentFormat?: 'markdown' | 'raw';+ createMode?: 'always-new' | 'if-missing' | 'must-exist';+}++export interface AgentDocumentMkdirOptions {+ recursive?: boolean;+}++export interface AgentDocumentDeleteOptions {+ recursive?: boolean;+}++export interface AgentDocumentCopyOptions {+ overwrite?: boolean;+}