Skip to content

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

✨ feat(cli,server,database): now agent document can be used as vfs, offer fs compatible output (#14222)

Nekod5511a6af277
diff --git a/apps/cli/e2e/agent-fs-vfs.e2e.test.ts b/apps/cli/e2e/agent-fs-vfs.e2e.test.ts
new file mode 100644
index 00000000000..11a44cae078
--- /dev/null
+++ b/apps/cli/e2e/agent-fs-vfs.e2e.test.ts
@@ -0,0 +1,80 @@
+import { execSync } from 'node:child_process';
+
+import { describe, expect, it } from 'vitest';
+
+/**
+ * Manual E2E coverage for `lh agent space fs` against a real backend.
+ *
+ * Run when:
+ * - A local or remote LobeHub backend is reachable by the CLI
+ * - `AGENT_FS_E2E_AGENT_ID` points at an agent with document access
+ *
+ * Expects:
+ * - The command creates and cleans up a temporary VFS directory
+ * - This suite is skipped unless `AGENT_FS_E2E_AGENT_ID` is set
+ */
+const AGENT_ID = process.env.AGENT_FS_E2E_AGENT_ID;
+const CLI = process.env.LH_CLI_PATH || 'LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts';
+const TIMEOUT = 30_000;
+
+function run(args: string): string {
+ return execSync(`${CLI} ${args}`, {
+ encoding: 'utf8',
+ env: { ...process.env, PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}` },
+ timeout: TIMEOUT,
+ }).trim();
+}
+
+describe.skipIf(!AGENT_ID)('lh agent space fs unified VFS - manual E2E', () => {
+ const testRoot = `agent:/vfs-cli-e2e-${Date.now()}`;
+
+ it('exercises root, mounted namespaces, writes, copy, move, trash, and cleanup', () => {
+ const root = run(`agent space fs ls --agent-id ${AGENT_ID} agent:/`);
+ expect(root).toContain('lobe/');
+
+ const mountedRoot = run(`agent space fs ls --agent-id ${AGENT_ID} agent:/lobe/skills`);
+ expect(mountedRoot).toContain('builtin/');
+ expect(mountedRoot).toContain('agent/');
+
+ try {
+ expect(run(`agent space fs mkdir --agent-id ${AGENT_ID} --parents ${testRoot}`)).toContain(
+ 'created',
+ );
+ expect(
+ run(
+ `agent space fs write --agent-id ${AGENT_ID} --content "# VFS E2E" ${testRoot}/source.md`,
+ ),
+ ).toContain('created');
+ expect(run(`agent space fs cat --agent-id ${AGENT_ID} ${testRoot}/source.md`)).toContain(
+ '# VFS E2E',
+ );
+ expect(
+ run(`agent space fs cp --agent-id ${AGENT_ID} ${testRoot}/source.md ${testRoot}/copied.md`),
+ ).toContain('copied');
+ expect(
+ run(`agent space fs mv --agent-id ${AGENT_ID} ${testRoot}/copied.md ${testRoot}/moved.md`),
+ ).toContain('moved');
+ expect(run(`agent space fs rm --agent-id ${AGENT_ID} --yes ${testRoot}/moved.md`)).toContain(
+ 'deleted',
+ );
+ expect(run(`agent space fs trash ls --agent-id ${AGENT_ID} ${testRoot}`)).toContain(
+ `${testRoot}/moved.md`,
+ );
+ expect(
+ run(`agent space fs trash restore --agent-id ${AGENT_ID} ${testRoot}/moved.md`),
+ ).toContain('restored');
+ } finally {
+ try {
+ run(`agent space fs rm --agent-id ${AGENT_ID} --yes --recursive ${testRoot}`);
+ } catch {
+ // Cleanup is best-effort because earlier assertions may fail before creation.
+ }
+
+ try {
+ run(`agent space fs trash rm --agent-id ${AGENT_ID} --yes --recursive --force ${testRoot}`);
+ } catch {
+ // Cleanup is best-effort because the trash entry may not exist.
+ }
+ }
+ }, 60_000);
+});
diff --git a/apps/cli/package.json b/apps/cli/package.json
index e633a50bb5b..ec4f7bf94c5 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -35,6 +35,7 @@
"@types/node": "^22.13.5",
"@types/ws": "^8.18.1",
"commander": "^13.1.0",
+ "dayjs": "^1.11.19",
"debug": "^4.4.0",
"diff": "^8.0.3",
"fast-glob": "^3.3.3",
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.ts
index 46141c6a1f0..fbbe232067f 100644
--- a/apps/cli/src/commands/agent.test.ts
+++ b/apps/cli/src/commands/agent.test.ts
@@ -23,6 +23,25 @@ const { mockTrpcClient } = vi.hoisted(() => ({
updateAgentConfig: { mutate: vi.fn() },
updateAgentPinned: { mutate: vi.fn() },
},
+ agentDocument: {
+ copyDocumentByPath: { mutate: vi.fn() },
+ deleteDocumentByPath: { mutate: vi.fn() },
+ deleteDocumentPermanentlyByPath: { mutate: vi.fn() },
+ statDocumentByPath: { query: vi.fn() },
+ listDocumentsByPath: { query: vi.fn() },
+ listTrashDocumentsByPath: { query: vi.fn() },
+ mkdirDocumentByPath: { mutate: vi.fn() },
+ readDocumentByPath: { query: vi.fn() },
+ renameDocumentByPath: { mutate: vi.fn() },
+ restoreDocumentFromTrashByPath: { mutate: vi.fn() },
+ writeDocumentByPath: { mutate: vi.fn() },
+ },
+ agentSkills: {
+ createSkill: { mutate: vi.fn() },
+ deleteSkill: { mutate: vi.fn() },
+ promoteSkill: { mutate: vi.fn() },
+ updateSkill: { mutate: vi.fn() },
+ },
aiAgent: {
execAgent: { mutate: vi.fn() },
getOperationStatus: { query: vi.fn() },
@@ -41,6 +60,11 @@ const { mockStreamAgentEvents } = vi.hoisted(() => ({
mockStreamAgentEvents: vi.fn(),
}));
+const { mockReplayAgentEvents, mockStreamAgentEventsViaWebSocket } = vi.hoisted(() => ({
+ mockReplayAgentEvents: vi.fn(),
+ mockStreamAgentEventsViaWebSocket: vi.fn(),
+}));
+
const { mockGetAgentStreamAuthInfo } = vi.hoisted(() => ({
mockGetAgentStreamAuthInfo: vi.fn(),
}));
@@ -49,9 +73,18 @@ const { mockResolveLocalDeviceId } = vi.hoisted(() => ({
mockResolveLocalDeviceId: vi.fn(),
}));
+const { mockReadStdinText } = vi.hoisted(() => ({
+ mockReadStdinText: vi.fn(),
+}));
+
+vi.mock('node:stream/consumers', () => ({ text: mockReadStdinText }));
vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
vi.mock('../api/http', () => ({ getAgentStreamAuthInfo: mockGetAgentStreamAuthInfo }));
-vi.mock('../utils/agentStream', () => ({ streamAgentEvents: mockStreamAgentEvents }));
+vi.mock('../utils/agentStream', () => ({
+ replayAgentEvents: mockReplayAgentEvents,
+ streamAgentEvents: mockStreamAgentEvents,
+ streamAgentEventsViaWebSocket: mockStreamAgentEventsViaWebSocket,
+}));
vi.mock('../utils/device', () => ({ resolveLocalDeviceId: mockResolveLocalDeviceId }));
vi.mock('../utils/logger', () => ({
log: { debug: vi.fn(), error: vi.fn(), heartbeat: vi.fn(), info: vi.fn(), warn: vi.fn() },
@@ -71,12 +104,26 @@ describe('agent command', () => {
serverUrl: 'https://example.com',
});
mockStreamAgentEvents.mockResolvedValue(undefined);
+ mockReplayAgentEvents.mockReset();
+ mockStreamAgentEventsViaWebSocket.mockReset();
+ mockStreamAgentEventsViaWebSocket.mockResolvedValue(undefined);
mockResolveLocalDeviceId.mockReset();
+ mockReadStdinText.mockReset();
for (const method of Object.values(mockTrpcClient.agent)) {
for (const fn of Object.values(method)) {
(fn as ReturnType<typeof vi.fn>).mockReset();
}
}
+ for (const method of Object.values(mockTrpcClient.agentDocument)) {
+ for (const fn of Object.values(method)) {
+ (fn as ReturnType<typeof vi.fn>).mockReset();
+ }
+ }
+ for (const method of Object.values(mockTrpcClient.agentSkills)) {
+ for (const fn of Object.values(method)) {
+ (fn as ReturnType<typeof vi.fn>).mockReset();
+ }
+ }
for (const method of Object.values(mockTrpcClient.aiAgent)) {
for (const fn of Object.values(method)) {
(fn as ReturnType<typeof vi.fn>).mockReset();
@@ -282,7 +329,7 @@ describe('agent command', () => {
});
describe('run', () => {
- it('should exec agent and connect to SSE stream', async () => {
+ it('should exec agent and connect to the gateway WebSocket stream by default', async () => {
mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
operationId: 'op-123',
success: true,
@@ -304,11 +351,45 @@ describe('agent command', () => {
expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
expect.objectContaining({ agentId: 'a1', prompt: 'Hello' }),
);
+ expect(mockStreamAgentEventsViaWebSocket).toHaveBeenCalledWith(
+ expect.objectContaining({
+ gatewayUrl: expect.any(String),
+ json: undefined,
+ operationId: 'op-123',
+ serverUrl: 'https://example.com',
+ token: undefined,
+ tokenType: undefined,
+ verbose: undefined,
+ }),
+ );
+ expect(mockStreamAgentEvents).not.toHaveBeenCalled();
+ });
+
+ it('should fall back to SSE when --sse is provided', async () => {
+ mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
+ operationId: 'op-sse',
+ success: true,
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'run',
+ '--agent-id',
+ 'a1',
+ '--prompt',
+ 'Hello',
+ '--sse',
+ ]);
+
expect(mockStreamAgentEvents).toHaveBeenCalledWith(
- 'https://example.com/api/agent/stream?operationId=op-123',
+ 'https://example.com/api/agent/stream?operationId=op-sse',
expect.objectContaining({ 'Oidc-Auth': 'test-token' }),
expect.objectContaining({ json: undefined, verbose: undefined }),
);
+ expect(mockStreamAgentEventsViaWebSocket).not.toHaveBeenCalled();
});
it('should support --slug option', async () => {
mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
@@ -595,10 +676,8 @@ describe('agent command', () => {
'--json',
]);
- expect(mockStreamAgentEvents).toHaveBeenCalledWith(
- expect.any(String),
- expect.any(Object),
- expect.objectContaining({ json: true }),
+ expect(mockStreamAgentEventsViaWebSocket).toHaveBeenCalledWith(
+ expect.objectContaining({ json: true, operationId: 'op-j' }),
);
});
});
@@ -794,4 +873,542 @@ describe('agent command', () => {
);
});
});
+
+ describe('fs', () => {
+ it('should list VFS entries from the unified agent root alias', async () => {
+ mockTrpcClient.agentDocument.listDocumentsByPath.query.mockResolvedValue([
+ {
+ mode: 8,
+ mount: { driver: 'synthetic', source: 'virtual' },
+ name: 'writer',
+ path: './lobe',
+ type: 'directory',
+ },
+ ]);
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'ls',
+ '--agent-id',
+ 'a1',
+ 'agent:/',
+ '--json',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenCalledWith({
+ agentId: 'a1',
+ cursor: undefined,
+ limit: undefined,
+ path: './',
+ topicId: undefined,
+ });
+ expect(consoleSpy).toHaveBeenCalledWith(
+ JSON.stringify(
+ [
+ {
+ mode: 8,
+ mount: { driver: 'synthetic', source: 'virtual' },
+ name: 'writer',
+ path: './lobe',
+ type: 'directory',
+ },
+ ],
+ null,
+ 2,
+ ),
+ );
+ });
+
+ it('should pass pagination options to VFS ls', async () => {
+ mockTrpcClient.agentDocument.listDocumentsByPath.query.mockResolvedValue([]);
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'ls',
+ '--agent-id',
+ 'a1',
+ '--cursor',
+ '100',
+ '--limit',
+ '25',
+ 'agent:/notes',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenCalledWith({
+ agentId: 'a1',
+ cursor: '100',
+ limit: 25,
+ path: './notes',
+ topicId: undefined,
+ });
+ });
+
+ it('should print unix-like long listings with ls -la', async () => {
+ mockTrpcClient.agentDocument.listDocumentsByPath.query.mockResolvedValue([
+ {
+ mode: 14,
+ name: '.config',
+ path: './notes/.config',
+ size: 0,
+ type: 'directory',
+ updatedAt: '2026-04-27T07:18:00',
+ },
+ {
+ mode: 6,
+ name: 'SOUL.md',
+ path: './notes/SOUL.md',
+ size: 399,
+ type: 'file',
+ updatedAt: '2026-04-27T07:19:00',
+ },
+ ]);
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'ls',
+ '-la',
+ '--agent-id',
+ 'a1',
+ 'agent:/notes',
+ ]);
+
+ expect(consoleSpy).toHaveBeenNthCalledWith(1, 'total 1');
+ expect(consoleSpy).toHaveBeenNthCalledWith(
+ 2,
+ expect.stringMatching(/^dr-x------ {2}1 agent {2}agent {4}0 --- -- --:-- \.$/),
+ );
+ expect(consoleSpy).toHaveBeenNthCalledWith(
+ 3,
+ expect.stringMatching(/^dr-x------ {2}1 agent {2}agent {4}0 --- -- --:-- \.\.$/),
+ );
+ expect(consoleSpy).toHaveBeenNthCalledWith(
+ 4,
+ expect.stringMatching(/^drwx------ {2}1 agent {2}agent {4}0 Apr 27 07:18 \.config\/$/),
+ );
+ expect(consoleSpy).toHaveBeenNthCalledWith(
+ 5,
+ expect.stringMatching(/^-rw------- {2}1 agent {2}agent {2}399 Apr 27 07:19 SOUL\.md$/),
+ );
+ });
+
+ it('should expose VFS commands through agent space fs', async () => {
+ mockTrpcClient.agentDocument.listDocumentsByPath.query.mockResolvedValue([]);
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'ls',
+ '--agent-id',
+ 'a1',
+ 'agent:/notes',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenCalledWith({
+ agentId: 'a1',
+ cursor: undefined,
+ limit: undefined,
+ path: './notes',
+ topicId: undefined,
+ });
+ });
+
+ it('should collect tree traversal warnings instead of failing the whole tree', async () => {
+ mockTrpcClient.agentDocument.listDocumentsByPath.query
+ .mockResolvedValueOnce([
+ {
+ mode: 8,
+ name: 'agent-topic',
+ path: './lobe/skills/agent-topic',
+ type: 'directory',
+ },
+ ])
+ .mockRejectedValueOnce(new Error('Topic ID is required for the agent-topic namespace'));
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'tree',
+ '--agent-id',
+ 'a1',
+ 'agent:/lobe/skills',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenNthCalledWith(1, {
+ agentId: 'a1',
+ path: './lobe/skills',
+ topicId: undefined,
+ });
+ expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenNthCalledWith(2, {
+ agentId: 'a1',
+ path: './lobe/skills/agent-topic',
+ topicId: undefined,
+ });
+ expect(log.warn).toHaveBeenCalledWith(
+ './lobe/skills/agent-topic: Topic ID is required for the agent-topic namespace',
+ );
+ });
+
+ it('should read SKILL.md when cat targets a skill directory alias', async () => {
+ const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ mockTrpcClient.agentDocument.statDocumentByPath.query.mockResolvedValue({
+ content: '# Writer',
+ mode: 2,
+ mount: { driver: 'skills', namespace: 'builtin', source: 'builtin' },
+ name: 'SKILL.md',
+ path: './lobe/skills/builtin/skills/writer/SKILL.md',
+ type: 'file',
+ });
+ mockTrpcClient.agentDocument.readDocumentByPath.query.mockResolvedValue({
+ content: '# Writer',
+ contentType: 'text/markdown',
+ path: './lobe/skills/builtin/skills/writer/SKILL.md',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'cat',
+ '--agent-id',
+ 'a1',
+ 'builtin:/writer',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.statDocumentByPath.query).toHaveBeenCalledWith({
+ agentId: 'a1',
+ path: './lobe/skills/builtin/skills/writer/SKILL.md',
+ topicId: undefined,
+ });
+ expect(mockTrpcClient.agentDocument.readDocumentByPath.query).toHaveBeenCalledWith({
+ agentId: 'a1',
+ path: './lobe/skills/builtin/skills/writer/SKILL.md',
+ topicId: undefined,
+ });
+ expect(stdoutSpy).toHaveBeenCalledWith('# Writer');
+ stdoutSpy.mockRestore();
+ });
+
+ it('should create a writable skill through touch when the path does not exist', async () => {
+ mockTrpcClient.agentDocument.statDocumentByPath.query.mockRejectedValue({
+ data: { code: 'NOT_FOUND' },
+ });
+ mockTrpcClient.agentDocument.writeDocumentByPath.mutate.mockResolvedValue({
+ path: './lobe/skills/agent/skills/writer/SKILL.md',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'touch',
+ '--agent-id',
+ 'a1',
+ 'skills:/writer',
+ '--content',
+ '# Writer',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.writeDocumentByPath.mutate).toHaveBeenCalledWith({
+ agentId: 'a1',
+ content: '# Writer',
+ createMode: 'if-missing',
+ path: './lobe/skills/agent/skills/writer',
+ topicId: undefined,
+ });
+ });
+
+ it('should read write content from stdin when no content option is provided', async () => {
+ const stdinDescriptor = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
+ Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: false });
+ mockReadStdinText.mockResolvedValue('# Piped Content');
+ mockTrpcClient.agentDocument.statDocumentByPath.query.mockRejectedValue({
+ data: { code: 'NOT_FOUND' },
+ });
+ mockTrpcClient.agentDocument.writeDocumentByPath.mutate.mockResolvedValue({
+ path: './notes/piped.md',
+ });
+
+ try {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'write',
+ '--agent-id',
+ 'a1',
+ 'agent:/notes/piped.md',
+ ]);
+
+ expect(mockReadStdinText).toHaveBeenCalledWith(process.stdin);
+ expect(mockTrpcClient.agentDocument.writeDocumentByPath.mutate).toHaveBeenCalledWith({
+ agentId: 'a1',
+ content: '# Piped Content',
+ createMode: 'if-missing',
+ path: './notes/piped.md',
+ topicId: undefined,
+ });
+ } finally {
+ if (stdinDescriptor) {
+ Object.defineProperty(process.stdin, 'isTTY', stdinDescriptor);
+ }
+ }
+ });
+
+ it('should create directories through the generic mkdir path API', async () => {
+ mockTrpcClient.agentDocument.mkdirDocumentByPath.mutate.mockResolvedValue({
+ path: './notes/archive',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'mkdir',
+ '--agent-id',
+ 'a1',
+ '--parents',
+ 'agent:/notes/archive',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.mkdirDocumentByPath.mutate).toHaveBeenCalledWith({
+ agentId: 'a1',
+ path: './notes/archive',
+ recursive: true,
+ topicId: undefined,
+ });
+ });
+
+ it('should stat unified root paths', async () => {
+ mockTrpcClient.agentDocument.statDocumentByPath.query.mockResolvedValue({
+ mode: 8,
+ name: 'lobe',
+ path: './lobe',
+ type: 'directory',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'stat',
+ '--agent-id',
+ 'a1',
+ 'agent:/lobe',
+ '--json',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.statDocumentByPath.query).toHaveBeenCalledWith({
+ agentId: 'a1',
+ path: './lobe',
+ topicId: undefined,
+ });
+ });
+
+ it('should copy paths through the generic copyDocumentByPath API', async () => {
+ mockTrpcClient.agentDocument.copyDocumentByPath.mutate.mockResolvedValue({
+ path: './notes/published.md',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'cp',
+ '--agent-id',
+ 'a1',
+ '--force',
+ 'agent:/notes/draft.md',
+ 'agent:/notes/published.md',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.copyDocumentByPath.mutate).toHaveBeenCalledWith({
+ agentId: 'a1',
+ force: true,
+ fromPath: './notes/draft.md',
+ toPath: './notes/published.md',
+ topicId: undefined,
+ });
+ });
+
+ it('should rename paths through the generic renameDocumentByPath API', async () => {
+ mockTrpcClient.agentDocument.renameDocumentByPath.mutate.mockResolvedValue({
+ path: './notes/final.md',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'mv',
+ '--agent-id',
+ 'a1',
+ 'agent:/notes/draft.md',
+ 'agent:/notes/final.md',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.renameDocumentByPath.mutate).toHaveBeenCalledWith({
+ agentId: 'a1',
+ force: undefined,
+ fromPath: './notes/draft.md',
+ toPath: './notes/final.md',
+ topicId: undefined,
+ });
+ });
+
+ it('should soft-delete paths through the generic deleteDocumentByPath API', async () => {
+ mockTrpcClient.agentDocument.deleteDocumentByPath.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'rm',
+ '--agent-id',
+ 'a1',
+ '--yes',
+ '--recursive',
+ 'agent:/notes',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.deleteDocumentByPath.mutate).toHaveBeenCalledWith({
+ agentId: 'a1',
+ force: undefined,
+ path: './notes',
+ recursive: true,
+ topicId: undefined,
+ });
+ });
+
+ it('should list trash through the generic trash path API', async () => {
+ mockTrpcClient.agentDocument.listTrashDocumentsByPath.query.mockResolvedValue([
+ { path: './notes/deleted.md' },
+ ]);
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'trash',
+ 'ls',
+ '--agent-id',
+ 'a1',
+ 'agent:/notes',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.listTrashDocumentsByPath.query).toHaveBeenCalledWith({
+ agentId: 'a1',
+ path: './notes',
+ topicId: undefined,
+ });
+ expect(consoleSpy).toHaveBeenCalledWith('agent:/notes/deleted.md');
+ });
+
+ it('should restore trash entries through the generic trash restore API', async () => {
+ mockTrpcClient.agentDocument.restoreDocumentFromTrashByPath.mutate.mockResolvedValue({
+ path: './notes/deleted.md',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'trash',
+ 'restore',
+ '--agent-id',
+ 'a1',
+ 'agent:/notes/deleted.md',
+ ]);
+
+ expect(
+ mockTrpcClient.agentDocument.restoreDocumentFromTrashByPath.mutate,
+ ).toHaveBeenCalledWith({
+ agentId: 'a1',
+ path: './notes/deleted.md',
+ topicId: undefined,
+ });
+ });
+
+ it('should permanently delete trash entries through the generic trash rm API', async () => {
+ mockTrpcClient.agentDocument.deleteDocumentPermanentlyByPath.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'space',
+ 'fs',
+ 'trash',
+ 'rm',
+ '--agent-id',
+ 'a1',
+ '--yes',
+ '--force',
+ 'agent:/notes/deleted.md',
+ ]);
+
+ expect(
+ mockTrpcClient.agentDocument.deleteDocumentPermanentlyByPath.mutate,
+ ).toHaveBeenCalledWith({
+ agentId: 'a1',
+ force: true,
+ path: './notes/deleted.md',
+ recursive: undefined,
+ topicId: undefined,
+ });
+ });
+ });
});
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index c902a52bc97..1902d1b72f0 100644
--- a/apps/cli/src/commands/agent.ts
+++ b/apps/cli/src/commands/agent.ts
@@ -14,33 +14,12 @@ import {
import { resolveLocalDeviceId } from '../utils/device';
import { confirm, outputJson, printTable, truncate } from '../utils/format';
import { log, setVerbose } from '../utils/logger';
-
-/**
- * Resolve an agent identifier (agentId or slug) to a concrete agentId.
- * When a slug is provided, uses getBuiltinAgent to look up the agent.
- */
-async function resolveAgentId(
- client: any,
- opts: { agentId?: string; slug?: string },
-): Promise<string> {
- if (opts.agentId) return opts.agentId;
-
- if (opts.slug) {
- const agent = await client.agent.getBuiltinAgent.query({ slug: opts.slug });
- if (!agent) {
- log.error(`Agent not found for slug: ${opts.slug}`);
- process.exit(1);
- }
- return (agent as any).id || (agent as any).agentId;
- }
-
- log.error('Either <agentId> or --slug is required.');
- process.exit(1);
- return ''; // unreachable
-}
+import { resolveAgentId } from './agent/resolveAgentId';
+import { registerAgentSpaceFsCommand } from './agent/spaceFs';
export function registerAgentCommand(program: Command) {
const agent = program.command('agent').description('Manage agents');
+ registerAgentSpaceFsCommand(agent);
// ── list ──────────────────────────────────────────────
diff --git a/apps/cli/src/commands/agent/resolveAgentId.ts b/apps/cli/src/commands/agent/resolveAgentId.ts
new file mode 100644
index 00000000000..5236f26f504
--- /dev/null
+++ b/apps/cli/src/commands/agent/resolveAgentId.ts
@@ -0,0 +1,44 @@
+import { log } from '../../utils/logger';
+
+interface AgentLookupClient {
+ agent: {
+ getBuiltinAgent: {
+ query: (input: { slug: string }) => Promise<{ agentId?: string; id?: string } | null>;
+ };
+ };
+}
+
+/**
+ * Resolve an agent identifier into a concrete agent id.
+ *
+ * Use when:
+ * - A command accepts either a positional agent id or `--slug`.
+ * - Downstream tRPC calls require the concrete agent id.
+ *
+ * Expects:
+ * - `opts.agentId` to win over `opts.slug`.
+ * - `client.agent.getBuiltinAgent` to resolve slugs when needed.
+ *
+ * Returns:
+ * - The resolved agent id, or exits the process after logging a CLI-facing error.
+ */
+export async function resolveAgentId(
+ client: AgentLookupClient,
+ opts: { agentId?: string; slug?: string },
+): Promise<string> {
+ if (opts.agentId) return opts.agentId;
+
+ if (opts.slug) {
+ const agent = await client.agent.getBuiltinAgent.query({ slug: opts.slug });
+ if (!agent) {
+ log.error(`Agent not found for slug: ${opts.slug}`);
+ process.exit(1);
+ }
+
+ return agent.id || agent.agentId || '';
+ }
+
+ log.error('Either <agentId> or --slug is required.');
+ process.exit(1);
+ return '';
+}
diff --git a/apps/cli/src/commands/agent/spaceFs.ts b/apps/cli/src/commands/agent/spaceFs.ts
new file mode 100644
index 00000000000..c34619a7f1f
--- /dev/null
+++ b/apps/cli/src/commands/agent/spaceFs.ts
@@ -0,0 +1,947 @@
+import { readFileSync } from 'node:fs';
+import { text } from 'node:stream/consumers';
+
+import type { Command } from 'commander';
+import dayjs from 'dayjs';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../../api/client';
+import { confirm, outputJson } from '../../utils/format';
+import { log } from '../../utils/logger';
+import { resolveAgentId } from './resolveAgentId';
+
+const SKILL_FILE_NAME = 'SKILL.md';
+
+const SKILL_NAMESPACE_PREFIXES = {
+ 'agent': './lobe/skills/agent/skills',
+ 'agent-topic': './lobe/skills/agent-topic/skills',
+ 'builtin': './lobe/skills/builtin/skills',
+ 'installed-active': './lobe/skills/installed/active/skills',
+ 'installed-all': './lobe/skills/installed/all/skills',
+} as const;
+
+const FS_PATH_ALIASES = {
+ 'agent': './',
+ 'builtin': 'builtin',
+ 'skills': 'agent',
+ 'installed-active': 'installed-active',
+ 'installed-all': 'installed-all',
+ 'topic-skills': 'agent-topic',
+ 'topic': 'agent-topic',
+} as const;
+
+type SkillFsNamespace = keyof typeof SKILL_NAMESPACE_PREFIXES;
+type AgentFsClient = Awaited<ReturnType<typeof getTrpcClient>>;
+
+interface AgentFsContext {
+ agentId: string;
+ topicId?: string;
+}
+
+interface AgentFsNode {
+ content?: string;
+ createdAt?: Date | string;
+ mode?: number;
+ mount?: {
+ driver?: string;
+ namespace?: string;
+ };
+ name: string;
+ path: string;
+ size?: number;
+ type: 'directory' | 'file';
+ updatedAt?: Date | string;
+}
+
+interface AgentFsResolvedPath {
+ filePath?: string;
+ namespace?: SkillFsNamespace;
+ path: string;
+ skillName?: string;
+}
+
+interface AgentFsOptions {
+ agentId?: string;
+ slug?: string;
+ topicId?: string;
+}
+
+function getTrpcErrorCode(error: unknown): string | undefined {
+ if (!error || typeof error !== 'object') return undefined;
+
+ const value = error as {
+ data?: { code?: string };
+ shape?: { data?: { code?: string } };
+ };
+
+ return value.data?.code ?? value.shape?.data?.code;
+}
+
+function exitWithError(message: string): never {
+ log.error(message);
+ process.exit(1);
+ throw new Error(message);
+}
+
+function resolveAgentFsPath(input = 'agent:/'): AgentFsResolvedPath {
+ const raw = input.trim();
+
+ const aliasMatch = raw.match(/^([a-z-]+):(\/.*)?$/);
+
+ if (aliasMatch) {
+ const alias = aliasMatch[1] as keyof typeof FS_PATH_ALIASES;
+ const target = FS_PATH_ALIASES[alias];
+
+ if (!target) {
+ exitWithError(
+ `Unknown fs namespace "${aliasMatch[1]}". Use agent, skills, topic-skills, builtin, installed-all, or installed-active.`,
+ );
+ }
+
+ const suffix = aliasMatch[2]?.replace(/^\/+/, '').replace(/\/+$/, '') ?? '';
+ const prefix = target === './' ? './' : SKILL_NAMESPACE_PREFIXES[target as SkillFsNamespace];
+
+ return resolveAgentFsPath(suffix ? `${prefix}/${suffix}` : prefix);
+ }
+
+ if (raw === './' || raw === '.' || raw === '/') {
+ return { path: './' };
+ }
+
+ const match = Object.entries(SKILL_NAMESPACE_PREFIXES).find(([, prefix]) => {
+ return raw === prefix || raw.startsWith(`${prefix}/`);
+ });
+
+ if (!match) {
+ if (!raw.startsWith('./')) {
+ exitWithError(`Invalid fs path "${input}". Use aliases like "agent:/" or a full VFS path.`);
+ }
+
+ const normalizedPath = raw.replaceAll(/\/+/g, '/').replace(/\/+$/, '') || './';
+ return { path: normalizedPath };
+ }
+
+ const [namespace, prefix] = match as [
+ SkillFsNamespace,
+ (typeof SKILL_NAMESPACE_PREFIXES)[SkillFsNamespace],
+ ];
+ const relativePath = raw.slice(prefix.length).replace(/^\/+/, '').replace(/\/+$/, '');
+
+ if (
+ relativePath.includes('//') ||
+ relativePath.split('/').some((segment) => segment === '.' || segment === '..')
+ ) {
+ exitWithError(`Invalid fs path "${input}"`);
+ }
+
+ if (!relativePath) {
+ return { namespace, path: prefix };
+ }
+
+ const separatorIndex = relativePath.indexOf('/');
+
+ if (separatorIndex < 0) {
+ return {
+ namespace,
+ path: `${prefix}/${relativePath}`,
+ skillName: relativePath,
+ };
+ }
+
+ return {
+ filePath: relativePath.slice(separatorIndex + 1),
+ namespace,
+ path: `${prefix}/${relativePath}`,
+ skillName: relativePath.slice(0, separatorIndex),
+ };
+}
+
+function requireTopicId(namespace: SkillFsNamespace | undefined, topicId?: string) {
+ if (namespace === 'agent-topic' && !topicId) {
+ exitWithError('--topic-id is required for agent-topic fs paths.');
+ }
+}
+
+function requireSkillNamespace(resolved: AgentFsResolvedPath): SkillFsNamespace {
+ if (!resolved.namespace) {
+ exitWithError(`Expected a skill namespace path, but received "${resolved.path}".`);
+ }
+
+ return resolved.namespace;
+}
+
+function canonicalSkillFilePath(resolved: AgentFsResolvedPath) {
+ if (!resolved.skillName) {
+ exitWithError('Expected a skill path, but received a namespace root.');
+ }
+
+ if (resolved.filePath && resolved.filePath !== SKILL_FILE_NAME) {
+ exitWithError(`Unsupported writable path "${resolved.path}". Only SKILL.md is mutable.`);
+ }
+
+ return `${SKILL_NAMESPACE_PREFIXES[requireSkillNamespace(resolved)]}/${resolved.skillName}/${SKILL_FILE_NAME}`;
+}
+
+function toDisplayPath(path: string) {
+ if (path === './') return 'agent:/';
+ if (path.startsWith('./') && path !== './lobe' && !path.startsWith('./lobe/')) {
+ return `agent:/${path.slice(2)}`;
+ }
+
+ for (const [namespace, prefix] of Object.entries(SKILL_NAMESPACE_PREFIXES) as Array<
+ [SkillFsNamespace, string]
+ >) {
+ const alias =
+ namespace === 'agent' ? 'skills' : namespace === 'agent-topic' ? 'topic-skills' : namespace;
+ if (path === prefix) return `${alias}:/`;
+ if (path.startsWith(`${prefix}/`)) return `${alias}:/${path.slice(prefix.length + 1)}`;
+ }
+
+ return path;
+}
+
+function isWritableNode(node: { mode?: number }) {
+ return ((node.mode ?? 0) & 4) !== 0;
+}
+
+function parseOptionalPositiveInteger(value?: string) {
+ if (value === undefined) return undefined;
+
+ const parsed = Number.parseInt(value, 10);
+ if (!Number.isFinite(parsed) || parsed <= 0) {
+ exitWithError(`Expected a positive integer, received "${value}".`);
+ }
+
+ return parsed;
+}
+
+function formatFsNodeName(node: { mode?: number; name: string; type: 'directory' | 'file' }) {
+ const suffix = node.type === 'directory' ? '/' : '';
+ return isWritableNode(node) ? `${node.name}${suffix}` : pc.dim(`${node.name}${suffix}`);
+}
+
+function getFsNodeDisplayName(node: Pick<AgentFsNode, 'name' | 'type'>) {
+ if (node.name === '.' || node.name === '..') return node.name;
+
+ return `${node.name}${node.type === 'directory' ? '/' : ''}`;
+}
+
+function getParentFsPath(path: string) {
+ if (path === './') return './';
+
+ const segments = path.replace(/^\.\//, '').split('/').filter(Boolean);
+ if (segments.length <= 1) return './';
+
+ return `./${segments.slice(0, -1).join('/')}`;
+}
+
+function createSyntheticListingNode(name: '.' | '..', path: string): AgentFsNode {
+ return {
+ mode: 10,
+ name,
+ path,
+ size: 0,
+ type: 'directory',
+ };
+}
+
+function formatFsPermissions(node: Pick<AgentFsNode, 'mode' | 'type'>) {
+ const mode = node.mode ?? 0;
+ const canRead = (mode & 2) !== 0 || (mode & 8) !== 0;
+ const canWrite = (mode & 4) !== 0;
+ const canExecute = (mode & 1) !== 0 || (node.type === 'directory' && (mode & 8) !== 0);
+ const owner = `${canRead ? 'r' : '-'}${canWrite ? 'w' : '-'}${canExecute ? 'x' : '-'}`;
+
+ return `${node.type === 'directory' ? 'd' : '-'}${owner}------`;
+}
+
+function formatFsLongDate(value?: Date | string) {
+ if (!value) return '--- -- --:--';
+
+ const date = dayjs(value);
+ if (!date.isValid()) return '--- -- --:--';
+
+ return date.format('MMM DD HH:mm');
+}
+
+function formatFsLongListing(nodes: AgentFsNode[]) {
+ const sizeWidth = Math.max(1, ...nodes.map((node) => String(node.size ?? 0).length));
+ const totalBlocks = nodes.reduce((total, node) => total + Math.ceil((node.size ?? 0) / 512), 0);
+ const lines = [`total ${totalBlocks}`];
+
+ for (const node of nodes) {
+ const size = String(node.size ?? 0).padStart(sizeWidth, ' ');
+ const mtime = formatFsLongDate(node.updatedAt ?? node.createdAt);
+ lines.push(
+ `${formatFsPermissions(node)} 1 agent agent ${size} ${mtime} ${getFsNodeDisplayName(node)}`,
+ );
+ }
+
+ return lines;
+}
+
+async function readFsContentInput(options: { content?: string; contentFile?: string }) {
+ if (options.contentFile) {
+ return readFileSync(options.contentFile, 'utf8');
+ }
+
+ if (options.content !== undefined) return options.content;
+
+ // NOTICE:
+ // CLI write commands should compose with shell pipelines without blocking interactive runs.
+ // Node marks piped stdin with `isTTY === false`, while normal terminals are `true` or undefined in tests.
+ // Remove this branch only if Commander gains first-class stdin option support for these commands.
+ if (process.stdin.isTTY === false) return text(process.stdin);
+
+ return '';
+}
+
+async function resolveAgentFsContext(client: AgentFsClient, options: AgentFsOptions) {
+ const agentId = await resolveAgentId(client, options);
+ return { agentId, topicId: options.topicId };
+}
+
+async function getFsNode(client: AgentFsClient, context: AgentFsContext, path: string) {
+ try {
+ return (await client.agentDocument.statDocumentByPath.query({
+ agentId: context.agentId,
+ path,
+ topicId: context.topicId,
+ })) as AgentFsNode;
+ } catch (error) {
+ if (getTrpcErrorCode(error) === 'NOT_FOUND') return undefined;
+ throw error;
+ }
+}
+
+async function readFsFile(client: AgentFsClient, context: AgentFsContext, inputPath: string) {
+ const resolved = resolveAgentFsPath(inputPath);
+ requireTopicId(resolved.namespace, context.topicId);
+
+ const readPath =
+ resolved.skillName && !resolved.filePath
+ ? `${SKILL_NAMESPACE_PREFIXES[requireSkillNamespace(resolved)]}/${resolved.skillName}/${SKILL_FILE_NAME}`
+ : resolved.path;
+
+ const stat = await getFsNode(client, context, readPath);
+
+ if (!stat) {
+ exitWithError(`Path not found: ${inputPath}`);
+ }
+
+ if (stat.type !== 'file') {
+ exitWithError(`Cannot read directory path: ${inputPath}`);
+ }
+
+ const node = (await client.agentDocument.readDocumentByPath.query({
+ agentId: context.agentId,
+ path: readPath,
+ topicId: context.topicId,
+ })) as AgentFsNode;
+
+ return { node, resolved: resolveAgentFsPath(readPath) };
+}
+
+async function writeFsFile(
+ client: AgentFsClient,
+ context: AgentFsContext,
+ inputPath: string,
+ content: string,
+) {
+ const resolved = resolveAgentFsPath(inputPath);
+ requireTopicId(resolved.namespace, context.topicId);
+ const existing = await getFsNode(
+ client,
+ context,
+ resolved.skillName && !resolved.filePath ? canonicalSkillFilePath(resolved) : resolved.path,
+ );
+ const result = await client.agentDocument.writeDocumentByPath.mutate({
+ agentId: context.agentId,
+ content,
+ createMode: existing ? 'must-exist' : 'if-missing',
+ path: resolved.path,
+ topicId: context.topicId,
+ });
+
+ return {
+ action: existing ? ('updated' as const) : ('created' as const),
+ path: result?.path ?? resolved.path,
+ };
+}
+
+async function mkdirFsPath(
+ client: AgentFsClient,
+ context: AgentFsContext,
+ inputPath: string,
+ options?: { recursive?: boolean },
+) {
+ const resolved = resolveAgentFsPath(inputPath);
+ requireTopicId(resolved.namespace, context.topicId);
+
+ return client.agentDocument.mkdirDocumentByPath.mutate({
+ agentId: context.agentId,
+ path: resolved.path,
+ recursive: options?.recursive,
+ topicId: context.topicId,
+ });
+}
+
+async function deleteFsPath(
+ client: AgentFsClient,
+ context: AgentFsContext,
+ inputPath: string,
+ options?: { force?: boolean; recursive?: boolean },
+) {
+ const resolved = resolveAgentFsPath(inputPath);
+ requireTopicId(resolved.namespace, context.topicId);
+
+ return client.agentDocument.deleteDocumentByPath.mutate({
+ agentId: context.agentId,
+ force: options?.force,
+ path: resolved.path,
+ recursive: options?.recursive,
+ topicId: context.topicId,
+ });
+}
+
+async function copyFsPath(
+ client: AgentFsClient,
+ context: AgentFsContext,
+ source: string,
+ destination: string,
+ force?: boolean,
+) {
+ const sourceResolved = resolveAgentFsPath(source);
+ const destinationResolved = resolveAgentFsPath(destination);
+
+ requireTopicId(sourceResolved.namespace, context.topicId);
+ requireTopicId(destinationResolved.namespace, context.topicId);
+
+ return client.agentDocument.copyDocumentByPath.mutate({
+ agentId: context.agentId,
+ force,
+ fromPath: sourceResolved.path,
+ toPath: destinationResolved.path,
+ topicId: context.topicId,
+ });
+}
+
+async function renameFsPath(
+ client: AgentFsClient,
+ context: AgentFsContext,
+ source: string,
+ destination: string,
+ force?: boolean,
+) {
+ const sourceResolved = resolveAgentFsPath(source);
+ const destinationResolved = resolveAgentFsPath(destination);
+
+ requireTopicId(sourceResolved.namespace, context.topicId);
+ requireTopicId(destinationResolved.namespace, context.topicId);
+
+ return client.agentDocument.renameDocumentByPath.mutate({
+ agentId: context.agentId,
+ force,
+ fromPath: sourceResolved.path,
+ toPath: destinationResolved.path,
+ topicId: context.topicId,
+ });
+}
+
+async function listTrashFsPath(client: AgentFsClient, context: AgentFsContext, inputPath?: string) {
+ const resolved = resolveAgentFsPath(inputPath || 'agent:/');
+ requireTopicId(resolved.namespace, context.topicId);
+
+ return (await client.agentDocument.listTrashDocumentsByPath.query({
+ agentId: context.agentId,
+ path: resolved.path,
+ topicId: context.topicId,
+ })) as Array<Pick<AgentFsNode, 'path'>>;
+}
+
+async function restoreTrashFsPath(
+ client: AgentFsClient,
+ context: AgentFsContext,
+ inputPath: string,
+) {
+ const resolved = resolveAgentFsPath(inputPath);
+ requireTopicId(resolved.namespace, context.topicId);
+
+ return client.agentDocument.restoreDocumentFromTrashByPath.mutate({
+ agentId: context.agentId,
+ path: resolved.path,
+ topicId: context.topicId,
+ });
+}
+
+async function deleteTrashFsPath(
+ client: AgentFsClient,
+ context: AgentFsContext,
+ inputPath: string,
+ options?: { force?: boolean; recursive?: boolean },
+) {
+ const resolved = resolveAgentFsPath(inputPath);
+ requireTopicId(resolved.namespace, context.topicId);
+
+ return client.agentDocument.deleteDocumentPermanentlyByPath.mutate({
+ agentId: context.agentId,
+ force: options?.force,
+ path: resolved.path,
+ recursive: options?.recursive,
+ topicId: context.topicId,
+ });
+}
+
+async function printFsTree(
+ client: AgentFsClient,
+ context: AgentFsContext,
+ path: string,
+ prefix = '',
+ warnings: string[] = [],
+) {
+ let nodes: AgentFsNode[];
+
+ try {
+ nodes = (await client.agentDocument.listDocumentsByPath.query({
+ agentId: context.agentId,
+ path,
+ topicId: context.topicId,
+ })) as AgentFsNode[];
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'failed to list path';
+ warnings.push(`${toDisplayPath(path)}: ${message}`);
+ return;
+ }
+
+ for (const [index, node] of nodes.entries()) {
+ const last = index === nodes.length - 1;
+ console.log(`${prefix}${last ? '└── ' : '├── '}${formatFsNodeName(node)}`);
+
+ if (node.type === 'directory') {
+ await printFsTree(client, context, node.path, `${prefix}${last ? ' ' : '│ '}`, warnings);
+ }
+ }
+}
+
+function registerFsCommands(fsCommand: Command) {
+ fsCommand
+ .command('ls [path]')
+ .description('List VFS entries')
+ .option('-a, --all', 'Include hidden entries')
+ .option('-l, --long', 'Use long listing format')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .option('--cursor <cursor>', 'Directory pagination cursor')
+ .option('-L, --limit <n>', 'Maximum number of entries')
+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
+ .action(
+ async (
+ inputPath: string | undefined,
+ options: {
+ agentId?: string;
+ all?: boolean;
+ cursor?: string;
+ json?: string | boolean;
+ limit?: string;
+ long?: boolean;
+ slug?: string;
+ topicId?: string;
+ },
+ ) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const resolved = resolveAgentFsPath(inputPath || 'agent:/');
+ requireTopicId(resolved.namespace, context.topicId);
+
+ const nodes = ((await client.agentDocument.listDocumentsByPath.query({
+ agentId: context.agentId,
+ cursor: options.cursor,
+ limit: parseOptionalPositiveInteger(options.limit),
+ path: resolved.path,
+ topicId: context.topicId,
+ })) ?? []) as AgentFsNode[];
+ const filtered = options.all ? nodes : nodes.filter((node) => !node.name.startsWith('.'));
+
+ if (options.json !== undefined) {
+ const fields = typeof options.json === 'string' ? options.json : undefined;
+ outputJson(filtered, fields);
+ return;
+ }
+
+ if (options.long) {
+ const longNodes = options.all
+ ? [
+ createSyntheticListingNode('.', resolved.path),
+ createSyntheticListingNode('..', getParentFsPath(resolved.path)),
+ ...filtered,
+ ]
+ : filtered;
+ formatFsLongListing(longNodes).forEach((line) => console.log(line));
+ return;
+ }
+
+ filtered.forEach((node) => console.log(formatFsNodeName(node)));
+ },
+ );
+
+ fsCommand
+ .command('tree [path]')
+ .description('Print a tree view of the VFS')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .action(
+ async (
+ inputPath: string | undefined,
+ options: { agentId?: string; slug?: string; topicId?: string },
+ ) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const resolved = resolveAgentFsPath(inputPath || 'agent:/');
+ requireTopicId(resolved.namespace, context.topicId);
+
+ console.log(pc.bold(toDisplayPath(resolved.path)));
+ const warnings: string[] = [];
+ await printFsTree(client, context, resolved.path, '', warnings);
+
+ for (const warning of warnings) {
+ log.warn(warning);
+ }
+ },
+ );
+
+ fsCommand
+ .command('cat <path>')
+ .description('Read a VFS file')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .action(
+ async (inputPath: string, options: { agentId?: string; slug?: string; topicId?: string }) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const { node } = await readFsFile(client, context, inputPath);
+ process.stdout.write(node.content ?? '');
+ },
+ );
+
+ fsCommand
+ .command('stat <path>')
+ .description('Show VFS node metadata')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
+ .action(
+ async (
+ inputPath: string,
+ options: {
+ agentId?: string;
+ json?: string | boolean;
+ slug?: string;
+ topicId?: string;
+ },
+ ) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const resolved = resolveAgentFsPath(inputPath);
+ requireTopicId(resolved.namespace, context.topicId);
+
+ const node = await getFsNode(client, context, resolved.path);
+
+ if (!node) {
+ exitWithError(`Path not found: ${inputPath}`);
+ }
+
+ if (options.json !== undefined) {
+ const fields = typeof options.json === 'string' ? options.json : undefined;
+ outputJson(node, fields);
+ return;
+ }
+
+ console.log(JSON.stringify(node, null, 2));
+ },
+ );
+
+ fsCommand
+ .command('touch <path>')
+ .description('Create or update a VFS file')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .option('-c, --content <content>', 'File content')
+ .option('-F, --content-file <path>', 'Read content from a local file')
+ .action(
+ async (
+ inputPath: string,
+ options: {
+ agentId?: string;
+ content?: string;
+ contentFile?: string;
+ slug?: string;
+ topicId?: string;
+ },
+ ) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const content = await readFsContentInput(options);
+ const result = await writeFsFile(client, context, inputPath, content);
+ console.log(`${pc.green('✓')} ${result.action} ${pc.bold(toDisplayPath(result.path))}`);
+ },
+ );
+
+ fsCommand
+ .command('write <path>')
+ .description('Write content to a VFS file')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .option('-c, --content <content>', 'File content')
+ .option('-F, --content-file <path>', 'Read content from a local file')
+ .action(
+ async (
+ inputPath: string,
+ options: {
+ agentId?: string;
+ content?: string;
+ contentFile?: string;
+ slug?: string;
+ topicId?: string;
+ },
+ ) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const content = await readFsContentInput(options);
+ const result = await writeFsFile(client, context, inputPath, content);
+ console.log(`${pc.green('✓')} ${result.action} ${pc.bold(toDisplayPath(result.path))}`);
+ },
+ );
+
+ fsCommand
+ .command('mkdir <path>')
+ .description('Create a VFS directory')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .option('-p, --parents', 'Create parent directories as needed')
+ .action(
+ async (
+ inputPath: string,
+ options: { agentId?: string; parents?: boolean; slug?: string; topicId?: string },
+ ) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const result = await mkdirFsPath(client, context, inputPath, {
+ recursive: options.parents,
+ });
+ console.log(
+ `${pc.green('✓')} created ${pc.bold(toDisplayPath(result?.path ?? inputPath))}`,
+ );
+ },
+ );
+
+ fsCommand
+ .command('rm <path>')
+ .description('Delete a VFS node into trash')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .option('-r, --recursive', 'Recursively delete a directory subtree')
+ .option('-f, --force', 'Forward force semantics to the VFS delete primitive')
+ .option('--yes', 'Skip confirmation prompt')
+ .action(
+ async (
+ inputPath: string,
+ options: {
+ agentId?: string;
+ force?: boolean;
+ recursive?: boolean;
+ slug?: string;
+ topicId?: string;
+ yes?: boolean;
+ },
+ ) => {
+ if (!options.yes) {
+ const confirmed = await confirm(`Delete ${inputPath}?`);
+ if (!confirmed) {
+ console.log('Cancelled.');
+ return;
+ }
+ }
+
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ await deleteFsPath(client, context, inputPath, {
+ force: options.force,
+ recursive: options.recursive,
+ });
+ console.log(`${pc.green('✓')} deleted ${pc.bold(inputPath)}`);
+ },
+ );
+
+ fsCommand
+ .command('cp <source> <destination>')
+ .description('Copy a VFS node')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic source or destination paths')
+ .option('-f, --force', 'Overwrite the destination if it exists')
+ .action(
+ async (
+ source: string,
+ destination: string,
+ options: { agentId?: string; force?: boolean; slug?: string; topicId?: string },
+ ) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const result = await copyFsPath(client, context, source, destination, options.force);
+ console.log(
+ `${pc.green('✓')} copied ${pc.bold(source)} → ${pc.bold(toDisplayPath(result?.path ?? destination))}`,
+ );
+ },
+ );
+
+ fsCommand
+ .command('mv <source> <destination>')
+ .description('Move or rename a VFS node')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic source or destination paths')
+ .option('-f, --force', 'Overwrite the destination if it exists')
+ .action(
+ async (
+ source: string,
+ destination: string,
+ options: { agentId?: string; force?: boolean; slug?: string; topicId?: string },
+ ) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const sourceResolved = resolveAgentFsPath(source);
+ const destinationResolved = resolveAgentFsPath(destination);
+
+ if (sourceResolved.path === destinationResolved.path) {
+ console.log(`${pc.yellow('!')} source and destination are the same.`);
+ return;
+ }
+
+ const result = await renameFsPath(client, context, source, destination, options.force);
+ console.log(
+ `${pc.green('✓')} moved ${pc.bold(source)} → ${pc.bold(toDisplayPath(result?.path ?? destination))}`,
+ );
+ },
+ );
+
+ const trashCommand = fsCommand.command('trash').description('Operate on soft-deleted VFS nodes');
+
+ trashCommand
+ .command('ls [path]')
+ .description('List trashed VFS nodes')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
+ .action(
+ async (
+ inputPath: string | undefined,
+ options: {
+ agentId?: string;
+ json?: string | boolean;
+ slug?: string;
+ topicId?: string;
+ },
+ ) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const nodes = await listTrashFsPath(client, context, inputPath);
+
+ if (options.json !== undefined) {
+ const fields = typeof options.json === 'string' ? options.json : undefined;
+ outputJson(nodes, fields);
+ return;
+ }
+
+ if (nodes.length === 0) {
+ console.log('Trash is empty.');
+ return;
+ }
+
+ nodes.forEach((node) => console.log(toDisplayPath(node.path)));
+ },
+ );
+
+ trashCommand
+ .command('restore <path>')
+ .description('Restore a soft-deleted VFS node')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .action(
+ async (inputPath: string, options: { agentId?: string; slug?: string; topicId?: string }) => {
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ const result = await restoreTrashFsPath(client, context, inputPath);
+ console.log(
+ `${pc.green('✓')} restored ${pc.bold(toDisplayPath(result?.path ?? inputPath))}`,
+ );
+ },
+ );
+
+ trashCommand
+ .command('rm <path>')
+ .description('Permanently delete a trashed VFS node')
+ .option('-A, --agent-id <id>', 'Agent ID')
+ .option('-s, --slug <slug>', 'Agent slug')
+ .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
+ .option('-r, --recursive', 'Recursively delete a directory subtree')
+ .option('-f, --force', 'Forward force semantics to the permanent delete primitive')
+ .option('--yes', 'Skip confirmation prompt')
+ .action(
+ async (
+ inputPath: string,
+ options: {
+ agentId?: string;
+ force?: boolean;
+ recursive?: boolean;
+ slug?: string;
+ topicId?: string;
+ yes?: boolean;
+ },
+ ) => {
+ if (!options.yes) {
+ const confirmed = await confirm(`Permanently delete ${inputPath}?`);
+ if (!confirmed) {
+ console.log('Cancelled.');
+ return;
+ }
+ }
+
+ const client = await getTrpcClient();
+ const context = await resolveAgentFsContext(client, options);
+ await deleteTrashFsPath(client, context, inputPath, {
+ force: options.force,
+ recursive: options.recursive,
+ });
+ console.log(`${pc.green('✓')} permanently deleted ${pc.bold(inputPath)}`);
+ },
+ );
+}
+
+/**
+ * Register agent document VFS commands under `agent space fs`.
+ *
+ * Use when:
+ * - The CLI should expose filesystem-like operations for an agent document space.
+ * - Command registration should stay outside the core `agent` command file.
+ *
+ * Expects:
+ * - `agentCommand` to be the existing `agent` command group.
+ *
+ * Returns:
+ * - Registered Commander subcommands.
+ */
+export function registerAgentSpaceFsCommand(agentCommand: Command) {
+ const spaceCommand = agentCommand.command('space').description('Manage agent document space');
+ const fsCommand = spaceCommand.command('fs').description('Operate on the agent document VFS');
+ registerFsCommands(fsCommand);
+}
diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
index 9ea9992e19e..e35154258e0 100644
--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { agentDocuments, agents, documents, users } from '../../../schemas';
+import { DOCUMENT_FOLDER_TYPE } from '../../../schemas/file';
import type { LobeChatDatabase } from '../../../type';
import {
AgentDocumentModel,
@@ -127,6 +128,28 @@ describe('AgentDocumentModel', () => {
expect(countAfter.length).toBe(countBefore.length);
});
+
+ it('should reject associating a document when a live sibling already owns the same path', async () => {
+ await agentDocumentModel.create(agentId, 'associated.md', 'managed');
+ const [doc] = await serverDB
+ .insert(documents)
+ .values({
+ content: 'existing',
+ fileType: 'article',
+ filename: 'associated.md',
+ source: 'https://example.com/associated',
+ sourceType: 'web',
+ title: 'Associated',
+ totalCharCount: 8,
+ totalLineCount: 1,
+ userId,
+ })
+ .returning();
+
+ await expect(
+ agentDocumentModel.associate({ agentId, documentId: doc!.id }),
+ ).rejects.toThrow();
+ });
});
describe('create', () => {
@@ -171,6 +194,45 @@ describe('AgentDocumentModel', () => {
expect(result.accessShared).toBe(0);
expect(result.accessPublic).toBe(0);
});
+
+ it('should reject duplicate live siblings at the database boundary', async () => {
+ await agentDocumentModel.create(agentId, 'duplicate.md', 'first');
+
+ await expect(agentDocumentModel.create(agentId, 'duplicate.md', 'second')).rejects.toThrow();
+ });
+
+ it('should allow different agents to use the same root filename', async () => {
+ const first = await agentDocumentModel.create(agentId, 'shared.md', 'first');
+ const second = await agentDocumentModel.create(secondAgentId, 'shared.md', 'second');
+
+ expect(first.agentId).toBe(agentId);
+ expect(second.agentId).toBe(secondAgentId);
+ expect(first.documentId).not.toBe(second.documentId);
+ });
+
+ it('should allow recreating a filename after the previous sibling is soft deleted', async () => {
+ const first = await agentDocumentModel.create(agentId, 'recreated.md', 'first');
+
+ await agentDocumentModel.delete(first.id, 'replace');
+
+ const second = await agentDocumentModel.create(agentId, 'recreated.md', 'second');
+
+ expect(second.id).not.toBe(first.id);
+ expect(second.content).toBe('second');
+ });
+
+ it('should allow callers to opt out of sibling uniqueness for managed mount documents', async () => {
+ const first = await agentDocumentModel.create(agentId, 'skills', '', {
+ uniqueSibling: false,
+ metadata: { mount: { namespace: 'topic', role: 'root' } },
+ });
+ const second = await agentDocumentModel.create(agentId, 'skills', '', {
+ uniqueSibling: false,
+ metadata: { mount: { namespace: 'agent', role: 'root' } },
+ });
+
+ expect(first.documentId).not.toBe(second.documentId);
+ });
});
describe('findById and findByFilename', () => {
@@ -309,6 +371,49 @@ describe('AgentDocumentModel', () => {
expect(renamed?.filename).toBe('IDENTITY 2');
});
+ it('should move path metadata without changing agent document identity', async () => {
+ const folder = await agentDocumentModel.create(agentId, 'folder', '', {
+ fileType: DOCUMENT_FOLDER_TYPE,
+ title: 'folder',
+ });
+ const created = await agentDocumentModel.create(agentId, 'old.md', 'hello');
+
+ const moved = await agentDocumentModel.movePath(created.id, {
+ filename: 'new.md',
+ parentId: folder.documentId,
+ });
+
+ expect(moved?.id).toBe(created.id);
+ expect(moved?.documentId).toBe(created.documentId);
+ expect(moved?.filename).toBe('new.md');
+ expect(moved?.parentId).toBe(folder.documentId);
+
+ const [doc] = await serverDB
+ .select()
+ .from(documents)
+ .where(eq(documents.id, created.documentId));
+
+ expect(doc?.source).toBe(`agent-document://${agentId}/${encodeURIComponent('new.md')}`);
+ });
+
+ it('should reject moving a document over an existing live sibling path', async () => {
+ const folder = await agentDocumentModel.create(agentId, 'move-folder', '', {
+ fileType: DOCUMENT_FOLDER_TYPE,
+ title: 'move-folder',
+ });
+ const source = await agentDocumentModel.create(agentId, 'source.md', 'source');
+ await agentDocumentModel.create(agentId, 'target.md', 'target', {
+ parentId: folder.documentId,
+ });
+
+ await expect(
+ agentDocumentModel.movePath(source.id, {
+ filename: 'target.md',
+ parentId: folder.documentId,
+ }),
+ ).rejects.toThrow();
+ });
+
it('should copy into a new record and keep policy/template metadata', async () => {
const created = await agentDocumentModel.create(agentId, 'copy-source.md', 'copy me', {
loadPosition: DocumentLoadPosition.BEFORE_SYSTEM,
@@ -505,6 +610,15 @@ describe('AgentDocumentModel', () => {
expect(rawDoc).toBeDefined();
});
+ it('should reject restoring a deleted document over an existing live sibling path', async () => {
+ const first = await agentDocumentModel.create(agentId, 'restore-conflict.md', 'first');
+
+ await agentDocumentModel.delete(first.id, 'replace');
+ await agentDocumentModel.create(agentId, 'restore-conflict.md', 'second');
+
+ await expect(agentDocumentModel.restore(first.id)).rejects.toThrow();
+ });
+
it('should return empty string from getAgentContext when no loadable docs exist', async () => {
const context = await agentDocumentModel.getAgentContext(agentId);
expect(context).toBe('');
@@ -542,5 +656,149 @@ describe('AgentDocumentModel', () => {
.where(and(eq(agentDocuments.id, otherTemplateDoc.id), eq(agentDocuments.userId, userId)));
expect(otherTemplateRow?.deletedAt).toBeNull();
});
+
+ it('should support include-deleted lookups and deleted-only child listings', async () => {
+ const folder = await agentDocumentModel.create(agentId, 'notes', '', {
+ fileType: DOCUMENT_FOLDER_TYPE,
+ title: 'notes',
+ });
+ const visibleChild = await agentDocumentModel.create(agentId, 'visible.md', 'visible', {
+ parentId: folder.documentId,
+ });
+ const deletedChild = await agentDocumentModel.create(agentId, 'deleted.md', 'deleted', {
+ parentId: folder.documentId,
+ });
+
+ await agentDocumentModel.delete(deletedChild.id, 'trash it');
+
+ expect(await agentDocumentModel.findById(deletedChild.id)).toBeUndefined();
+ expect(
+ await agentDocumentModel.findById(deletedChild.id, {
+ includeDeleted: true,
+ }),
+ ).toMatchObject({ id: deletedChild.id });
+
+ const liveChildren = await agentDocumentModel.listByParent(agentId, folder.documentId);
+ const allChildren = await agentDocumentModel.listByParent(agentId, folder.documentId, {
+ includeDeleted: true,
+ });
+ const deletedChildren = await agentDocumentModel.listByParent(agentId, folder.documentId, {
+ deletedOnly: true,
+ });
+
+ expect(liveChildren.map((item) => item.id)).toEqual([visibleChild.id]);
+ expect(allChildren.map((item) => item.id).sort()).toEqual(
+ [visibleChild.id, deletedChild.id].sort(),
+ );
+ expect(deletedChildren.map((item) => item.id)).toEqual([deletedChild.id]);
+
+ const deletedByPath = await agentDocumentModel.findByParentAndFilename(
+ agentId,
+ folder.documentId,
+ 'deleted.md',
+ {
+ includeDeleted: true,
+ },
+ );
+ expect(deletedByPath?.id).toBe(deletedChild.id);
+
+ const liveByPath = await agentDocumentModel.listByParentAndFilename(
+ agentId,
+ folder.documentId,
+ 'visible.md',
+ {
+ limit: 1,
+ },
+ );
+ expect(liveByPath.map((item) => item.id)).toEqual([visibleChild.id]);
+ });
+
+ it('should soft-delete, restore, and permanently delete a subtree by root document id', async () => {
+ const rootFolder = await agentDocumentModel.create(agentId, 'workspace', '', {
+ fileType: DOCUMENT_FOLDER_TYPE,
+ title: 'workspace',
+ });
+ const nestedFolder = await agentDocumentModel.create(agentId, 'drafts', '', {
+ fileType: DOCUMENT_FOLDER_TYPE,
+ parentId: rootFolder.documentId,
+ title: 'drafts',
+ });
+ const nestedFile = await agentDocumentModel.create(agentId, 'plan.md', 'v1', {
+ parentId: nestedFolder.documentId,
+ });
+ const siblingFile = await agentDocumentModel.create(agentId, 'keep.md', 'keep me');
+
+ await agentDocumentModel.deleteSubtreeByDocumentId(
+ agentId,
+ rootFolder.documentId,
+ 'recursive cleanup',
+ );
+
+ expect(await agentDocumentModel.findById(rootFolder.id)).toBeUndefined();
+ expect(await agentDocumentModel.findById(nestedFolder.id)).toBeUndefined();
+ expect(await agentDocumentModel.findById(nestedFile.id)).toBeUndefined();
+ expect(await agentDocumentModel.findById(siblingFile.id)).toBeDefined();
+
+ const deletedTree = await agentDocumentModel.listSubtreeByDocumentId(
+ agentId,
+ rootFolder.documentId,
+ {
+ includeDeleted: true,
+ },
+ );
+ expect(deletedTree.map((item) => item.id).sort()).toEqual(
+ [rootFolder.id, nestedFolder.id, nestedFile.id].sort(),
+ );
+
+ const trashItems = await agentDocumentModel.listDeletedByAgent(agentId);
+ expect(trashItems.map((item) => item.id).sort()).toEqual(
+ [rootFolder.id, nestedFolder.id, nestedFile.id].sort(),
+ );
+
+ await agentDocumentModel.restoreSubtreeByDocumentId(agentId, rootFolder.documentId);
+
+ const restoredTree = await agentDocumentModel.listSubtreeByDocumentId(
+ agentId,
+ rootFolder.documentId,
+ );
+ expect(restoredTree.map((item) => item.id).sort()).toEqual(
+ [rootFolder.id, nestedFolder.id, nestedFile.id].sort(),
+ );
+ expect(await agentDocumentModel.listDeletedByAgent(agentId)).toEqual([]);
+
+ await agentDocumentModel.deleteSubtreeByDocumentId(
+ agentId,
+ rootFolder.documentId,
+ 'recursive cleanup',
+ );
+ await agentDocumentModel.permanentlyDeleteSubtreeByDocumentId(agentId, rootFolder.documentId);
+
+ expect(
+ await agentDocumentModel.findByDocumentId(agentId, rootFolder.documentId, {
+ includeDeleted: true,
+ }),
+ ).toBeUndefined();
+ expect(
+ await agentDocumentModel.findByDocumentId(agentId, nestedFolder.documentId, {
+ includeDeleted: true,
+ }),
+ ).toBeUndefined();
+ expect(
+ await agentDocumentModel.findByDocumentId(agentId, nestedFile.documentId, {
+ includeDeleted: true,
+ }),
+ ).toBeUndefined();
+ expect(await agentDocumentModel.findById(siblingFile.id)).toBeDefined();
+
+ const remainingRows = await serverDB
+ .select()
+ .from(documents)
+ .where(eq(documents.userId, userId));
+
+ expect(remainingRows.map((item) => item.id)).toContain(siblingFile.documentId);
+ expect(remainingRows.map((item) => item.id)).not.toContain(rootFolder.documentId);
+ expect(remainingRows.map((item) => item.id)).not.toContain(nestedFolder.documentId);
+ expect(remainingRows.map((item) => item.id)).not.toContain(nestedFile.documentId);
+ });
});
});
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.ts
index 087b6946e45..c87834649b5 100644
--- a/packages/database/src/models/agentDocuments/agentDocument.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument.ts
@@ -1,4 +1,4 @@
-import { and, desc, eq, inArray, isNull } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNotNull, isNull, ne } from 'drizzle-orm';
import type { DocumentItem, NewAgentDocument, NewDocument } from '../../schemas';
import { agentDocuments, documents } from '../../schemas';
@@ -29,6 +29,30 @@ import {
export * from './types';
+interface AgentDocumentQueryOptions {
+ cursor?: string;
+ deletedOnly?: boolean;
+ includeDeleted?: boolean;
+ limit?: number;
+}
+
+/**
+ * Options for runtime VFS sibling uniqueness checks.
+ */
+interface AgentDocumentSiblingUniquenessOptions {
+ /**
+ * Whether to enforce one live ordinary document per `agentId + parentId + filename`.
+ *
+ * @default true
+ *
+ * NOTICE:
+ * Set this to `false` only for managed mount documents that are not resolved through the
+ * ordinary document VFS tree. Managed mounts can reuse backing storage names such as `skills`
+ * while exposing distinct mounted namespaces.
+ */
+ uniqueSibling?: boolean;
+}
+
export class AgentDocumentModel {
private userId: string;
private db: LobeChatDatabase;
@@ -72,9 +96,11 @@ export class AgentDocumentModel {
description: doc.description ?? null,
documentId: settings.documentId,
editorData: doc.editorData ?? null,
+ fileType: doc.fileType,
filename: doc.filename ?? '',
id: settings.id,
metadata: (doc.metadata as Record<string, any> | null) ?? null,
+ parentId: doc.parentId ?? null,
policy,
policyLoadFormat,
policyLoadPosition: settings.policyLoadPosition,
@@ -88,45 +114,181 @@ export class AgentDocumentModel {
};
}
+ private buildDeletedAtFilters(options?: AgentDocumentQueryOptions) {
+ if (options?.deletedOnly) return [isNotNull(agentDocuments.deletedAt)];
+ if (options?.includeDeleted) return [];
+
+ return [isNull(agentDocuments.deletedAt)];
+ }
+
+ /**
+ * Guards the agent-visible VFS sibling invariant before writes.
+ *
+ * Runtime enforcement is required for now because `agentId`/`deletedAt` live on `agent_documents`
+ * while `parentId`/`filename` live on `documents`.
+ */
+ private async assertNoLiveSiblingConflict(
+ db: Pick<LobeChatDatabase, 'select'>,
+ params: {
+ agentId: string;
+ excludeAgentDocumentId?: string;
+ excludeDocumentId?: string;
+ filename: string;
+ parentId: string | null;
+ },
+ ) {
+ const excludeAgentDocument = params.excludeAgentDocumentId
+ ? ne(agentDocuments.id, params.excludeAgentDocumentId)
+ : undefined;
+ const excludeDocument = params.excludeDocumentId
+ ? ne(agentDocuments.documentId, params.excludeDocumentId)
+ : undefined;
+
+ // TODO: Move this extra conflict query to a schema-level invariant when VFS path ownership fields live on one table.
+ const [conflict] = await db
+ .select({ id: agentDocuments.id })
+ .from(agentDocuments)
+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ eq(agentDocuments.agentId, params.agentId),
+ eq(documents.filename, params.filename),
+ params.parentId ? eq(documents.parentId, params.parentId) : isNull(documents.parentId),
+ isNull(agentDocuments.deletedAt),
+ ...(excludeAgentDocument ? [excludeAgentDocument] : []),
+ ...(excludeDocument ? [excludeDocument] : []),
+ ),
+ )
+ .limit(1);
+
+ if (conflict) {
+ throw new Error(`Agent document sibling already exists: ${params.filename}`);
+ }
+ }
+
+ private normalizeListOffset(cursor?: string): number {
+ if (!cursor) return 0;
+
+ const parsed = Number.parseInt(cursor, 10);
+
+ // Offset cursors keep the first VFS pagination pass storage-neutral.
+ // Callers that need opaque cursors can wrap this model helper at the service layer later.
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
+ }
+
+ private async listByParentIds(
+ agentId: string,
+ parentIds: string[],
+ options?: AgentDocumentQueryOptions,
+ ): Promise<AgentDocument[]> {
+ if (parentIds.length === 0) return [];
+
+ const results = await this.db
+ .select({ doc: documents, settings: agentDocuments })
+ .from(agentDocuments)
+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ eq(agentDocuments.agentId, agentId),
+ inArray(documents.parentId, parentIds),
+ ...this.buildDeletedAtFilters(options),
+ ),
+ )
+ .orderBy(desc(agentDocuments.updatedAt));
+
+ return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));
+ }
+
+ /**
+ * Associates an existing document row with an agent document binding.
+ *
+ * Use when:
+ * - A document already exists and should become visible to an agent.
+ * - Managed mount providers need to bind pre-created document tree nodes.
+ *
+ * Expects:
+ * - `documentId` belongs to the current user.
+ * - `uniqueSibling` defaults to `true` for ordinary VFS documents.
+ *
+ * Returns:
+ * - The inserted agent document binding id, or an empty id when the source document is missing.
+ *
+ * NOTICE:
+ * Pass `uniqueSibling: false` only for managed mount documents whose visible path is resolved by
+ * the mount provider instead of the ordinary `parentId + filename` VFS tree.
+ */
async associate(params: {
agentId: string;
documentId: string;
+ uniqueSibling?: boolean;
policyLoad?: PolicyLoad;
}): Promise<{ id: string }> {
- const { agentId, documentId, policyLoad } = params;
-
- // Verify the document belongs to the current user
- const doc = await this.db.query.documents.findFirst({
- where: and(eq(documents.id, documentId), eq(documents.userId, this.userId)),
- });
-
- if (!doc) return { id: '' };
+ const { agentId, documentId, uniqueSibling = true, policyLoad } = params;
- const [result] = await this.db
- .insert(agentDocuments)
- .values({
- accessPublic: 0,
- accessSelf:
- AgentAccess.EXECUTE |
- AgentAccess.LIST |
- AgentAccess.READ |
- AgentAccess.WRITE |
- AgentAccess.DELETE,
- accessShared: 0,
- agentId,
- documentId,
- policyLoad: policyLoad ?? PolicyLoad.PROGRESSIVE,
- policyLoadFormat: DocumentLoadFormat.RAW,
- policyLoadPosition: DocumentLoadPosition.BEFORE_FIRST_USER,
- policyLoadRule: DocumentLoadRule.ALWAYS,
- userId: this.userId,
- })
- .onConflictDoNothing()
- .returning({ id: agentDocuments.id });
+ return this.db.transaction(async (trx) => {
+ const [doc] = await trx
+ .select()
+ .from(documents)
+ .where(and(eq(documents.id, documentId), eq(documents.userId, this.userId)))
+ .limit(1);
+
+ if (!doc) return { id: '' };
+
+ if (uniqueSibling) {
+ await this.assertNoLiveSiblingConflict(trx, {
+ agentId,
+ excludeDocumentId: documentId,
+ filename: doc.filename ?? '',
+ parentId: doc.parentId ?? null,
+ });
+ }
- return { id: result?.id };
+ const [result] = await trx
+ .insert(agentDocuments)
+ .values({
+ accessPublic: 0,
+ accessSelf:
+ AgentAccess.EXECUTE |
+ AgentAccess.LIST |
+ AgentAccess.READ |
+ AgentAccess.WRITE |
+ AgentAccess.DELETE,
+ accessShared: 0,
+ agentId,
+ documentId,
+ policyLoad: policyLoad ?? PolicyLoad.PROGRESSIVE,
+ policyLoadFormat: DocumentLoadFormat.RAW,
+ policyLoadPosition: DocumentLoadPosition.BEFORE_FIRST_USER,
+ policyLoadRule: DocumentLoadRule.ALWAYS,
+ userId: this.userId,
+ })
+ .onConflictDoNothing()
+ .returning({ id: agentDocuments.id });
+
+ return { id: result?.id };
+ });
}
+ /**
+ * Creates a document row and links it to an agent in one transaction.
+ *
+ * Use when:
+ * - Creating ordinary agent-visible VFS files or folders.
+ * - Creating model-owned documents that still need agent document policy metadata.
+ *
+ * Expects:
+ * - `filename` is a single VFS segment supplied by the caller.
+ * - `uniqueSibling` defaults to `true` for ordinary VFS documents.
+ *
+ * Returns:
+ * - The created agent document with joined document content and metadata.
+ *
+ * NOTICE:
+ * Pass `uniqueSibling: false` only for managed mount documents whose storage filename can
+ * intentionally collide with ordinary-looking names outside the ordinary VFS resolver.
+ */
async create(
agentId: string,
filename: string,
@@ -134,22 +296,27 @@ export class AgentDocumentModel {
params?: {
createdAt?: Date;
editorData?: Record<string, any>;
+ fileType?: string;
loadPosition?: DocumentLoadPosition;
loadRules?: DocumentLoadRules;
metadata?: Record<string, any>;
+ parentId?: string | null;
policy?: AgentDocumentPolicy;
policyLoad?: PolicyLoad;
templateId?: string;
title?: string;
updatedAt?: Date;
- },
+ } & AgentDocumentSiblingUniquenessOptions,
): Promise<AgentDocument> {
const {
createdAt,
editorData,
+ uniqueSibling = true,
+ fileType = 'agent/document',
loadPosition,
loadRules,
metadata,
+ parentId,
policy,
policyLoad,
templateId,
@@ -162,13 +329,22 @@ export class AgentDocumentModel {
const normalizedPolicy = normalizePolicy(loadPosition, loadRules, policy);
return this.db.transaction(async (trx) => {
+ if (uniqueSibling) {
+ await this.assertNoLiveSiblingConflict(trx, {
+ agentId,
+ filename,
+ parentId: parentId ?? null,
+ });
+ }
+
const documentPayload: NewDocument = {
content,
createdAt,
description: metadata?.description,
editorData,
- fileType: 'agent/document',
+ fileType,
filename,
+ parentId,
metadata,
source: `agent-document://${agentId}/${encodeURIComponent(filename)}`,
sourceType: 'file',
@@ -295,7 +471,29 @@ export class AgentDocumentModel {
});
}
- async rename(documentId: string, newTitle: string): Promise<AgentDocument | undefined> {
+ /**
+ * Renames an agent document by updating the backing document filename and title.
+ *
+ * Use when:
+ * - A caller wants title-style rename behavior.
+ * - The document should keep its binding, content, policy, and document identity.
+ *
+ * Expects:
+ * - `newTitle` is a human-readable title that can be normalized into a filename.
+ * - `uniqueSibling` defaults to `true` for ordinary VFS documents.
+ *
+ * Returns:
+ * - The renamed agent document, or `undefined` when the binding is not visible.
+ *
+ * NOTICE:
+ * Pass `uniqueSibling: false` only for managed mount documents whose provider owns collision
+ * handling outside the ordinary document VFS tree.
+ */
+ async rename(
+ documentId: string,
+ newTitle: string,
+ options: AgentDocumentSiblingUniquenessOptions = {},
+ ): Promise<AgentDocument | undefined> {
const existing = await this.findById(documentId);
if (!existing) return undefined;
@@ -304,15 +502,83 @@ export class AgentDocumentModel {
const filename = buildDocumentFilename(title);
const source = `agent-document://${existing.agentId}/${encodeURIComponent(filename)}`;
+ const { uniqueSibling = true } = options;
- await this.db
- .update(documents)
- .set({
- filename,
- source,
- title,
- })
- .where(and(eq(documents.id, existing.documentId), eq(documents.userId, this.userId)));
+ await this.db.transaction(async (trx) => {
+ if (uniqueSibling) {
+ await this.assertNoLiveSiblingConflict(trx, {
+ agentId: existing.agentId,
+ excludeAgentDocumentId: existing.id,
+ filename,
+ parentId: existing.parentId,
+ });
+ }
+
+ await trx
+ .update(documents)
+ .set({
+ filename,
+ source,
+ title,
+ })
+ .where(and(eq(documents.id, existing.documentId), eq(documents.userId, this.userId)));
+ });
+
+ return this.findById(documentId);
+ }
+
+ /**
+ * Moves or renames an agent document without changing its binding or document identity.
+ *
+ * Use when:
+ * - VFS `rename(from, to)` needs filesystem-style metadata mutation
+ * - Callers must preserve document id, agent document id, policy, history, and load settings
+ *
+ * Expects:
+ * - `filename` is already validated as a single VFS path segment
+ * - `parentId` points to a document row owned by the same user, or `null` for root
+ * - `uniqueSibling` defaults to `true` for ordinary VFS documents
+ *
+ * Returns:
+ * - The same agent document binding after the backing document row is moved
+ *
+ * NOTICE:
+ * Pass `uniqueSibling: false` only for managed mount documents whose provider owns collision
+ * handling outside the ordinary document VFS tree.
+ */
+ async movePath(
+ documentId: string,
+ params: { filename: string; parentId: string | null } & AgentDocumentSiblingUniquenessOptions,
+ ): Promise<AgentDocument | undefined> {
+ const existing = await this.findById(documentId);
+ if (!existing) return undefined;
+
+ const filename = params.filename.trim();
+ if (!filename) return existing;
+
+ const source = `agent-document://${existing.agentId}/${encodeURIComponent(filename)}`;
+ const { uniqueSibling = true } = params;
+
+ await this.db.transaction(async (trx) => {
+ if (uniqueSibling) {
+ await this.assertNoLiveSiblingConflict(trx, {
+ agentId: existing.agentId,
+ excludeAgentDocumentId: existing.id,
+ filename,
+ parentId: params.parentId,
+ });
+ }
+
+ await trx
+ .update(documents)
+ .set({
+ filename,
+ parentId: params.parentId,
+ source,
+ title: filename,
+ })
+ .where(and(eq(documents.id, existing.documentId), eq(documents.userId, this.userId)));
+ });
return this.findById(documentId);
}
@@ -367,7 +633,17 @@ export class AgentDocumentModel {
return this.findById(documentId);
}
- async findById(documentId: string): Promise<AgentDocument | undefined> {
+ async findById(
+ documentId: string,
+ options?: AgentDocumentQueryOptions,
+ ): Promise<AgentDocument | undefined> {
+ return this.findByIdWithOptions(documentId, options);
+ }
+
+ async findByIdWithOptions(
+ documentId: string,
+ options?: AgentDocumentQueryOptions,
+ ): Promise<AgentDocument | undefined> {
const [result] = await this.db
.select({ doc: documents, settings: agentDocuments })
.from(agentDocuments)
@@ -376,7 +652,7 @@ export class AgentDocumentModel {
and(
eq(agentDocuments.id, documentId),
eq(agentDocuments.userId, this.userId),
- isNull(agentDocuments.deletedAt),
+ ...this.buildDeletedAtFilters(options),
),
)
.limit(1);
@@ -386,6 +662,24 @@ export class AgentDocumentModel {
return this.toAgentDocument(result.settings, result.doc);
}
+ /**
+ * Updates an existing document by filename or creates a new one when missing.
+ *
+ * Use when:
+ * - Callers want idempotent writes keyed by agent and filename.
+ * - Existing document policy and metadata should be merged on update.
+ *
+ * Expects:
+ * - `filename` addresses the current agent's ordinary filename lookup.
+ * - `uniqueSibling` is forwarded only to the create path and defaults to `true` there.
+ *
+ * Returns:
+ * - The updated or created agent document.
+ *
+ * NOTICE:
+ * Pass `uniqueSibling: false` only when the create path is creating managed mount documents
+ * whose visible uniqueness is enforced by a provider-specific resolver.
+ */
async upsert(
agentId: string,
filename: string,
@@ -400,11 +694,12 @@ export class AgentDocumentModel {
policyLoad?: PolicyLoad;
templateId?: string;
updatedAt?: Date;
- },
+ } & AgentDocumentSiblingUniquenessOptions,
): Promise<AgentDocument> {
const {
createdAt,
editorData,
+ uniqueSibling,
loadPosition,
loadRules,
metadata,
@@ -439,6 +734,7 @@ export class AgentDocumentModel {
return this.create(agentId, filename, content, {
createdAt,
editorData,
+ uniqueSibling,
loadPosition,
loadRules,
metadata,
@@ -541,7 +837,11 @@ export class AgentDocumentModel {
});
}
- async findByFilename(agentId: string, filename: string): Promise<AgentDocument | undefined> {
+ async findByFilename(
+ agentId: string,
+ filename: string,
+ options?: AgentDocumentQueryOptions,
+ ): Promise<AgentDocument | undefined> {
const [result] = await this.db
.select({ doc: documents, settings: agentDocuments })
.from(agentDocuments)
@@ -551,7 +851,34 @@ export class AgentDocumentModel {
eq(agentDocuments.userId, this.userId),
eq(agentDocuments.agentId, agentId),
eq(documents.filename, filename),
- isNull(agentDocuments.deletedAt),
+ ...this.buildDeletedAtFilters(options),
+ ),
+ )
+ .orderBy(desc(agentDocuments.updatedAt))
+ .limit(1);
+
+ if (!result) return undefined;
+
+ return this.toAgentDocument(result.settings, result.doc);
+ }
+
+ async findByParentAndFilename(
+ agentId: string,
+ parentId: string | null,
+ filename: string,
+ options?: AgentDocumentQueryOptions,
+ ): Promise<AgentDocument | undefined> {
+ const [result] = await this.db
+ .select({ doc: documents, settings: agentDocuments })
+ .from(agentDocuments)
+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ eq(agentDocuments.agentId, agentId),
+ eq(documents.filename, filename),
+ parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),
+ ...this.buildDeletedAtFilters(options),
),
)
.orderBy(desc(agentDocuments.updatedAt))
@@ -562,6 +889,137 @@ export class AgentDocumentModel {
return this.toAgentDocument(result.settings, result.doc);
}
+ /**
+ * Lists agent document bindings that share one tree segment.
+ *
+ * Use when:
+ * - VFS callers need to reject ambiguous sibling paths before create, write, or restore
+ * - Migration checks need to detect duplicate `parentId + filename` rows
+ *
+ * Expects:
+ * - `parentId` is the canonical document row parent id, not the agent document id
+ *
+ * Returns:
+ * - Matching bindings ordered newest first, optionally capped for conflict probes
+ */
+ async listByParentAndFilename(
+ agentId: string,
+ parentId: string | null,
+ filename: string,
+ options?: AgentDocumentQueryOptions,
+ ): Promise<AgentDocument[]> {
+ const results = await this.db
+ .select({ doc: documents, settings: agentDocuments })
+ .from(agentDocuments)
+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ eq(agentDocuments.agentId, agentId),
+ eq(documents.filename, filename),
+ parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),
+ ...this.buildDeletedAtFilters(options),
+ ),
+ )
+ .orderBy(desc(agentDocuments.updatedAt))
+ .limit(options?.limit ?? 9999)
+ .offset(this.normalizeListOffset(options?.cursor));
+
+ return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));
+ }
+
+ async findByDocumentId(
+ agentId: string,
+ documentId: string,
+ options?: AgentDocumentQueryOptions,
+ ): Promise<AgentDocument | undefined> {
+ const [result] = await this.db
+ .select({ doc: documents, settings: agentDocuments })
+ .from(agentDocuments)
+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ eq(agentDocuments.agentId, agentId),
+ eq(agentDocuments.documentId, documentId),
+ ...this.buildDeletedAtFilters(options),
+ ),
+ )
+ .orderBy(desc(agentDocuments.updatedAt))
+ .limit(1);
+
+ if (!result) return undefined;
+
+ return this.toAgentDocument(result.settings, result.doc);
+ }
+
+ async listByParent(
+ agentId: string,
+ parentId: string | null,
+ options?: AgentDocumentQueryOptions,
+ ): Promise<AgentDocument[]> {
+ const results = await this.db
+ .select({ doc: documents, settings: agentDocuments })
+ .from(agentDocuments)
+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ eq(agentDocuments.agentId, agentId),
+ parentId ? eq(documents.parentId, parentId) : isNull(documents.parentId),
+ ...this.buildDeletedAtFilters(options),
+ ),
+ )
+ .orderBy(desc(agentDocuments.updatedAt))
+ .limit(options?.limit ?? 9999)
+ .offset(this.normalizeListOffset(options?.cursor));
+
+ return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));
+ }
+
+ async listDeletedByAgent(agentId: string): Promise<AgentDocument[]> {
+ const results = await this.db
+ .select({ doc: documents, settings: agentDocuments })
+ .from(agentDocuments)
+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ eq(agentDocuments.agentId, agentId),
+ eq(documents.userId, this.userId),
+ isNotNull(agentDocuments.deletedAt),
+ ),
+ )
+ .orderBy(desc(agentDocuments.deletedAt), desc(agentDocuments.updatedAt));
+
+ return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));
+ }
+
+ async listSubtreeByDocumentId(
+ agentId: string,
+ rootDocumentId: string,
+ options?: AgentDocumentQueryOptions,
+ ): Promise<AgentDocument[]> {
+ const root = await this.findByDocumentId(agentId, rootDocumentId, options);
+
+ if (!root) return [];
+
+ const subtree = [root];
+ const pendingParentIds = [root.documentId];
+
+ while (pendingParentIds.length > 0) {
+ const parentIds = pendingParentIds.splice(0, pendingParentIds.length);
+ const children = await this.listByParentIds(agentId, parentIds, options);
+
+ for (const child of children) {
+ subtree.push(child);
+ pendingParentIds.push(child.documentId);
+ }
+ }
+
+ return subtree;
+ }
+
async delete(documentId: string, deleteReason?: string): Promise<void> {
// Soft delete only: mark deleted metadata and stop autoload.
// We intentionally keep both agent_documents row and linked documents row for recovery.
@@ -583,6 +1041,155 @@ export class AgentDocumentModel {
);
}
+ async deleteSubtreeByDocumentId(
+ agentId: string,
+ rootDocumentId: string,
+ deleteReason?: string,
+ ): Promise<void> {
+ const subtree = await this.listSubtreeByDocumentId(agentId, rootDocumentId);
+
+ if (subtree.length === 0) return;
+
+ await this.db
+ .update(agentDocuments)
+ .set({
+ policyLoad: PolicyLoad.DISABLED,
+ deleteReason,
+ deletedAt: new Date(),
+ deletedByAgentId: null,
+ deletedByUserId: this.userId,
+ })
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ inArray(
+ agentDocuments.id,
+ subtree.map((item) => item.id),
+ ),
+ isNull(agentDocuments.deletedAt),
+ ),
+ );
+ }
+
+ /**
+ * Restores a soft-deleted agent document binding to the live tree.
+ *
+ * Use when:
+ * - Moving a deleted document back into active VFS visibility.
+ * - Preserving the existing document row and agent document id.
+ *
+ * Expects:
+ * - `documentId` may refer to a deleted binding owned by the current user.
+ * - `uniqueSibling` defaults to `true` for ordinary VFS documents.
+ *
+ * Returns:
+ * - Nothing; missing bindings are ignored.
+ *
+ * NOTICE:
+ * Pass `uniqueSibling: false` only for managed mount documents whose provider owns restore
+ * collision handling outside the ordinary document VFS tree.
+ */
+ async restore(
+ documentId: string,
+ options: AgentDocumentSiblingUniquenessOptions = {},
+ ): Promise<void> {
+ const existing = await this.findByIdWithOptions(documentId, { includeDeleted: true });
+
+ if (!existing) return;
+ const { uniqueSibling = true } = options;
+
+ await this.db.transaction(async (trx) => {
+ if (uniqueSibling) {
+ await this.assertNoLiveSiblingConflict(trx, {
+ agentId: existing.agentId,
+ excludeAgentDocumentId: existing.id,
+ filename: existing.filename,
+ parentId: existing.parentId,
+ });
+ }
+
+ await trx
+ .update(agentDocuments)
+ .set({
+ deleteReason: null,
+ deletedAt: null,
+ deletedByAgentId: null,
+ deletedByUserId: null,
+ policyLoad: PolicyLoad.PROGRESSIVE,
+ })
+ .where(and(eq(agentDocuments.id, documentId), eq(agentDocuments.userId, this.userId)));
+ });
+ }
+
+ async restoreSubtreeByDocumentId(agentId: string, rootDocumentId: string): Promise<void> {
+ const subtree = await this.listSubtreeByDocumentId(agentId, rootDocumentId, {
+ includeDeleted: true,
+ });
+
+ if (subtree.length === 0) return;
+
+ await this.db
+ .update(agentDocuments)
+ .set({
+ deleteReason: null,
+ deletedAt: null,
+ deletedByAgentId: null,
+ deletedByUserId: null,
+ policyLoad: PolicyLoad.PROGRESSIVE,
+ })
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ inArray(
+ agentDocuments.id,
+ subtree.map((item) => item.id),
+ ),
+ ),
+ );
+ }
+
+ async permanentlyDelete(documentId: string): Promise<void> {
+ const existing = await this.findByIdWithOptions(documentId, { includeDeleted: true });
+
+ if (!existing) return;
+
+ await this.db.transaction(async (trx) => {
+ await trx
+ .delete(agentDocuments)
+ .where(and(eq(agentDocuments.id, documentId), eq(agentDocuments.userId, this.userId)));
+
+ await trx
+ .delete(documents)
+ .where(and(eq(documents.id, existing.documentId), eq(documents.userId, this.userId)));
+ });
+ }
+
+ async permanentlyDeleteSubtreeByDocumentId(
+ agentId: string,
+ rootDocumentId: string,
+ ): Promise<void> {
+ const subtree = await this.listSubtreeByDocumentId(agentId, rootDocumentId, {
+ includeDeleted: true,
+ });
+
+ if (subtree.length === 0) return;
+
+ const agentDocumentIds = subtree.map((item) => item.id);
+ const documentIds = subtree.map((item) => item.documentId);
+
+ await this.db.transaction(async (trx) => {
+ await trx
+ .delete(agentDocuments)
+ .where(
+ and(eq(agentDocuments.userId, this.userId), inArray(agentDocuments.id, agentDocumentIds)),
+ );
+
+ await trx
+ .delete(documents)
+ .where(and(eq(documents.userId, this.userId), inArray(documents.id, documentIds)));
+ });
+ }
+
async deleteByAgent(agentId: string, deleteReason?: string): Promise<void> {
await this.db
.update(agentDocuments)
diff --git a/packages/database/src/models/agentDocuments/types.ts b/packages/database/src/models/agentDocuments/types.ts
index cb235055482..2ec3eea45b8 100644
--- a/packages/database/src/models/agentDocuments/types.ts
+++ b/packages/database/src/models/agentDocuments/types.ts
@@ -39,8 +39,10 @@ export interface AgentDocument {
documentId: string;
editorData: Record<string, any> | null;
filename: string;
+ fileType: string;
id: string;
metadata: Record<string, any> | null;
+ parentId: string | null;
policy: AgentDocumentPolicy | null;
policyLoad: PolicyLoad;
policyLoadFormat: DocumentLoadFormat;
diff --git a/packages/database/src/models/userMemory/model.ts b/packages/database/src/models/userMemory/model.ts
index 886338e2db8..34fdf1e0d7d 100644
--- a/packages/database/src/models/userMemory/model.ts
+++ b/packages/database/src/models/userMemory/model.ts
@@ -83,6 +83,48 @@ const coerceDate = (input: unknown): Date | null => {
return null;
};
+const escapeLikePattern = (value: string) =>
+ value.replaceAll('\\', '\\\\').replaceAll('%', '\\%').replaceAll('_', '\\_');
+
+const buildContainsCondition = (column: unknown, q?: string) => {
+ const normalized = q?.trim();
+ if (!normalized) return undefined;
+
+ return sql<boolean>`${column} ILIKE ${`%${escapeLikePattern(normalized)}%`} ESCAPE '\\'`;
+};
+
+const isPGliteDatabase = (db: LobeChatDatabase) => {
+ const client = (
+ db as unknown as {
+ $client?: {
+ dataDir?: unknown;
+ waitReady?: unknown;
+ };
+ }
+ ).$client;
+
+ return 'waitReady' in (client ?? {}) && 'dataDir' in (client ?? {});
+};
+
+const buildTextSearchCondition = (params: {
+ bm25Query: string;
+ columns: unknown[];
+ normalizedQuery: string;
+ supportsBm25: boolean;
+}) => {
+ const { bm25Query, columns, normalizedQuery, supportsBm25 } = params;
+
+ if (!normalizedQuery) return undefined;
+
+ const conditions = supportsBm25
+ ? columns.map((column) => sql<boolean>`${column} @@@ ${bm25Query}`)
+ : columns
+ .map((column) => buildContainsCondition(column, normalizedQuery))
+ .filter((condition): condition is SQL<boolean> => Boolean(condition));
+
+ return conditions.length > 0 ? or(...conditions) : undefined;
+};
+
const parseAssociationExtra = (
value: string | null | undefined,
): Record<string, unknown> | null => {
@@ -903,6 +945,24 @@ export class UserMemoryModel {
const bm25Query = normalizedQuery
? sanitizeBm25Query(normalizedQuery, SAFE_BM25_QUERY_OPTIONS)
: '';
+ // NOTICE:
+ // Why this workaround is needed.
+ // PGlite-based tests do not provide ParadeDB `pg_search`, so BM25 `@@@`
+ // operators fail during local/test execution.
+ //
+ // Root cause summary.
+ // `getTestDB.ts` intentionally skips migrations containing `pg_search` or
+ // `bm25` for PGlite compatibility, which means lexical search paths in this
+ // model cannot rely on BM25 there.
+ //
+ // Source/context.
+ // See `packages/database/src/core/getTestDB.ts` where those migration
+ // statements are filtered out before executing test migrations.
+ //
+ // Removal condition.
+ // Remove this fallback once the test database can execute the same BM25
+ // operators/indexes as the production PostgreSQL environment.
+ const supportsBm25 = !isPGliteDatabase(this.db);
const conditions: Array<SQL | undefined> = [
eq(userMemories.userId, this.userId),
@@ -969,9 +1029,19 @@ export class UserMemoryModel {
const contextFilters: Array<SQL | undefined> = [
whereClause,
- normalizedQuery
- ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesContexts.title} @@@ ${bm25Query} OR ${userMemoriesContexts.description} @@@ ${bm25Query} OR ${userMemoriesContexts.currentStatus} @@@ ${bm25Query})`
- : undefined,
+ buildTextSearchCondition({
+ bm25Query,
+ columns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ userMemoriesContexts.title,
+ userMemoriesContexts.description,
+ userMemoriesContexts.currentStatus,
+ ],
+ normalizedQuery,
+ supportsBm25,
+ }),
types && types.length > 0 ? inArray(userMemoriesContexts.type, types) : undefined,
tags && tags.length > 0
? or(
@@ -1058,9 +1128,19 @@ export class UserMemoryModel {
const activityFilters: Array<SQL | undefined> = [
whereClause,
- normalizedQuery
- ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesActivities.narrative} @@@ ${bm25Query} OR ${userMemoriesActivities.notes} @@@ ${bm25Query} OR ${userMemoriesActivities.feedback} @@@ ${bm25Query})`
- : undefined,
+ buildTextSearchCondition({
+ bm25Query,
+ columns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ userMemoriesActivities.narrative,
+ userMemoriesActivities.notes,
+ userMemoriesActivities.feedback,
+ ],
+ normalizedQuery,
+ supportsBm25,
+ }),
types && types.length > 0 ? inArray(userMemoriesActivities.type, types) : undefined,
status && status.length > 0 ? inArray(userMemoriesActivities.status, status) : undefined,
tags && tags.length > 0
@@ -1155,9 +1235,19 @@ export class UserMemoryModel {
const experienceFilters: Array<SQL | undefined> = [
whereClause,
- normalizedQuery
- ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesExperiences.situation} @@@ ${bm25Query} OR ${userMemoriesExperiences.keyLearning} @@@ ${bm25Query} OR ${userMemoriesExperiences.action} @@@ ${bm25Query})`
- : undefined,
+ buildTextSearchCondition({
+ bm25Query,
+ columns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ userMemoriesExperiences.situation,
+ userMemoriesExperiences.keyLearning,
+ userMemoriesExperiences.action,
+ ],
+ normalizedQuery,
+ supportsBm25,
+ }),
types && types.length > 0 ? inArray(userMemoriesExperiences.type, types) : undefined,
tags && tags.length > 0
? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesExperiences.tags})`))
@@ -1232,9 +1322,18 @@ export class UserMemoryModel {
const identityFilters: Array<SQL | undefined> = [
whereClause,
- normalizedQuery
- ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesIdentities.description} @@@ ${bm25Query} OR ${userMemoriesIdentities.role} @@@ ${bm25Query})`
- : undefined,
+ buildTextSearchCondition({
+ bm25Query,
+ columns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ userMemoriesIdentities.description,
+ userMemoriesIdentities.role,
+ ],
+ normalizedQuery,
+ supportsBm25,
+ }),
types && types.length > 0 ? inArray(userMemoriesIdentities.type, types) : undefined,
tags && tags.length > 0
? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesIdentities.tags})`))
@@ -1316,9 +1415,18 @@ export class UserMemoryModel {
const preferenceFilters: Array<SQL | undefined> = [
whereClause,
- normalizedQuery
- ? sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query} OR ${userMemoriesPreferences.conclusionDirectives} @@@ ${bm25Query} OR ${userMemoriesPreferences.suggestions} @@@ ${bm25Query})`
- : undefined,
+ buildTextSearchCondition({
+ bm25Query,
+ columns: [
+ userMemories.title,
+ userMemories.summary,
+ userMemories.details,
+ userMemoriesPreferences.conclusionDirectives,
+ userMemoriesPreferences.suggestions,
+ ],
+ normalizedQuery,
+ supportsBm25,
+ }),
types && types.length > 0 ? inArray(userMemoriesPreferences.type, types) : undefined,
tags && tags.length > 0
? or(...tags.map((tag) => sql<boolean>`${tag} = ANY(${userMemoriesPreferences.tags})`))
@@ -2533,7 +2641,7 @@ export class UserMemoryModel {
.select(selectNonVectorColumns(userMemoriesIdentities))
.from(userMemoriesIdentities)
.where(eq(userMemoriesIdentities.userId, this.userId))
- .orderBy(desc(userMemoriesIdentities.capturedAt));
+ .orderBy(desc(userMemoriesIdentities.capturedAt), desc(userMemoriesIdentities.createdAt));
return res;
};
@@ -2547,7 +2655,7 @@ export class UserMemoryModel {
.from(userMemoriesIdentities)
.innerJoin(userMemories, eq(userMemories.id, userMemoriesIdentities.userMemoryId))
.where(eq(userMemoriesIdentities.userId, this.userId))
- .orderBy(desc(userMemoriesIdentities.capturedAt));
+ .orderBy(desc(userMemoriesIdentities.capturedAt), desc(userMemoriesIdentities.createdAt));
return res;
};
@@ -2559,7 +2667,7 @@ export class UserMemoryModel {
.where(
and(eq(userMemoriesIdentities.userId, this.userId), eq(userMemoriesIdentities.type, type)),
)
- .orderBy(desc(userMemoriesIdentities.capturedAt));
+ .orderBy(desc(userMemoriesIdentities.capturedAt), desc(userMemoriesIdentities.createdAt));
return res;
};
diff --git a/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts b/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts
new file mode 100644
index 00000000000..626c5561518
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts
@@ -0,0 +1,121 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentDocumentModel } from '@/database/models/agentDocuments';
+
+import { agentDocumentRouter } from '../../agentDocument';
+import { cleanupTestUser, createTestAgent, createTestContext, createTestUser } from './setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+vi.mock('@/server/services/skill/resource', () => ({
+ SkillResourceService: vi.fn().mockImplementation(() => ({
+ listResources: vi.fn().mockResolvedValue([]),
+ readResource: vi.fn().mockRejectedValue(new Error('Resource not found')),
+ storeResources: vi.fn().mockResolvedValue({}),
+ })),
+}));
+
+describe('AgentDocument VFS Router Integration Tests', () => {
+ let agentDocumentModel: AgentDocumentModel;
+ let agentId: string;
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ agentId = await createTestAgent(serverDB, userId);
+ agentDocumentModel = new AgentDocumentModel(serverDB, userId);
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ });
+
+ it('lists ordinary root documents and synthetic mounts through listDocumentsByPath', async () => {
+ await agentDocumentModel.create(agentId, 'SOUL.md', '# Soul');
+
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const nodes = await caller.listDocumentsByPath({ agentId, path: './' });
+
+ expect(nodes).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ mount: expect.objectContaining({ driver: 'agent-documents' }),
+ name: 'SOUL.md',
+ path: './SOUL.md',
+ type: 'file',
+ }),
+ expect.objectContaining({
+ mount: expect.objectContaining({ driver: 'synthetic' }),
+ name: 'lobe',
+ path: './lobe',
+ type: 'directory',
+ }),
+ ]),
+ );
+ });
+
+ it('stats and reads ordinary documents through VFS path APIs', async () => {
+ await agentDocumentModel.create(agentId, 'SOUL.md', '# Soul');
+
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const stat = await caller.statDocumentByPath({ agentId, path: './SOUL.md' });
+ const read = await caller.readDocumentByPath({ agentId, path: './SOUL.md' });
+
+ expect(stat).toEqual(
+ expect.objectContaining({
+ mount: expect.objectContaining({ driver: 'agent-documents' }),
+ path: './SOUL.md',
+ type: 'file',
+ }),
+ );
+ expect(read).toEqual(
+ expect.objectContaining({
+ content: '# Soul',
+ path: './SOUL.md',
+ }),
+ );
+ });
+
+ it('stats mounted agent skills through unified ./lobe paths', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+
+ await caller.writeDocumentByPath({
+ agentId,
+ content: '# Router Skill',
+ path: './lobe/skills/agent/skills/router-skill/SKILL.md',
+ });
+
+ const stat = await caller.statDocumentByPath({
+ agentId,
+ path: './lobe/skills/agent/skills/router-skill/SKILL.md',
+ });
+
+ expect(stat).toEqual(
+ expect.objectContaining({
+ mount: expect.objectContaining({ driver: 'skills', namespace: 'agent' }),
+ path: './lobe/skills/agent/skills/router-skill/SKILL.md',
+ type: 'file',
+ }),
+ );
+
+ const read = await caller.readDocumentByPath({
+ agentId,
+ path: './lobe/skills/agent/skills/router-skill/SKILL.md',
+ });
+
+ if (!read) {
+ throw new Error('Expected readDocumentByPath to return the router skill file content');
+ }
+
+ expect(read.content).toContain('# Router Skill');
+ });
+});
diff --git a/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts b/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts
index 40152c64967..f5661e67309 100644
--- a/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts
+++ b/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts
@@ -4,8 +4,17 @@ import { agentSkills } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { AgentDocumentModel } from '@/database/models/agentDocuments';
+
+import { agentDocumentRouter } from '../../agentDocument';
import { agentSkillsRouter } from '../../agentSkills';
-import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+import {
+ cleanupTestUser,
+ createTestAgent,
+ createTestContext,
+ createTestTopic,
+ createTestUser,
+} from './setup';
// Mock getServerDB to return our test database instance
let testDB: LobeChatDatabase;
@@ -83,18 +92,47 @@ vi.stubGlobal('fetch', mockFetch);
describe('Skill Router Integration Tests', () => {
let serverDB: LobeChatDatabase;
+ let agentDocumentModel: AgentDocumentModel;
let userId: string;
beforeEach(async () => {
serverDB = await getTestDB();
testDB = serverDB;
userId = await createTestUser(serverDB);
+ agentDocumentModel = new AgentDocumentModel(serverDB, userId);
});
afterEach(async () => {
await cleanupTestUser(serverDB, userId);
});
+ const getManagedSkillBindingId = async ({
+ agentId,
+ namespace,
+ skillName,
+ topicId,
+ }: {
+ agentId: string;
+ namespace: 'agent' | 'agent-topic';
+ skillName: string;
+ topicId?: string;
+ }) => {
+ const documents = await agentDocumentModel.findByAgent(agentId);
+ const document = documents.find(
+ (item) =>
+ item.filename === 'SKILL.md' &&
+ item.metadata?.lobeSkill?.namespace === namespace &&
+ item.metadata?.lobeSkill?.skillName === skillName &&
+ item.metadata?.lobeSkill?.topicId === topicId,
+ );
+
+ if (!document) {
+ throw new Error(`Expected managed skill document ${namespace}:${skillName} to exist`);
+ }
+
+ return document.id;
+ };
+
describe('create', () => {
it('should create a new skill', async () => {
const caller = agentSkillsRouter.createCaller(createTestContext(userId));
@@ -434,6 +472,340 @@ describe('Skill Router Integration Tests', () => {
});
});
+ describe('VFS write APIs', () => {
+ it('should create an agent skill through the VFS API', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ const result = await caller.createSkillByPath({
+ agentId,
+ content: '# Research Helper\n\nUse this skill for research.',
+ skillName: 'research-helper',
+ targetNamespace: 'agent',
+ });
+
+ if (!result) {
+ throw new Error('Expected createSkill to return a skill file node');
+ }
+
+ expect(result.mount?.namespace).toBe('agent');
+ expect(result.path).toBe('./lobe/skills/agent/skills/research-helper/SKILL.md');
+
+ const fileNode = await caller.readDocumentByPath({
+ agentId,
+ path: './lobe/skills/agent/skills/research-helper/SKILL.md',
+ });
+
+ if (!fileNode) {
+ throw new Error('Expected created agent skill file to exist');
+ }
+
+ expect(fileNode.content?.trimEnd()).toBe('# Research Helper\n\nUse this skill for research.');
+ });
+
+ it('should create and update an agent-topic skill through the VFS API', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+ const topicId = await createTestTopic(serverDB, userId);
+
+ const created = await caller.createSkillByPath({
+ agentId,
+ content: '# Topic Draft\n\nInitial topic skill content.',
+ skillName: 'topic-draft',
+ targetNamespace: 'agent-topic',
+ topicId,
+ });
+
+ if (!created) {
+ throw new Error('Expected createSkill to return a topic skill file node');
+ }
+
+ const updated = await caller.updateSkillByPath({
+ agentId,
+ content: '# Topic Draft\n\nUpdated topic skill content.',
+ path: created.path,
+ topicId,
+ });
+
+ if (!updated) {
+ throw new Error('Expected updateSkill to return an updated topic skill file node');
+ }
+
+ expect(updated.mount?.namespace).toBe('agent-topic');
+
+ const updatedFile = await caller.readDocumentByPath({
+ agentId,
+ path: updated.path,
+ topicId,
+ });
+
+ if (!updatedFile) {
+ throw new Error('Expected readDocumentByPath to return the updated topic skill file');
+ }
+
+ expect(updatedFile.content?.trimEnd()).toBe('# Topic Draft\n\nUpdated topic skill content.');
+
+ const persistedFile = (await agentDocumentModel.findByAgent(agentId)).find(
+ (document) =>
+ document.filename === 'SKILL.md' &&
+ document.metadata?.lobeSkill?.namespace === 'agent-topic' &&
+ document.metadata?.lobeSkill?.skillName === 'topic-draft' &&
+ document.metadata?.lobeSkill?.topicId === topicId,
+ );
+
+ expect(persistedFile?.content.trimEnd()).toBe(
+ '# Topic Draft\n\nUpdated topic skill content.',
+ );
+ });
+
+ it('should delete an agent skill through the VFS API', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ const created = await caller.createSkillByPath({
+ agentId,
+ content: '# Disposable Skill\n\nTemporary content.',
+ skillName: 'disposable-skill',
+ targetNamespace: 'agent',
+ });
+
+ if (!created) {
+ throw new Error('Expected createSkill to return a disposable skill file node');
+ }
+
+ await caller.deleteSkillByPath({
+ agentId,
+ path: created.path,
+ });
+
+ await expect(
+ caller.readDocumentByPath({
+ agentId,
+ path: created.path,
+ }),
+ ).rejects.toThrow();
+ });
+
+ it('should promote an agent-topic skill into the agent namespace', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+ const topicId = await createTestTopic(serverDB, userId);
+
+ const created = await caller.createSkillByPath({
+ agentId,
+ content: '# Topic Specialist\n\nPromote this skill.',
+ skillName: 'topic-specialist',
+ targetNamespace: 'agent-topic',
+ topicId,
+ });
+
+ if (!created) {
+ throw new Error('Expected createSkill to return a promotable topic skill file node');
+ }
+
+ const promoted = await caller.promoteSkillByPath({
+ agentId,
+ path: created.path,
+ targetName: 'agent-specialist',
+ topicId,
+ });
+
+ if (!promoted) {
+ throw new Error('Expected promoteSkill to return a promoted skill file node');
+ }
+
+ expect(promoted.mount?.namespace).toBe('agent');
+ expect(promoted.path).toBe('./lobe/skills/agent/skills/agent-specialist/SKILL.md');
+
+ const promotedFile = await caller.readDocumentByPath({ agentId, path: promoted.path });
+
+ if (!promotedFile) {
+ throw new Error('Expected promoted agent skill file to exist');
+ }
+
+ expect(promotedFile.content?.trimEnd()).toBe('# Topic Specialist\n\nPromote this skill.');
+ });
+
+ it('should surface CONFLICT when creating a duplicate VFS skill', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ await caller.createSkillByPath({
+ agentId,
+ content: '# Research Helper\n\nUse this skill for research.',
+ skillName: 'research-helper',
+ targetNamespace: 'agent',
+ });
+
+ await expect(
+ caller.createSkillByPath({
+ agentId,
+ content: '# Research Helper\n\nDuplicate content.',
+ skillName: 'research-helper',
+ targetNamespace: 'agent',
+ }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('should surface NOT_FOUND when deleting a missing VFS skill', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ await expect(
+ caller.deleteSkillByPath({
+ agentId,
+ path: './lobe/skills/agent/skills/missing-skill/SKILL.md',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('should surface METHOD_NOT_SUPPORTED when promoting from a non-promotable namespace', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ const created = await caller.createSkillByPath({
+ agentId,
+ content: '# Local Skill\n\nNo promote support.',
+ skillName: 'local-skill',
+ targetNamespace: 'agent',
+ });
+
+ if (!created) {
+ throw new Error('Expected createSkill to return a local skill file node');
+ }
+
+ await expect(
+ caller.promoteSkillByPath({
+ agentId,
+ path: created.path,
+ topicId: 'topic-1',
+ }),
+ ).rejects.toMatchObject({ code: 'METHOD_NOT_SUPPORTED' });
+ });
+
+ it('should surface BAD_REQUEST for invalid skill names', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ await expect(
+ caller.createSkillByPath({
+ agentId,
+ content: '# Invalid',
+ skillName: 'bad/name',
+ targetNamespace: 'agent',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('should surface BAD_REQUEST when agent-topic skill creation is missing topicId', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ await expect(
+ caller.createSkillByPath({
+ agentId,
+ content: '# Topic Skill',
+ skillName: 'topic-skill',
+ targetNamespace: 'agent-topic',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('should surface BAD_REQUEST for invalid promote target names', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+ const topicId = await createTestTopic(serverDB, userId);
+
+ const created = await caller.createSkillByPath({
+ agentId,
+ content: '# Topic Specialist\n\nPromote this skill.',
+ skillName: 'topic-specialist',
+ targetNamespace: 'agent-topic',
+ topicId,
+ });
+
+ if (!created) {
+ throw new Error('Expected createSkill to return a promotable topic skill file node');
+ }
+
+ await expect(
+ caller.promoteSkillByPath({
+ agentId,
+ path: created.path,
+ targetName: 'bad/name',
+ topicId,
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('should surface BAD_REQUEST for unsupported VFS file paths on update', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ await expect(
+ caller.updateSkillByPath({
+ agentId,
+ content: '# Updated',
+ path: './lobe/skills/agent/skills/research-helper/notes.md',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('should surface METHOD_NOT_SUPPORTED when renaming a skill-managed document through agentDocument', async () => {
+ const skillCaller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const documentCaller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ await skillCaller.createSkillByPath({
+ agentId,
+ content: '# Research Helper\n\nUse this skill for research.',
+ skillName: 'research-helper',
+ targetNamespace: 'agent',
+ });
+
+ const id = await getManagedSkillBindingId({
+ agentId,
+ namespace: 'agent',
+ skillName: 'research-helper',
+ });
+
+ await expect(
+ documentCaller.renameDocument({
+ agentId,
+ id,
+ newTitle: 'Renamed Skill',
+ }),
+ ).rejects.toMatchObject({ code: 'METHOD_NOT_SUPPORTED' });
+ });
+
+ it('should surface METHOD_NOT_SUPPORTED when copying a skill-managed document through agentDocument', async () => {
+ const skillCaller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const documentCaller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const agentId = await createTestAgent(serverDB, userId);
+
+ await skillCaller.createSkillByPath({
+ agentId,
+ content: '# Research Helper\n\nUse this skill for research.',
+ skillName: 'research-helper',
+ targetNamespace: 'agent',
+ });
+
+ const id = await getManagedSkillBindingId({
+ agentId,
+ namespace: 'agent',
+ skillName: 'research-helper',
+ });
+
+ await expect(
+ documentCaller.copyDocument({
+ agentId,
+ id,
+ newTitle: 'Copied Skill',
+ }),
+ ).rejects.toMatchObject({ code: 'METHOD_NOT_SUPPORTED' });
+ });
+ });
+
describe('listResources', () => {
it('should return empty array for skill without resources', async () => {
const caller = agentSkillsRouter.createCaller(createTestContext(userId));
diff --git a/src/server/routers/lambda/agentDocument.ts b/src/server/routers/lambda/agentDocument.ts
index d1702319166..e5c0dff872c 100644
--- a/src/server/routers/lambda/agentDocument.ts
+++ b/src/server/routers/lambda/agentDocument.ts
@@ -3,6 +3,7 @@ import {
DocumentLoadFormat,
DocumentLoadRule,
} from '@lobechat/agent-templates';
+import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { AgentDocumentModel } from '@/database/models/agentDocuments';
@@ -11,10 +12,51 @@ import { TopicDocumentModel } from '@/database/models/topicDocument';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
+import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+import { getUnifiedSkillNamespaceRootPath } from '@/server/services/agentDocumentVfs/mounts/skills/path';
const MAX_METADATA_BYTES = 16 * 1024;
const MAX_RULE_REGEXP_LENGTH = 512;
+const agentDocumentVfsErrorToTRPCCode = (
+ code: AgentDocumentVfsError['code'],
+): 'BAD_REQUEST' | 'CONFLICT' | 'FORBIDDEN' | 'METHOD_NOT_SUPPORTED' | 'NOT_FOUND' => {
+ switch (code) {
+ case 'CONFLICT': {
+ return 'CONFLICT';
+ }
+ case 'FORBIDDEN': {
+ return 'FORBIDDEN';
+ }
+ case 'METHOD_NOT_SUPPORTED': {
+ return 'METHOD_NOT_SUPPORTED';
+ }
+ case 'NOT_FOUND': {
+ return 'NOT_FOUND';
+ }
+ default: {
+ return 'BAD_REQUEST';
+ }
+ }
+};
+
+const handleAgentDocumentVfsError = (error: unknown): never => {
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ if (error instanceof AgentDocumentVfsError) {
+ throw new TRPCError({
+ cause: error,
+ code: agentDocumentVfsErrorToTRPCCode(error.code),
+ message: error.message,
+ });
+ }
+
+ throw error;
+};
+
const metadataSchema = z
.record(z.string(), z.unknown())
.refine((value) => JSON.stringify(value).length <= MAX_METADATA_BYTES, {
@@ -33,6 +75,37 @@ const toolLoadRuleSchema = z.object({
});
const readFormatSchema = z.enum(['xml', 'markdown', 'both']).optional();
+const writeCreateModeSchema = z.enum(['always-new', 'if-missing', 'must-exist']).optional();
+const recursiveSchema = z.boolean().optional();
+const mountedSkillNamespaceSchema = z.enum(['agent', 'agent-topic']);
+
+const createMountedSkillSchema = z.object({
+ agentId: z.string(),
+ content: z.string(),
+ skillName: z.string().min(1),
+ targetNamespace: mountedSkillNamespaceSchema,
+ topicId: z.string().optional(),
+});
+
+const deleteMountedSkillSchema = z.object({
+ agentId: z.string(),
+ path: z.string(),
+ topicId: z.string().optional(),
+});
+
+const promoteMountedSkillSchema = z.object({
+ agentId: z.string(),
+ path: z.string(),
+ targetName: z.string().optional(),
+ topicId: z.string(),
+});
+
+const updateMountedSkillSchema = z.object({
+ agentId: z.string(),
+ content: z.string(),
+ path: z.string(),
+ topicId: z.string().optional(),
+});
const liteXMLOperationSchema = z.union([
z.object({
@@ -62,6 +135,7 @@ const agentDocumentProcedure = authedProcedure.use(serverDatabase).use(async (op
ctx: {
agentDocumentModel: new AgentDocumentModel(ctx.serverDB, ctx.userId),
agentDocumentService: new AgentDocumentsService(ctx.serverDB, ctx.userId),
+ agentDocumentVfsService: new AgentDocumentVfsService(ctx.serverDB, ctx.userId),
topicModel: new TopicModel(ctx.serverDB, ctx.userId),
topicDocumentModel: new TopicDocumentModel(ctx.serverDB, ctx.userId),
},
@@ -236,6 +310,37 @@ export const agentDocumentRouter = router({
return ctx.agentDocumentService.listDocuments(input.agentId);
}),
+ /**
+ * Tool-oriented: list documents by VFS path
+ */
+ listDocumentsByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ cursor: z.string().optional(),
+ limit: z.number().int().positive().max(500).optional(),
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.list(
+ input.path,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ {
+ cursor: input.cursor,
+ limit: input.limit,
+ },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
/**
* Tool-oriented: read document by filename
*/
@@ -253,6 +358,331 @@ export const agentDocumentRouter = router({
: ctx.agentDocumentService.getDocumentByFilename(input.agentId, input.filename);
}),
+ /**
+ * Tool-oriented: stat document by VFS path
+ */
+ statDocumentByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.stat(input.path, {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ /**
+ * Tool-oriented: read document by VFS path
+ */
+ readDocumentByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.read(input.path, {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ /**
+ * Tool-oriented: write document by VFS path
+ */
+ writeDocumentByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ content: z.string(),
+ createMode: writeCreateModeSchema,
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.write(
+ input.path,
+ input.content,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { createMode: input.createMode },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ createSkillByPath: agentDocumentProcedure
+ .input(createMountedSkillSchema)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const path = `${getUnifiedSkillNamespaceRootPath(input.targetNamespace)}/${input.skillName}`;
+
+ return await ctx.agentDocumentVfsService.write(
+ path,
+ input.content,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { createMode: 'always-new' },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ updateSkillByPath: agentDocumentProcedure
+ .input(updateMountedSkillSchema)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.write(
+ input.path,
+ input.content,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { createMode: 'must-exist' },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ deleteSkillByPath: agentDocumentProcedure
+ .input(deleteMountedSkillSchema)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await ctx.agentDocumentVfsService.delete(input.path, {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ promoteSkillByPath: agentDocumentProcedure
+ .input(promoteMountedSkillSchema)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.promoteSkill(
+ input.path,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { targetName: input.targetName },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ /**
+ * Tool-oriented: create a VFS directory
+ */
+ mkdirDocumentByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ path: z.string(),
+ recursive: recursiveSchema,
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.mkdir(
+ input.path,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { recursive: input.recursive },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ /**
+ * Tool-oriented: rename or move a VFS path
+ */
+ renameDocumentByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ force: z.boolean().optional(),
+ fromPath: z.string(),
+ toPath: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.rename(
+ input.fromPath,
+ input.toPath,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { overwrite: input.force },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ /**
+ * Tool-oriented: copy a VFS path
+ */
+ copyDocumentByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ force: z.boolean().optional(),
+ fromPath: z.string(),
+ toPath: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.copy(
+ input.fromPath,
+ input.toPath,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { overwrite: input.force },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ /**
+ * Tool-oriented: soft-delete a VFS path
+ */
+ deleteDocumentByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ force: z.boolean().optional(),
+ path: z.string(),
+ recursive: recursiveSchema,
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await ctx.agentDocumentVfsService.delete(
+ input.path,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { recursive: input.recursive },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ /**
+ * Tool-oriented: list agent-scoped trash entries
+ */
+ listTrashDocumentsByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ path: z.string().optional(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.listTrash(
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ input.path,
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ /**
+ * Tool-oriented: restore a trash entry
+ */
+ restoreDocumentFromTrashByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.restoreFromTrashByPath(input.path, {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
+ /**
+ * Tool-oriented: permanently remove a trash entry
+ */
+ deleteDocumentPermanentlyByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ force: z.boolean().optional(),
+ path: z.string(),
+ recursive: recursiveSchema,
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await ctx.agentDocumentVfsService.deletePermanentlyByPath(input.path, {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+
/**
* Tool-oriented: upsert document by filename
*/
@@ -303,7 +733,7 @@ export const agentDocumentRouter = router({
/**
* Create an agent document and associate it with a topic in one call.
- * Used by the topic → page flow to replace the legacy notebook entry point.
+ * Used by the topic → page flow to create an agent document.
*/
createForTopic: agentDocumentProcedure
.input(
@@ -405,7 +835,15 @@ export const agentDocumentRouter = router({
}),
)
.mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.copyDocumentById(input.id, input.newTitle, input.agentId);
+ try {
+ return await ctx.agentDocumentService.copyDocumentById(
+ input.id,
+ input.newTitle,
+ input.agentId,
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
}),
/**
@@ -420,7 +858,15 @@ export const agentDocumentRouter = router({
}),
)
.mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.renameDocumentById(input.id, input.newTitle, input.agentId);
+ try {
+ return await ctx.agentDocumentService.renameDocumentById(
+ input.id,
+ input.newTitle,
+ input.agentId,
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
}),
/**
diff --git a/src/server/routers/lambda/agentSkills.ts b/src/server/routers/lambda/agentSkills.ts
index 0c3e476da1d..7d5720b010c 100644
--- a/src/server/routers/lambda/agentSkills.ts
+++ b/src/server/routers/lambda/agentSkills.ts
@@ -55,6 +55,7 @@ const handleSkillImportError = (error: unknown): never => {
const skillProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
+ const skillModel = new AgentSkillModel(ctx.serverDB, ctx.userId);
return opts.next({
ctx: {
@@ -62,7 +63,16 @@ const skillProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
fileService: new FileService(ctx.serverDB, ctx.userId),
marketService: new MarketService({ userInfo: { userId: ctx.userId } }),
skillImporter: new SkillImporter(ctx.serverDB, ctx.userId),
- skillModel: new AgentSkillModel(ctx.serverDB, ctx.userId),
+ skillModel,
+ },
+ });
+});
+
+const skillResourceProcedure = skillProcedure.use(async (opts) => {
+ const { ctx } = opts;
+
+ return opts.next({
+ ctx: {
skillResourceService: new SkillResourceService(ctx.serverDB, ctx.userId),
},
});
@@ -207,7 +217,7 @@ export const agentSkillsRouter = router({
return ctx.skillModel.findAll();
}),
- listResources: skillProcedure
+ listResources: skillResourceProcedure
.input(z.object({ id: z.string(), includeContent: z.boolean().optional() }))
.query(async ({ ctx, input }) => {
const skill = await ctx.skillModel.findById(input.id);
@@ -222,7 +232,7 @@ export const agentSkillsRouter = router({
return ctx.skillResourceService.listResources(skill.resources, input.includeContent);
}),
- readResource: skillProcedure
+ readResource: skillResourceProcedure
.input(
z.object({
id: z.string(),
diff --git a/src/server/services/agentDocumentVfs/errors.ts b/src/server/services/agentDocumentVfs/errors.ts
new file mode 100644
index 00000000000..6a45857380f
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/errors.ts
@@ -0,0 +1,29 @@
+export type AgentDocumentVfsErrorCode =
+ | 'BAD_REQUEST'
+ | 'CONFLICT'
+ | 'FORBIDDEN'
+ | 'METHOD_NOT_SUPPORTED'
+ | 'NOT_FOUND';
+
+/**
+ * Represents VFS and mounted-subtree operation failures.
+ *
+ * Use when:
+ * - Agent document VFS path validation fails.
+ * - A mounted VFS adapter rejects a read, write, delete, or promotion.
+ *
+ * Expects:
+ * - `code` maps directly to a tRPC error code at router boundaries.
+ *
+ * Returns:
+ * - A typed error that keeps VFS failures independent from skill-domain errors.
+ */
+export class AgentDocumentVfsError extends Error {
+ code: AgentDocumentVfsErrorCode;
+
+ constructor(message: string, code: AgentDocumentVfsErrorCode) {
+ super(message);
+ this.name = 'AgentDocumentVfsError';
+ this.code = code;
+ }
+}
diff --git a/src/server/services/agentDocumentVfs/index.test.ts b/src/server/services/agentDocumentVfs/index.test.ts
new file mode 100644
index 00000000000..9c6fbfb6713
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/index.test.ts
@@ -0,0 +1,714 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentAccess, AgentDocumentModel } from '@/database/models/agentDocuments';
+import type { LobeChatDatabase } from '@/database/type';
+
+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(),
+}));
+
+vi.mock('./mounts/skills/createSkillMount', () => ({
+ createSkillMount: vi.fn(),
+}));
+
+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(() => {
+ for (const method of Object.values(mockAgentDocumentModel)) {
+ method.mockReset();
+ }
+ for (const method of Object.values(mockSkillMount)) {
+ method.mockReset();
+ }
+ (AgentDocumentModel as unknown as ReturnType<typeof vi.fn>).mockImplementation(
+ () => 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] : [];
+ });
+ });
+
+ 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',
+ filename: 'SOUL.md',
+ id: 'agent-doc-1',
+ updatedAt: new Date('2024-01-02T00: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,
+ limit: 100,
+ });
+ 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',
+ }),
+ ]);
+ });
+
+ 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',
+ 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',
+ { limit: 2 },
+ );
+ expect(node).toEqual(
+ expect.objectContaining({
+ documentId: 'documents-1',
+ metadata: { category: 'system' },
+ path: './SOUL.md',
+ type: 'file',
+ }),
+ );
+ });
+
+ 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',
+ 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('rejects ordinary path resolution when duplicate siblings own the path segment', async () => {
+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([
+ {
+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
+ content: 'first',
+ documentId: 'documents-first',
+ fileType: 'agent/document',
+ filename: 'notes.md',
+ id: 'agent-doc-first',
+ },
+ {
+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
+ content: 'second',
+ documentId: 'documents-second',
+ fileType: 'agent/document',
+ filename: 'notes.md',
+ id: 'agent-doc-second',
+ },
+ ]);
+
+ const service = new AgentDocumentVfsService(db, userId);
+
+ await expect(service.stat('./notes.md', { agentId: 'agent-1' })).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ 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',
+ 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',
+ 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',
+ 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('rejects restore when a live node already owns the target parent 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',
+ 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',
+ 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);
+
+ await expect(
+ service.restoreFromTrash('deleted-agent-doc-1', { agentId: 'agent-1' }),
+ ).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(mockAgentDocumentModel.restore).not.toHaveBeenCalled();
+ });
+
+ it('permanently deletes ordinary directory subtrees child-first', async () => {
+ 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',
+ 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',
+ );
+ });
+
+ 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',
+ 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',
+ 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,
+ limit: 100,
+ });
+ 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',
+ 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/src/server/services/agentDocumentVfs/index.ts b/src/server/services/agentDocumentVfs/index.ts
new file mode 100644
index 00000000000..fab02e2f6ef
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/index.ts
@@ -0,0 +1,1408 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import {
+ AgentAccess,
+ type AgentDocument,
+ AgentDocumentModel,
+} from '@/database/models/agentDocuments';
+import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';
+
+import { createMarkdownEditorSnapshot } from '../agentDocuments/headlessEditor';
+import { AgentDocumentVfsError } from './errors';
+import { createSkillMount } from './mounts/skills/createSkillMount';
+import {
+ getUnifiedSkillNamespaceParentPath,
+ getUnifiedSkillNamespaceRootPath,
+ isUnifiedSkillPath as isSkillPath,
+ SKILL_NAMESPACES,
+ type SkillNamespace,
+} from './mounts/skills/path';
+import type { SkillMount } from './mounts/skills/SkillMount';
+import type { SkillMountNode } from './mounts/skills/types';
+import type {
+ AgentDocumentListOptions,
+ AgentDocumentNode,
+ AgentDocumentReadResult,
+ AgentDocumentStats,
+ AgentDocumentTrashEntry,
+} 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 {
+ 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.
+ *
+ * Use when:
+ * - Router path APIs need one filesystem-shaped surface
+ * - CLI commands should stop reasoning about skill-only path aliases
+ *
+ * Expects:
+ * - Ordinary documents remain backed by `agent_documents` + `documents`
+ * - Mounted subtrees can translate into existing services during migration
+ *
+ * Returns:
+ * - Plain-data VFS nodes, stats, and read results
+ *
+ * Call stack:
+ *
+ * agentDocumentRouter.listDocumentsByPath/statDocumentByPath
+ * -> {@link AgentDocumentVfsService.list}
+ * -> {@link AgentDocumentVfsService.stat}
+ * -> ordinary document query helpers
+ * -> mounted subtree query helpers
+ */
+export class AgentDocumentVfsService {
+ private agentDocumentModel: AgentDocumentModel;
+ private skillMount: SkillMount;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.agentDocumentModel = new AgentDocumentModel(db, userId);
+ this.skillMount = createSkillMount(db, userId);
+ }
+
+ /**
+ * Lists direct children for a unified VFS directory path.
+ *
+ * Use when:
+ * - Implementing `ls` or `tree`
+ * - Enumerating either ordinary documents or mounted subtree entries
+ *
+ * Expects:
+ * - Only direct children are returned
+ * - The current phase ignores pagination cursors while preserving the call shape
+ *
+ * Returns:
+ * - Plain-data directory entries
+ */
+ async list(
+ path: string,
+ ctx: AgentDocumentVfsContext,
+ options: AgentDocumentListOptions = {},
+ ): Promise<AgentDocumentNode[]> {
+ // NOTICE:
+ // This directory listing does not copy Node.js `readdir` exactly.
+ // The backend is document rows plus mounted subtrees rather than a local syscall-driven filesystem.
+ // We keep `list` lightweight and avoid content loads so callers do not trigger a `list -> stat` N+1 loop.
+ const normalizedPath = normalizeAgentDocumentPath(path);
+
+ if (normalizedPath === './') {
+ const [ordinaryNodes, lobeNode] = await Promise.all([
+ this.listOrdinaryNodes(ctx.agentId, null, './', options),
+ Promise.resolve(this.createSyntheticDirectoryNode(LOBE_PATH, 'lobe')),
+ ]);
+
+ return [...ordinaryNodes, lobeNode];
+ }
+
+ const syntheticChildren = this.listSyntheticChildren(normalizedPath);
+
+ if (syntheticChildren) return syntheticChildren;
+
+ if (isSkillPath(normalizedPath)) {
+ const nodes = await this.skillMount.list({
+ agentId: ctx.agentId,
+ path: normalizedPath,
+ topicId: ctx.topicId,
+ });
+
+ return applyListLimit(
+ nodes.map((node) => this.toMountedNode(node)),
+ options,
+ );
+ }
+
+ const parentNode = await this.resolveOrdinaryPath(normalizedPath, ctx.agentId);
+
+ if (!parentNode) {
+ throw new AgentDocumentVfsError(`Path not found: ${normalizedPath}`, 'NOT_FOUND');
+ }
+
+ if (parentNode.fileType !== DOCUMENT_FOLDER_TYPE) {
+ throw new AgentDocumentVfsError(`Path is not a directory: ${normalizedPath}`, 'BAD_REQUEST');
+ }
+
+ return this.listOrdinaryNodes(ctx.agentId, parentNode.documentId, normalizedPath, options);
+ }
+
+ /**
+ * Resolves a unified VFS path into detailed node state.
+ *
+ * Use when:
+ * - Implementing `stat`
+ * - Backing the `statDocumentByPath` router API
+ *
+ * Returns:
+ * - Detailed VFS node state or `undefined` when the path is not found
+ */
+ async stat(path: string, ctx: AgentDocumentVfsContext): Promise<AgentDocumentStats | undefined> {
+ const normalizedPath = normalizeAgentDocumentPath(path);
+ const syntheticNode = this.getSyntheticNode(normalizedPath);
+
+ if (syntheticNode) return syntheticNode;
+
+ if (isSkillPath(normalizedPath)) {
+ const node = await this.skillMount.get({
+ agentId: ctx.agentId,
+ path: normalizedPath,
+ topicId: ctx.topicId,
+ });
+
+ return this.toMountedStats(node);
+ }
+
+ const ordinaryNode = await this.resolveOrdinaryPath(normalizedPath, ctx.agentId);
+ return ordinaryNode ? this.toOrdinaryStats(ordinaryNode, normalizedPath) : undefined;
+ }
+
+ /**
+ * Reads file content from a unified VFS path.
+ *
+ * Use when:
+ * - A caller needs the file body rather than only `stat` metadata
+ *
+ * Returns:
+ * - File content payload
+ */
+ async read(path: string, ctx: AgentDocumentVfsContext): Promise<AgentDocumentReadResult> {
+ const normalizedPath = normalizeAgentDocumentPath(path);
+
+ if (isSkillPath(normalizedPath)) {
+ const node = await this.skillMount.get({
+ agentId: ctx.agentId,
+ path: normalizedPath,
+ topicId: ctx.topicId,
+ });
+
+ if (node.type !== 'file') {
+ throw new AgentDocumentVfsError(`Path is not a file: ${path}`, 'BAD_REQUEST');
+ }
+
+ return {
+ content: node.content ?? '',
+ contentType: node.contentType,
+ path: node.path,
+ };
+ }
+
+ const node = await this.resolveOrdinaryPath(normalizedPath, ctx.agentId);
+
+ if (!node) {
+ throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');
+ }
+
+ if (node.fileType === DOCUMENT_FOLDER_TYPE) {
+ throw new AgentDocumentVfsError(`Path is not a file: ${path}`, 'BAD_REQUEST');
+ }
+
+ return {
+ content: node.content,
+ contentType: 'text/markdown',
+ path: normalizedPath,
+ };
+ }
+
+ /**
+ * Writes file content through the unified VFS surface.
+ *
+ * Use when:
+ * - Updating an ordinary agent document by path
+ * - Creating or updating a writable mounted skill entry during the migration period
+ *
+ * Expects:
+ * - `createMode` controls whether missing paths are created or rejected
+ *
+ * Returns:
+ * - The updated file state
+ */
+ async write(
+ path: string,
+ content: string,
+ ctx: AgentDocumentVfsContext,
+ options: AgentDocumentWriteOptions = {},
+ ): Promise<AgentDocumentStats> {
+ const normalizedPath = normalizeAgentDocumentPath(path);
+ const createMode = options.createMode ?? 'if-missing';
+
+ if (isSkillPath(normalizedPath)) {
+ return this.writeMountedSkill(normalizedPath, content, ctx, createMode);
+ }
+
+ return this.writeOrdinaryDocument(normalizedPath, content, ctx, createMode);
+ }
+
+ /**
+ * Creates a directory through the unified VFS surface.
+ *
+ * Use when:
+ * - CLI `mkdir` targets the ordinary document tree
+ *
+ * Returns:
+ * - The created or existing directory state
+ */
+ async mkdir(
+ path: string,
+ ctx: AgentDocumentVfsContext,
+ options: AgentDocumentMkdirOptions = {},
+ ): Promise<AgentDocumentStats> {
+ const normalizedPath = normalizeAgentDocumentPath(path);
+
+ if (isSkillPath(normalizedPath)) {
+ throw new AgentDocumentVfsError(
+ `mkdir is not supported for mounted path: ${path}`,
+ 'BAD_REQUEST',
+ );
+ }
+
+ if (
+ normalizedPath === './' ||
+ normalizedPath === LOBE_PATH ||
+ normalizedPath.startsWith(`${LOBE_PATH}/`)
+ ) {
+ throw new AgentDocumentVfsError(`Cannot create reserved path: ${path}`, 'BAD_REQUEST');
+ }
+
+ const segments = splitAgentDocumentPath(normalizedPath);
+ let parentId: string | null = null;
+ let currentPath = './';
+ let currentNode: AgentDocument | undefined;
+
+ for (const [index, segment] of segments.entries()) {
+ const isLeaf = index === segments.length - 1;
+ const nextPath = buildOrdinaryPath(currentPath, segment);
+ const existing = await this.agentDocumentModel.findByParentAndFilename(
+ ctx.agentId,
+ parentId,
+ segment,
+ );
+
+ if (existing) {
+ await this.assertUniqueOrdinarySibling(ctx.agentId, parentId, segment, existing.id);
+
+ if (existing.fileType !== DOCUMENT_FOLDER_TYPE) {
+ throw new AgentDocumentVfsError(
+ `Path segment is not a directory: ${nextPath}`,
+ 'BAD_REQUEST',
+ );
+ }
+
+ currentNode = existing;
+ parentId = existing.documentId;
+ currentPath = nextPath;
+ continue;
+ }
+
+ if (!isLeaf && !options.recursive) {
+ throw new AgentDocumentVfsError(`Parent path not found: ${nextPath}`, 'BAD_REQUEST');
+ }
+
+ await this.assertNoOrdinarySiblingConflict(ctx.agentId, parentId, segment);
+
+ const created = await this.agentDocumentModel.create(ctx.agentId, segment, '', {
+ fileType: DOCUMENT_FOLDER_TYPE,
+ parentId,
+ title: segment,
+ });
+
+ currentNode = created;
+ parentId = created.documentId;
+ currentPath = nextPath;
+ }
+
+ if (!currentNode) {
+ throw new AgentDocumentVfsError(`Invalid directory path: ${path}`, 'BAD_REQUEST');
+ }
+
+ return this.toOrdinaryStats(currentNode, normalizedPath);
+ }
+
+ /**
+ * Renames or moves a path through the unified VFS surface.
+ *
+ * Use when:
+ * - CLI `mv` needs filesystem-style `rename(from, to)`
+ *
+ * Returns:
+ * - The destination node state
+ */
+ async rename(
+ fromPath: string,
+ toPath: string,
+ ctx: AgentDocumentVfsContext,
+ options: AgentDocumentCopyOptions = {},
+ ): Promise<AgentDocumentStats> {
+ const sourcePath = normalizeAgentDocumentPath(fromPath);
+ const destinationPath = normalizeAgentDocumentPath(toPath);
+
+ if (sourcePath === destinationPath) {
+ const existing = await this.stat(sourcePath, ctx);
+
+ if (!existing) {
+ throw new AgentDocumentVfsError(`Path not found: ${fromPath}`, 'NOT_FOUND');
+ }
+
+ return existing;
+ }
+
+ const sourceNode = await this.stat(sourcePath, ctx);
+
+ if (!sourceNode) {
+ throw new AgentDocumentVfsError(`Path not found: ${fromPath}`, 'NOT_FOUND');
+ }
+
+ assertNotSelfReferentialCopy(sourcePath, destinationPath, sourceNode);
+
+ if (!isSkillPath(sourcePath) && !isSkillPath(destinationPath)) {
+ return this.renameOrdinaryPath(sourcePath, destinationPath, ctx, options);
+ }
+
+ const copied = await this.copy(sourcePath, destinationPath, ctx, options);
+ await this.delete(sourcePath, ctx, {
+ recursive: copied.type === 'directory',
+ });
+
+ return copied;
+ }
+
+ /**
+ * Copies a path through the unified VFS surface.
+ *
+ * Use when:
+ * - CLI `cp` needs filesystem-style path copying
+ *
+ * Returns:
+ * - The destination node state
+ */
+ async copy(
+ fromPath: string,
+ toPath: string,
+ ctx: AgentDocumentVfsContext,
+ options: AgentDocumentCopyOptions = {},
+ ): Promise<AgentDocumentStats> {
+ const sourcePath = normalizeAgentDocumentPath(fromPath);
+ const destinationPath = normalizeAgentDocumentPath(toPath);
+ const sourceNode = await this.stat(sourcePath, ctx);
+
+ if (!sourceNode) {
+ throw new AgentDocumentVfsError(`Path not found: ${fromPath}`, 'NOT_FOUND');
+ }
+
+ assertNotSelfReferentialCopy(sourcePath, destinationPath, sourceNode);
+
+ const existingDestination = await this.stat(destinationPath, ctx);
+
+ if (existingDestination && !options.overwrite) {
+ throw new AgentDocumentVfsError(`Path already exists: ${toPath}`, 'BAD_REQUEST');
+ }
+
+ if (sourceNode.type === 'directory') {
+ await this.mkdir(destinationPath, ctx, { recursive: true });
+
+ const children = await this.listChildrenForRecursiveCopy(sourcePath, ctx);
+ for (const child of children) {
+ await this.copy(child.path, `${destinationPath}/${child.name}`, ctx, options);
+ }
+
+ const copiedDirectory = await this.stat(destinationPath, ctx);
+
+ if (!copiedDirectory) {
+ throw new AgentDocumentVfsError(`Failed to reload copied path: ${toPath}`, 'BAD_REQUEST');
+ }
+
+ return copiedDirectory;
+ }
+
+ const { content } = await this.read(resolveReadablePath(sourcePath), ctx);
+ return this.write(destinationPath, content, ctx, {
+ createMode: options.overwrite ? 'if-missing' : 'always-new',
+ });
+ }
+
+ /**
+ * Soft-deletes a VFS path into agent-scoped trash.
+ *
+ * Use when:
+ * - CLI `rm` should preserve restorable state
+ *
+ * Returns:
+ * - Void
+ */
+ async delete(
+ path: string,
+ ctx: AgentDocumentVfsContext,
+ options: AgentDocumentDeleteOptions = {},
+ ): Promise<void> {
+ const normalizedPath = normalizeAgentDocumentPath(path);
+
+ if (isSkillPath(normalizedPath)) {
+ await this.deleteMountedSkill(normalizedPath, ctx);
+ return;
+ }
+
+ const node = await this.resolveOrdinaryPath(normalizedPath, ctx.agentId);
+
+ if (!node) {
+ throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');
+ }
+
+ const subtree = await this.collectOrdinarySubtree(node, ctx.agentId, true);
+
+ if (node.fileType === DOCUMENT_FOLDER_TYPE && !options.recursive) {
+ throw new AgentDocumentVfsError(
+ `recursive=true is required for directory delete: ${path}`,
+ 'BAD_REQUEST',
+ );
+ }
+
+ for (const item of subtree) {
+ await this.agentDocumentModel.delete(
+ item.id,
+ item.fileType === DOCUMENT_FOLDER_TYPE ? 'recursive-delete' : 'user-delete',
+ );
+ }
+ }
+
+ /**
+ * Promotes a topic-scoped skill into an agent-scoped mounted skill.
+ *
+ * Use when:
+ * - Router APIs need the old promote behavior through the unified VFS path surface
+ *
+ * Returns:
+ * - The promoted mounted skill metadata
+ */
+ async promoteSkill(path: string, ctx: AgentDocumentVfsContext, options: { targetName?: string }) {
+ const normalizedPath = normalizeAgentDocumentPath(path);
+
+ if (!isSkillPath(normalizedPath)) {
+ throw new AgentDocumentVfsError(`Path is not a skill mount path: ${path}`, 'BAD_REQUEST');
+ }
+
+ if (!ctx.topicId) {
+ throw new AgentDocumentVfsError(
+ 'Topic ID is required to promote a topic skill',
+ 'BAD_REQUEST',
+ );
+ }
+
+ const nextNode = await this.skillMount.promote({
+ agentId: ctx.agentId,
+ path: normalizedPath,
+ targetName: options.targetName,
+ topicId: ctx.topicId,
+ });
+
+ return this.toMountedStats(nextNode);
+ }
+
+ /**
+ * Lists agent-scoped trash entries.
+ *
+ * Use when:
+ * - CLI `trash ls` needs a recovery-oriented view
+ *
+ * Returns:
+ * - 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}/`),
+ );
+ }
+
+ /**
+ * 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
+ */
+ async restoreFromTrash(
+ 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);
+ await this.assertNoRestoreConflicts([...ancestors, ...subtree], ctx.agentId);
+
+ 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),
+ );
+ }
+
+ /**
+ * Permanently removes a trash entry and its subtree.
+ *
+ * Use when:
+ * - CLI `trash rm` should erase recoverable state
+ *
+ * Returns:
+ * - 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()) {
+ await this.agentDocumentModel.permanentlyDelete(item.id);
+ }
+ }
+
+ 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);
+ }
+
+ 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,
+ limit: normalizeListLimit(options.limit),
+ });
+ return applyListLimit(
+ docs.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,
+ limit: 2,
+ },
+ );
+
+ if (candidates.length > 1) {
+ throw new AgentDocumentVfsError(`Duplicate VFS path segment: ${segment}`, 'CONFLICT');
+ }
+
+ current = candidates[0];
+ if (!current) return undefined;
+ parentId = current.documentId;
+ }
+
+ return current;
+ }
+
+ private async listChildrenForRecursiveCopy(
+ path: string,
+ ctx: AgentDocumentVfsContext,
+ ): Promise<AgentDocumentNode[]> {
+ const syntheticChildren = this.listSyntheticChildren(path);
+
+ if (syntheticChildren) return syntheticChildren;
+
+ if (isSkillPath(path)) {
+ const nodes = await this.skillMount.list({
+ agentId: ctx.agentId,
+ path,
+ topicId: ctx.topicId,
+ });
+
+ return nodes.map((node) => this.toMountedNode(node));
+ }
+
+ const parentNode = await this.resolveOrdinaryPath(path, ctx.agentId);
+
+ if (!parentNode) {
+ throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');
+ }
+
+ if (parentNode.fileType !== DOCUMENT_FOLDER_TYPE) {
+ throw new AgentDocumentVfsError(`Path is not a directory: ${path}`, 'BAD_REQUEST');
+ }
+
+ const docs = await this.agentDocumentModel.listByParent(ctx.agentId, parentNode.documentId, {
+ limit: MAX_RECURSIVE_COPY_CHILDREN + 1,
+ });
+
+ if (docs.length > MAX_RECURSIVE_COPY_CHILDREN) {
+ throw new AgentDocumentVfsError(
+ `Directory has too many direct children to copy safely: ${path}`,
+ 'BAD_REQUEST',
+ );
+ }
+
+ 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']>,
+ ): Promise<AgentDocumentStats> {
+ if (path === './' || path === LOBE_PATH || path.startsWith(`${LOBE_PATH}/`)) {
+ throw new AgentDocumentVfsError(`Cannot write reserved path: ${path}`, 'BAD_REQUEST');
+ }
+
+ const existing = await this.resolveOrdinaryPath(path, ctx.agentId);
+
+ if (existing) {
+ if (existing.fileType === DOCUMENT_FOLDER_TYPE) {
+ throw new AgentDocumentVfsError(`Path is not a file: ${path}`, 'BAD_REQUEST');
+ }
+
+ await this.assertUniqueOrdinarySibling(
+ ctx.agentId,
+ existing.parentId,
+ existing.filename,
+ existing.id,
+ );
+
+ if (createMode === 'always-new') {
+ throw new AgentDocumentVfsError(`Path already exists: ${path}`, 'BAD_REQUEST');
+ }
+
+ const snapshot = await createMarkdownEditorSnapshot(content);
+ await this.agentDocumentModel.update(existing.id, {
+ content: snapshot.content,
+ editorData: snapshot.editorData,
+ });
+
+ const updated = await this.resolveOrdinaryPath(path, ctx.agentId);
+
+ if (!updated) {
+ throw new AgentDocumentVfsError(`Failed to reload updated path: ${path}`, 'BAD_REQUEST');
+ }
+
+ return this.toOrdinaryStats(updated, path);
+ }
+
+ if (createMode === 'must-exist') {
+ throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');
+ }
+
+ const segments = splitAgentDocumentPath(path);
+ const filename = segments.at(-1);
+
+ if (!filename) {
+ throw new AgentDocumentVfsError(`Invalid VFS path: ${path}`, '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',
+ );
+ }
+
+ await this.assertNoOrdinarySiblingConflict(
+ ctx.agentId,
+ parentNode?.documentId ?? null,
+ filename,
+ );
+
+ const snapshot = await createMarkdownEditorSnapshot(content);
+ const created = await this.agentDocumentModel.create(ctx.agentId, filename, snapshot.content, {
+ editorData: snapshot.editorData,
+ parentId: parentNode?.documentId ?? null,
+ title: filename,
+ });
+
+ return this.toOrdinaryStats(created, path);
+ }
+
+ 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;
+ await this.assertNoOrdinarySiblingConflict(ctx.agentId, parentId, filename);
+
+ 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 : 'text/markdown',
+ 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'),
+ this.createSyntheticDirectoryNode('./lobe/skills/agent-topic', 'agent-topic'),
+ ];
+ }
+
+ 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 assertNoRestoreConflicts(nodes: AgentDocument[], agentId: string): Promise<void> {
+ for (const node of nodes) {
+ if (!node.deletedAt) continue;
+
+ const liveNode = await this.agentDocumentModel.findByParentAndFilename(
+ agentId,
+ node.parentId,
+ node.filename,
+ );
+
+ if (liveNode && liveNode.id !== node.id) {
+ throw new AgentDocumentVfsError(
+ `Cannot restore over live path: ${node.filename}`,
+ 'CONFLICT',
+ );
+ }
+
+ await this.assertUniqueOrdinarySibling(agentId, node.parentId, node.filename, node.id);
+ }
+ }
+
+ private async assertNoOrdinarySiblingConflict(
+ agentId: string,
+ parentId: string | null,
+ filename: string,
+ ): Promise<void> {
+ const conflicts = await this.agentDocumentModel.listByParentAndFilename(
+ agentId,
+ parentId,
+ filename,
+ {
+ limit: 1,
+ },
+ );
+
+ if (conflicts.length > 0) {
+ throw new AgentDocumentVfsError(`Path already exists: ${filename}`, 'CONFLICT');
+ }
+ }
+
+ private async assertUniqueOrdinarySibling(
+ agentId: string,
+ parentId: string | null,
+ filename: string,
+ expectedAgentDocumentId: string,
+ ): Promise<void> {
+ const conflicts = await this.agentDocumentModel.listByParentAndFilename(
+ agentId,
+ parentId,
+ filename,
+ {
+ limit: 2,
+ },
+ );
+ const unexpectedConflicts = conflicts.filter((node) => node.id !== expectedAgentDocumentId);
+
+ if (unexpectedConflicts.length > 0) {
+ throw new AgentDocumentVfsError(`Duplicate VFS path segment: ${filename}`, 'CONFLICT');
+ }
+ }
+
+ 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' && namespace !== 'agent-topic') {
+ 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);
+ }
+}
+
+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 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 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 inferMountedSkillIdentity = (path: string) => {
+ for (const namespace of ['agent', 'agent-topic'] 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,
+ 'agent-topic':
+ AgentAccess.READ |
+ AgentAccess.LIST |
+ AgentAccess.WRITE |
+ AgentAccess.DELETE |
+ AgentAccess.EXECUTE,
+ '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',
+ 'agent-topic',
+ '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/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.test.ts b/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.test.ts
new file mode 100644
index 00000000000..1183598a29b
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.test.ts
@@ -0,0 +1,178 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { SkillMount } from './SkillMount';
+
+describe('SkillMount', () => {
+ it('routes builtin getByPath requests with the original path and forwarded context', async () => {
+ const builtinProvider = { get: vi.fn().mockResolvedValue({ name: 'builtin-skill' }) };
+ const service = new SkillMount({ builtin: builtinProvider } as any);
+
+ const result = await service.get({
+ agentId: 'agent-1',
+ path: './lobe/skills/builtin/skills/builtin-skill/SKILL.md',
+ topicId: 'topic-1',
+ });
+
+ expect(builtinProvider.get).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ path: './lobe/skills/builtin/skills/builtin-skill/SKILL.md',
+ resolvedPath: {
+ filePath: 'SKILL.md',
+ namespace: 'builtin',
+ relativePath: 'builtin-skill/SKILL.md',
+ skillName: 'builtin-skill',
+ },
+ topicId: 'topic-1',
+ });
+ expect(result).toEqual({ name: 'builtin-skill' });
+ });
+
+ it('routes installed namespace listByPath requests with the original path and forwarded context', async () => {
+ const installedProvider = { list: vi.fn().mockResolvedValue([{ name: 'installed-skill' }]) };
+ const service = new SkillMount({ 'installed-active': installedProvider } as any);
+
+ const result = await service.list({
+ agentId: 'agent-1',
+ path: './lobe/skills/installed/active/skills',
+ topicId: 'topic-2',
+ });
+
+ expect(installedProvider.list).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ path: './lobe/skills/installed/active/skills',
+ resolvedPath: {
+ namespace: 'installed-active',
+ relativePath: '',
+ },
+ topicId: 'topic-2',
+ });
+ expect(result).toEqual([{ name: 'installed-skill' }]);
+ });
+
+ it('creates agent-topic skills through the writable provider', async () => {
+ const agentTopicProvider = {
+ create: vi.fn().mockResolvedValue({ path: './lobe/skills/agent-topic/skills/a/SKILL.md' }),
+ delete: vi.fn(),
+ get: vi.fn(),
+ list: vi.fn(),
+ promote: vi.fn(),
+ update: vi.fn(),
+ };
+ const service = new SkillMount({ 'agent-topic': agentTopicProvider } as any);
+
+ const result = await service.create({
+ agentId: 'agent-1',
+ content: '# A',
+ skillName: 'a',
+ targetNamespace: 'agent-topic',
+ topicId: 'topic-1',
+ });
+
+ expect(agentTopicProvider.create).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ content: '# A',
+ skillName: 'a',
+ targetNamespace: 'agent-topic',
+ topicId: 'topic-1',
+ });
+ expect(result.path).toContain('/agent-topic/skills/a/SKILL.md');
+ });
+
+ it('routes updateSkill and deleteSkill by path namespace', async () => {
+ const agentProvider = {
+ create: vi.fn(),
+ delete: vi.fn().mockResolvedValue(undefined),
+ get: vi.fn(),
+ list: vi.fn(),
+ update: vi.fn().mockResolvedValue({ path: './lobe/skills/agent/skills/a/SKILL.md' }),
+ };
+ const service = new SkillMount({ agent: agentProvider } as any);
+
+ const updateResult = await service.update({
+ agentId: 'agent-1',
+ content: '# Updated',
+ path: './lobe/skills/agent/skills/a/SKILL.md',
+ topicId: 'topic-1',
+ });
+ await service.delete({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent/skills/a/SKILL.md',
+ topicId: 'topic-1',
+ });
+
+ expect(agentProvider.update).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ content: '# Updated',
+ path: './lobe/skills/agent/skills/a/SKILL.md',
+ topicId: 'topic-1',
+ });
+ expect(agentProvider.delete).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent/skills/a/SKILL.md',
+ topicId: 'topic-1',
+ });
+ expect(updateResult.path).toBe('./lobe/skills/agent/skills/a/SKILL.md');
+ });
+
+ it('routes promoteSkill through the agent-topic writable provider', async () => {
+ const agentTopicProvider = {
+ create: vi.fn(),
+ delete: vi.fn(),
+ get: vi.fn(),
+ list: vi.fn(),
+ promote: vi
+ .fn()
+ .mockResolvedValue({ path: './lobe/skills/agent/skills/promoted-a/SKILL.md' }),
+ update: vi.fn(),
+ };
+ const service = new SkillMount({ 'agent-topic': agentTopicProvider } as any);
+
+ const result = await service.promote({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent-topic/skills/a/SKILL.md',
+ targetName: 'promoted-a',
+ topicId: 'topic-1',
+ });
+
+ expect(agentTopicProvider.promote).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent-topic/skills/a/SKILL.md',
+ targetName: 'promoted-a',
+ topicId: 'topic-1',
+ });
+ expect(result.path).toBe('./lobe/skills/agent/skills/promoted-a/SKILL.md');
+ });
+
+ it('rejects write operations for non-writable namespaces', async () => {
+ const builtinProvider = { get: vi.fn(), list: vi.fn() };
+ const service = new SkillMount({ builtin: builtinProvider } as any);
+
+ await expect(
+ service.update({
+ agentId: 'agent-1',
+ content: '# Updated',
+ path: './lobe/skills/builtin/skills/a/SKILL.md',
+ }),
+ ).rejects.toThrow('Namespace "builtin" is not writable');
+ });
+
+ it('rejects promoteSkill when the writable provider does not support promotion', async () => {
+ const agentProvider = {
+ create: vi.fn(),
+ delete: vi.fn(),
+ get: vi.fn(),
+ list: vi.fn(),
+ update: vi.fn(),
+ };
+ const service = new SkillMount({ agent: agentProvider } as any);
+
+ await expect(
+ service.promote({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent/skills/a/SKILL.md',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow('Namespace "agent" does not support promote');
+ });
+});
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.ts b/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.ts
new file mode 100644
index 00000000000..6e05e592eea
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.ts
@@ -0,0 +1,153 @@
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+
+import { SkillMountPathResolver } from './SkillMountPathResolver';
+import type { ResolvedSkillMountPath, SkillMountContext, SkillMountNode } from './types';
+
+export interface CreateSkillInput {
+ agentId: string;
+ content: string;
+ skillName: string;
+ targetNamespace: 'agent' | 'agent-topic';
+ topicId?: string;
+}
+
+export interface UpdateSkillInput {
+ agentId: string;
+ content: string;
+ path: string;
+ topicId?: string;
+}
+
+export interface DeleteSkillInput {
+ agentId: string;
+ path: string;
+ topicId?: string;
+}
+
+export interface PromoteSkillInput {
+ agentId: string;
+ path: string;
+ targetName?: string;
+ topicId: string;
+}
+
+export interface SkillMountProvider {
+ get: (input: SkillMountProviderRequest) => Promise<SkillMountNode>;
+ list: (input: SkillMountProviderRequest) => Promise<SkillMountNode[]>;
+}
+
+export interface WritableSkillMountProvider extends SkillMountProvider {
+ create: (input: CreateSkillInput) => Promise<SkillMountNode>;
+ delete: (input: DeleteSkillInput) => Promise<void>;
+ promote?: (input: PromoteSkillInput) => Promise<SkillMountNode>;
+ update: (input: UpdateSkillInput) => Promise<SkillMountNode>;
+}
+
+export interface SkillMountProviderRequest extends SkillMountContext {
+ path: string;
+ resolvedPath: ResolvedSkillMountPath;
+}
+
+export type SkillMountProviderRegistry = Partial<
+ Record<SkillMountNode['namespace'], SkillMountProvider>
+>;
+
+export class SkillMount {
+ constructor(private readonly providers: SkillMountProviderRegistry = {}) {}
+
+ async list(input: { agentId: string; path: string; topicId?: string }) {
+ const resolvedPath = SkillMountPathResolver.resolve(input.path);
+ const provider = this.getProvider(resolvedPath.namespace);
+
+ return provider.list({
+ agentId: input.agentId,
+ topicId: input.topicId,
+ path: input.path,
+ resolvedPath,
+ });
+ }
+
+ async get(input: { agentId: string; path: string; topicId?: string }) {
+ const resolvedPath = SkillMountPathResolver.resolve(input.path);
+ const provider = this.getProvider(resolvedPath.namespace);
+
+ return provider.get({
+ agentId: input.agentId,
+ topicId: input.topicId,
+ path: input.path,
+ resolvedPath,
+ });
+ }
+
+ async create(input: CreateSkillInput) {
+ const provider = this.getWritableProviderByNamespace(input.targetNamespace);
+
+ return provider.create(input);
+ }
+
+ async update(input: UpdateSkillInput) {
+ const provider = this.getWritableProviderByPath(input.path);
+
+ return provider.update(input);
+ }
+
+ async delete(input: DeleteSkillInput) {
+ const provider = this.getWritableProviderByPath(input.path);
+
+ return provider.delete(input);
+ }
+
+ async promote(input: PromoteSkillInput) {
+ const provider = this.getWritableProviderByPath(input.path);
+
+ if (!provider.promote) {
+ const { namespace } = SkillMountPathResolver.resolve(input.path);
+ throw new AgentDocumentVfsError(
+ `Namespace "${namespace}" does not support promote`,
+ 'METHOD_NOT_SUPPORTED',
+ );
+ }
+
+ return provider.promote(input);
+ }
+
+ private getProvider(namespace: SkillMountNode['namespace']) {
+ const provider = this.providers[namespace];
+
+ if (!provider) {
+ throw new AgentDocumentVfsError(
+ `No provider registered for namespace "${namespace}"`,
+ 'NOT_FOUND',
+ );
+ }
+
+ return provider;
+ }
+
+ private getWritableProviderByNamespace(namespace: CreateSkillInput['targetNamespace']) {
+ const provider = this.providers[namespace];
+
+ if (!this.isWritableProvider(provider)) {
+ throw new AgentDocumentVfsError(`Namespace "${namespace}" is not writable`, 'FORBIDDEN');
+ }
+
+ return provider;
+ }
+
+ private getWritableProviderByPath(path: string) {
+ const { namespace } = SkillMountPathResolver.resolve(path);
+ const provider = this.providers[namespace];
+
+ if (!this.isWritableProvider(provider)) {
+ throw new AgentDocumentVfsError(`Namespace "${namespace}" is not writable`, 'FORBIDDEN');
+ }
+
+ return provider;
+ }
+
+ private isWritableProvider(
+ provider?: SkillMountProvider,
+ ): provider is WritableSkillMountProvider {
+ return !!provider && 'create' in provider && 'delete' in provider && 'update' in provider;
+ }
+}
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/SkillMountPathResolver.test.ts b/src/server/services/agentDocumentVfs/mounts/skills/SkillMountPathResolver.test.ts
new file mode 100644
index 00000000000..aa36020c304
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/SkillMountPathResolver.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { SkillMountPathResolver } from './SkillMountPathResolver';
+
+describe('SkillMountPathResolver', () => {
+ it('resolves agent skill root paths', () => {
+ expect(
+ SkillMountPathResolver.resolve('./lobe/skills/agent/skills/research-paper/SKILL.md'),
+ ).toEqual({
+ filePath: 'SKILL.md',
+ namespace: 'agent',
+ relativePath: 'research-paper/SKILL.md',
+ skillName: 'research-paper',
+ });
+ });
+
+ it('resolves installed active directories', () => {
+ expect(SkillMountPathResolver.resolve('./lobe/skills/installed/active/skills')).toEqual({
+ namespace: 'installed-active',
+ relativePath: '',
+ });
+ });
+
+ it('rejects non-skill paths', () => {
+ expect(() => SkillMountPathResolver.resolve('./documents/lobe/agent/rules.md')).toThrow(
+ 'Not a skill VFS path',
+ );
+ expect(() => SkillMountPathResolver.resolve('./documents/lobe/agent/rules.md')).toThrowError(
+ expect.objectContaining({ code: 'BAD_REQUEST' }),
+ );
+ });
+
+ it('rejects traversal segments', () => {
+ expect(() =>
+ SkillMountPathResolver.resolve('./lobe/skills/agent/skills/research-paper/../other/SKILL.md'),
+ ).toThrow('Not a skill VFS path');
+ });
+
+ it('treats trailing slash paths as directories', () => {
+ expect(SkillMountPathResolver.resolve('./lobe/skills/agent/skills/research-paper/')).toEqual({
+ namespace: 'agent',
+ relativePath: 'research-paper',
+ skillName: 'research-paper',
+ });
+ });
+
+ it('rejects repeated separators in file paths', () => {
+ expect(() =>
+ SkillMountPathResolver.resolve('./lobe/skills/agent/skills/research-paper//SKILL.md'),
+ ).toThrow('Not a skill VFS path');
+ });
+
+ it('rejects repeated separators immediately after a namespace prefix', () => {
+ expect(() =>
+ SkillMountPathResolver.resolve('./lobe/skills/agent/skills//research-paper/SKILL.md'),
+ ).toThrowError(expect.objectContaining({ code: 'BAD_REQUEST' }));
+ });
+
+ it('rejects malformed paths in the guard helper', () => {
+ expect(
+ SkillMountPathResolver.isSkillPath('./lobe/skills/agent/skills/research-paper/../other'),
+ ).toBe(false);
+ });
+});
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/SkillMountPathResolver.ts b/src/server/services/agentDocumentVfs/mounts/skills/SkillMountPathResolver.ts
new file mode 100644
index 00000000000..1f8e5d1e762
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/SkillMountPathResolver.ts
@@ -0,0 +1,84 @@
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+
+import { getUnifiedSkillNamespaceRootPath, SKILL_NAMESPACES, type SkillNamespace } from './path';
+import type { ResolvedSkillMountPath } from './types';
+
+const SKILL_MOUNT_PREFIXES = SKILL_NAMESPACES.map(
+ (namespace) => [getUnifiedSkillNamespaceRootPath(namespace), namespace] as const,
+) satisfies ReadonlyArray<readonly [prefix: string, namespace: SkillNamespace]>;
+
+/**
+ * Resolves strict skill VFS paths into mount path parts.
+ *
+ * Use when:
+ * - Skill mounts need to dispatch unified `./lobe/skills/...` paths to namespace providers
+ * - Routers need invalid skill VFS paths to surface as BAD_REQUEST instead of generic failures
+ *
+ * Expects:
+ * - Paths use one of the configured strict skill namespace prefixes
+ *
+ * Returns:
+ * - Parsed namespace, skill name, and optional file path parts
+ */
+export class SkillMountPathResolver {
+ static isSkillPath(path: string) {
+ try {
+ SkillMountPathResolver.resolve(path);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ static resolve(path: string): ResolvedSkillMountPath {
+ const match = SKILL_MOUNT_PREFIXES.find(
+ ([prefix]) => path === prefix || path.startsWith(`${prefix}/`),
+ );
+
+ if (!match) {
+ throw new AgentDocumentVfsError('Not a skill VFS path', 'BAD_REQUEST');
+ }
+
+ const [prefix, namespace] = match;
+ const rawRelativePath = path.slice(prefix.length);
+
+ if (rawRelativePath.startsWith('//')) {
+ throw new AgentDocumentVfsError('Not a skill VFS path', 'BAD_REQUEST');
+ }
+
+ const relativePath = rawRelativePath.replace(/^\/+/, '').replace(/\/+$/, '');
+
+ if (
+ relativePath.includes('//') ||
+ relativePath.split('/').some((segment) => segment === '.' || segment === '..')
+ ) {
+ throw new AgentDocumentVfsError('Not a skill VFS path', 'BAD_REQUEST');
+ }
+
+ if (!relativePath) {
+ return {
+ namespace,
+ relativePath,
+ };
+ }
+
+ const separatorIndex = relativePath.indexOf('/');
+
+ if (separatorIndex < 0) {
+ return {
+ namespace,
+ relativePath,
+ skillName: relativePath,
+ };
+ }
+
+ return {
+ namespace,
+ relativePath,
+ skillName: relativePath.slice(0, separatorIndex),
+ ...(separatorIndex < relativePath.length - 1
+ ? { filePath: relativePath.slice(separatorIndex + 1) }
+ : {}),
+ };
+ }
+}
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/createSkillMount.ts b/src/server/services/agentDocumentVfs/mounts/skills/createSkillMount.ts
new file mode 100644
index 00000000000..7519dda37ec
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/createSkillMount.ts
@@ -0,0 +1,54 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import { AgentModel } from '@/database/models/agent';
+import { AgentDocumentModel } from '@/database/models/agentDocuments';
+import { AgentSkillModel } from '@/database/models/agentSkill';
+import { DocumentService } from '@/server/services/document';
+import { SkillResourceService } from '@/server/services/skill/resource';
+
+import { ProviderSkillsAgentDocument } from './providers/ProviderSkillsAgentDocument';
+import { ProviderSkillsBuiltin } from './providers/ProviderSkillsBuiltin';
+import { ProviderSkillsInstalledActive } from './providers/ProviderSkillsInstalledActive';
+import { ProviderSkillsInstalledAll } from './providers/ProviderSkillsInstalledAll';
+import { SkillMount } from './SkillMount';
+
+/**
+ * Creates the skill mount with all VFS namespace providers registered.
+ *
+ * Use when:
+ * - Building request-scoped VFS services for skill mount operations.
+ * - Wiring writable document-backed skills and read-only installed/builtin skills.
+ *
+ * Expects:
+ * - `db` and `userId` belong to the current request scope.
+ *
+ * Returns:
+ * - A skill mount that routes unified skill paths to namespace-specific providers.
+ */
+export const createSkillMount = (db: LobeChatDatabase, userId: string) => {
+ const agentModel = new AgentModel(db, userId);
+ const agentDocumentModel = new AgentDocumentModel(db, userId);
+ const documentService = new DocumentService(db, userId);
+ const skillModel = new AgentSkillModel(db, userId);
+ const skillResourceService = new SkillResourceService(db, userId);
+ return new SkillMount({
+ 'agent': new ProviderSkillsAgentDocument('agent', {
+ agentDocumentModel,
+ documentService,
+ }),
+ 'agent-topic': new ProviderSkillsAgentDocument('agent-topic', {
+ agentDocumentModel,
+ documentService,
+ }),
+ 'builtin': new ProviderSkillsBuiltin(),
+ 'installed-active': new ProviderSkillsInstalledActive({
+ agentModel,
+ skillModel,
+ skillResourceService,
+ }),
+ 'installed-all': new ProviderSkillsInstalledAll({
+ skillModel,
+ skillResourceService,
+ }),
+ });
+};
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/path.ts b/src/server/services/agentDocumentVfs/mounts/skills/path.ts
new file mode 100644
index 00000000000..c66bd6f05ec
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/path.ts
@@ -0,0 +1,55 @@
+import type { SkillMountNode } from './types';
+
+export type SkillNamespace = SkillMountNode['namespace'];
+
+export const SKILL_NAMESPACES = [
+ 'agent',
+ 'agent-topic',
+ 'builtin',
+ 'installed-active',
+ 'installed-all',
+] as const satisfies readonly SkillNamespace[];
+
+const UNIFIED_SKILL_ROOT_PREFIX = './lobe/skills';
+
+const SKILL_NAMESPACE_SEGMENTS = {
+ 'agent': ['agent', 'skills'],
+ 'agent-topic': ['agent-topic', 'skills'],
+ 'builtin': ['builtin', 'skills'],
+ 'installed-active': ['installed', 'active', 'skills'],
+ 'installed-all': ['installed', 'all', 'skills'],
+} as const satisfies Record<SkillNamespace, readonly string[]>;
+
+/**
+ * Returns the target unified skill mount root for a namespace.
+ *
+ * Use when:
+ * - Producing VFS nodes from skill providers.
+ * - Comparing mounted subtree paths inside the unified agent-document VFS.
+ *
+ * Expects:
+ * - `namespace` is one registered skill namespace.
+ *
+ * Returns:
+ * - A path such as `./lobe/skills/agent/skills`.
+ */
+export const getUnifiedSkillNamespaceRootPath = (namespace: SkillNamespace) =>
+ `${UNIFIED_SKILL_ROOT_PREFIX}/${SKILL_NAMESPACE_SEGMENTS[namespace].join('/')}`;
+
+/**
+ * Returns the parent directory that contains a skill namespace root.
+ *
+ * Use when:
+ * - Rendering synthetic namespace directories before the provider-owned root.
+ *
+ * Expects:
+ * - `namespace` is one registered skill namespace.
+ *
+ * Returns:
+ * - A path such as `./lobe/skills/installed/active`.
+ */
+export const getUnifiedSkillNamespaceParentPath = (namespace: SkillNamespace) =>
+ `${UNIFIED_SKILL_ROOT_PREFIX}/${SKILL_NAMESPACE_SEGMENTS[namespace].slice(0, -1).join('/')}`;
+
+export const isUnifiedSkillPath = (path: string) =>
+ path === UNIFIED_SKILL_ROOT_PREFIX || path.startsWith(`${UNIFIED_SKILL_ROOT_PREFIX}/`);
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.test.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.test.ts
new file mode 100644
index 00000000000..e3655412f89
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.test.ts
@@ -0,0 +1,537 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ProviderSkillsAgentDocument } from './ProviderSkillsAgentDocument';
+
+vi.mock('@/server/services/agentDocuments/headlessEditor', () => ({
+ createMarkdownEditorSnapshot: vi.fn(async (content: string) => ({
+ content,
+ editorData: { markdown: content },
+ })),
+ exportEditorDataSnapshot: vi.fn(async ({ fallbackContent }: { fallbackContent?: string }) => ({
+ content: fallbackContent ?? '',
+ editorData: { exported: true },
+ })),
+}));
+
+const createAgentDocument = (overrides: Record<string, unknown> = {}) =>
+ ({
+ content: 'existing content',
+ documentId: 'document-1',
+ editorData: { root: { children: [] } },
+ fileType: 'custom/document',
+ filename: 'skill-a',
+ id: 'agent-doc-1',
+ metadata: null,
+ parentId: null,
+ policy: null,
+ policyLoad: 'progressive',
+ templateId: null,
+ title: 'skill-a',
+ ...overrides,
+ }) as any;
+
+describe('Agent skill VFS providers', () => {
+ const agentDocumentModel = {
+ associate: vi.fn(),
+ delete: vi.fn(),
+ findByAgent: vi.fn(),
+ update: vi.fn(),
+ };
+ const documentService = {
+ createDocument: vi.fn(),
+ deleteDocument: vi.fn(),
+ trySaveCurrentDocumentHistory: vi.fn(),
+ updateDocument: vi.fn(),
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('ProviderSkillsAgentDocument agent namespace', () => {
+ it('lists only tree-backed agent skill folders at the namespace root', async () => {
+ agentDocumentModel.findByAgent.mockResolvedValue([
+ createAgentDocument({
+ documentId: 'root-1',
+ fileType: 'custom/folder',
+ filename: 'skills',
+ id: 'agent-doc-root',
+ metadata: { lobeSkill: { namespace: 'agent', role: 'namespace-root' } },
+ }),
+ createAgentDocument({
+ documentId: 'folder-1',
+ fileType: 'custom/folder',
+ filename: 'agent-skill',
+ id: 'agent-doc-folder',
+ metadata: {
+ lobeSkill: { namespace: 'agent', role: 'skill-folder', skillName: 'agent-skill' },
+ },
+ parentId: 'root-1',
+ }),
+ createAgentDocument({
+ documentId: 'file-1',
+ filename: 'SKILL.md',
+ id: 'agent-doc-file',
+ metadata: {
+ lobeSkill: { namespace: 'agent', role: 'skill-file', skillName: 'agent-skill' },
+ },
+ parentId: 'folder-1',
+ }),
+ createAgentDocument({
+ documentId: 'topic-folder',
+ fileType: 'custom/folder',
+ filename: 'topic-skill',
+ id: 'agent-doc-topic-folder',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent-topic',
+ role: 'skill-folder',
+ skillName: 'topic-skill',
+ topicId: 'topic-1',
+ },
+ },
+ parentId: 'root-topic',
+ }),
+ ]);
+
+ const provider = new ProviderSkillsAgentDocument('agent', {
+ agentDocumentModel,
+ documentService,
+ });
+
+ const result = await provider.list({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent/skills',
+ resolvedPath: { namespace: 'agent', relativePath: '' },
+ });
+
+ expect(result).toEqual([
+ expect.objectContaining({
+ name: 'agent-skill',
+ namespace: 'agent',
+ path: './lobe/skills/agent/skills/agent-skill',
+ type: 'directory',
+ }),
+ ]);
+ });
+
+ it('creates a tree-backed agent skill with namespace root, folder, and SKILL.md', async () => {
+ agentDocumentModel.findByAgent.mockResolvedValue([]);
+ documentService.createDocument
+ .mockResolvedValueOnce({
+ fileType: 'custom/folder',
+ filename: 'skills',
+ id: 'root-1',
+ metadata: { lobeSkill: { namespace: 'agent', role: 'namespace-root' } },
+ parentId: null,
+ title: 'skills',
+ })
+ .mockResolvedValueOnce({
+ fileType: 'custom/folder',
+ filename: 'writer',
+ id: 'folder-1',
+ metadata: {
+ lobeSkill: { namespace: 'agent', role: 'skill-folder', skillName: 'writer' },
+ },
+ parentId: 'root-1',
+ title: 'writer',
+ })
+ .mockResolvedValueOnce({
+ content: '# Skill',
+ fileType: 'custom/document',
+ filename: 'SKILL.md',
+ id: 'file-1',
+ metadata: { lobeSkill: { namespace: 'agent', role: 'skill-file', skillName: 'writer' } },
+ parentId: 'folder-1',
+ title: 'SKILL.md',
+ });
+
+ const provider = new ProviderSkillsAgentDocument('agent', {
+ agentDocumentModel,
+ documentService,
+ });
+
+ const result = await provider.create({
+ agentId: 'agent-1',
+ content: '# Skill',
+ skillName: 'writer',
+ targetNamespace: 'agent',
+ });
+
+ expect(documentService.createDocument).toHaveBeenNthCalledWith(1, {
+ editorData: { root: { children: [], type: 'root' } },
+ fileType: 'custom/folder',
+ metadata: { lobeSkill: { namespace: 'agent', role: 'namespace-root' } },
+ title: 'skills',
+ });
+ expect(documentService.createDocument).toHaveBeenNthCalledWith(2, {
+ editorData: { root: { children: [], type: 'root' } },
+ fileType: 'custom/folder',
+ metadata: { lobeSkill: { namespace: 'agent', role: 'skill-folder', skillName: 'writer' } },
+ parentId: 'root-1',
+ title: 'writer',
+ });
+ expect(documentService.createDocument).toHaveBeenNthCalledWith(3, {
+ content: '# Skill',
+ editorData: { markdown: '# Skill' },
+ metadata: { lobeSkill: { namespace: 'agent', role: 'skill-file', skillName: 'writer' } },
+ parentId: 'folder-1',
+ title: 'SKILL.md',
+ });
+ expect(agentDocumentModel.associate).toHaveBeenNthCalledWith(1, {
+ agentId: 'agent-1',
+ documentId: 'root-1',
+ policyLoad: 'disabled',
+ uniqueSibling: false,
+ });
+ expect(agentDocumentModel.associate).toHaveBeenNthCalledWith(2, {
+ agentId: 'agent-1',
+ documentId: 'folder-1',
+ policyLoad: 'disabled',
+ uniqueSibling: false,
+ });
+ expect(agentDocumentModel.associate).toHaveBeenNthCalledWith(3, {
+ agentId: 'agent-1',
+ documentId: 'file-1',
+ uniqueSibling: false,
+ });
+ expect(result.path).toBe('./lobe/skills/agent/skills/writer/SKILL.md');
+ });
+
+ it('updates an agent skill through the document model and saves history when content changes', async () => {
+ agentDocumentModel.findByAgent.mockResolvedValue([
+ createAgentDocument({
+ content: 'old content',
+ documentId: 'file-1',
+ filename: 'SKILL.md',
+ id: 'agent-doc-file',
+ metadata: { lobeSkill: { namespace: 'agent', role: 'skill-file', skillName: 'skill-a' } },
+ parentId: 'folder-1',
+ }),
+ ]);
+
+ const provider = new ProviderSkillsAgentDocument('agent', {
+ agentDocumentModel,
+ documentService,
+ });
+
+ const result = await provider.update({
+ agentId: 'agent-1',
+ content: 'new content',
+ path: './lobe/skills/agent/skills/skill-a/SKILL.md',
+ });
+
+ expect(documentService.trySaveCurrentDocumentHistory).toHaveBeenCalledWith(
+ 'file-1',
+ 'llm_call',
+ );
+ expect(agentDocumentModel.update).toHaveBeenCalledWith('agent-doc-file', {
+ content: 'new content',
+ editorData: { markdown: 'new content' },
+ });
+ expect(result.content).toBe('new content');
+ });
+
+ it('soft-deletes the folder subtree for an agent skill', async () => {
+ agentDocumentModel.findByAgent.mockResolvedValue([
+ createAgentDocument({
+ documentId: 'folder-1',
+ fileType: 'custom/folder',
+ filename: 'skill-a',
+ id: 'agent-doc-folder',
+ metadata: {
+ lobeSkill: { namespace: 'agent', role: 'skill-folder', skillName: 'skill-a' },
+ },
+ parentId: 'root-1',
+ }),
+ createAgentDocument({
+ documentId: 'file-1',
+ filename: 'SKILL.md',
+ id: 'agent-doc-file',
+ metadata: { lobeSkill: { namespace: 'agent', role: 'skill-file', skillName: 'skill-a' } },
+ parentId: 'folder-1',
+ }),
+ ]);
+
+ const provider = new ProviderSkillsAgentDocument('agent', {
+ agentDocumentModel,
+ documentService,
+ });
+
+ await provider.delete({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent/skills/skill-a/SKILL.md',
+ });
+
+ expect(documentService.deleteDocument).toHaveBeenCalledWith('folder-1');
+ });
+ });
+
+ describe('ProviderSkillsAgentDocument agent-topic namespace', () => {
+ it('lists only topic-matching tree-backed skills', async () => {
+ agentDocumentModel.findByAgent.mockResolvedValue([
+ createAgentDocument({
+ documentId: 'topic-folder-1',
+ fileType: 'custom/folder',
+ filename: 'topic-skill-a',
+ id: 'agent-doc-topic-a',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent-topic',
+ role: 'skill-folder',
+ skillName: 'topic-skill-a',
+ topicId: 'topic-1',
+ },
+ },
+ parentId: 'root-topic-1',
+ }),
+ createAgentDocument({
+ documentId: 'topic-folder-2',
+ fileType: 'custom/folder',
+ filename: 'topic-skill-b',
+ id: 'agent-doc-topic-b',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent-topic',
+ role: 'skill-folder',
+ skillName: 'topic-skill-b',
+ topicId: 'topic-2',
+ },
+ },
+ parentId: 'root-topic-2',
+ }),
+ ]);
+
+ const provider = new ProviderSkillsAgentDocument('agent-topic', {
+ agentDocumentModel,
+ documentService,
+ });
+
+ const result = await provider.list({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent-topic/skills',
+ resolvedPath: { namespace: 'agent-topic', relativePath: '' },
+ topicId: 'topic-1',
+ });
+
+ expect(result).toEqual([
+ expect.objectContaining({
+ name: 'topic-skill-a',
+ namespace: 'agent-topic',
+ path: './lobe/skills/agent-topic/skills/topic-skill-a',
+ }),
+ ]);
+ });
+
+ it('creates a topic skill with metadata scoped to the topic', async () => {
+ agentDocumentModel.findByAgent.mockResolvedValue([]);
+ documentService.createDocument
+ .mockResolvedValueOnce({
+ fileType: 'custom/folder',
+ filename: 'skills',
+ id: 'root-topic-1',
+ metadata: {
+ lobeSkill: { namespace: 'agent-topic', role: 'namespace-root', topicId: 'topic-1' },
+ },
+ parentId: null,
+ title: 'skills',
+ })
+ .mockResolvedValueOnce({
+ fileType: 'custom/folder',
+ filename: 'topic-skill',
+ id: 'topic-folder-1',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent-topic',
+ role: 'skill-folder',
+ skillName: 'topic-skill',
+ topicId: 'topic-1',
+ },
+ },
+ parentId: 'root-topic-1',
+ title: 'topic-skill',
+ })
+ .mockResolvedValueOnce({
+ content: 'topic content',
+ fileType: 'custom/document',
+ filename: 'SKILL.md',
+ id: 'topic-file-1',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent-topic',
+ role: 'skill-file',
+ skillName: 'topic-skill',
+ topicId: 'topic-1',
+ },
+ },
+ parentId: 'topic-folder-1',
+ title: 'SKILL.md',
+ });
+
+ const provider = new ProviderSkillsAgentDocument('agent-topic', {
+ agentDocumentModel,
+ documentService,
+ });
+
+ const result = await provider.create({
+ agentId: 'agent-1',
+ content: 'topic content',
+ skillName: 'topic-skill',
+ targetNamespace: 'agent-topic',
+ topicId: 'topic-1',
+ });
+
+ expect(documentService.createDocument).toHaveBeenNthCalledWith(2, {
+ editorData: { root: { children: [], type: 'root' } },
+ fileType: 'custom/folder',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent-topic',
+ role: 'skill-folder',
+ skillName: 'topic-skill',
+ topicId: 'topic-1',
+ },
+ },
+ parentId: 'root-topic-1',
+ title: 'topic-skill',
+ });
+ expect(result.path).toBe('./lobe/skills/agent-topic/skills/topic-skill/SKILL.md');
+ });
+
+ it('soft-deletes the topic skill subtree without touching other topics', async () => {
+ agentDocumentModel.findByAgent.mockResolvedValue([
+ createAgentDocument({
+ documentId: 'topic-folder-1',
+ fileType: 'custom/folder',
+ filename: 'topic-skill',
+ id: 'agent-doc-topic-folder',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent-topic',
+ role: 'skill-folder',
+ skillName: 'topic-skill',
+ topicId: 'topic-1',
+ },
+ },
+ parentId: 'root-topic-1',
+ }),
+ createAgentDocument({
+ documentId: 'topic-file-1',
+ filename: 'SKILL.md',
+ id: 'agent-doc-topic-file',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent-topic',
+ role: 'skill-file',
+ skillName: 'topic-skill',
+ topicId: 'topic-1',
+ },
+ },
+ parentId: 'topic-folder-1',
+ }),
+ ]);
+
+ const provider = new ProviderSkillsAgentDocument('agent-topic', {
+ agentDocumentModel,
+ documentService,
+ });
+
+ await provider.delete({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent-topic/skills/topic-skill/SKILL.md',
+ topicId: 'topic-1',
+ });
+
+ expect(documentService.deleteDocument).toHaveBeenCalledWith('topic-folder-1');
+ });
+
+ it('promotes a topic skill by copying it into the agent namespace', async () => {
+ agentDocumentModel.findByAgent.mockResolvedValue([
+ createAgentDocument({
+ content: 'topic content',
+ documentId: 'topic-file-1',
+ filename: 'SKILL.md',
+ id: 'agent-doc-topic-file',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent-topic',
+ role: 'skill-file',
+ skillName: 'topic-skill',
+ topicId: 'topic-1',
+ },
+ },
+ parentId: 'topic-folder-1',
+ }),
+ ]);
+ documentService.createDocument
+ .mockResolvedValueOnce({
+ fileType: 'custom/folder',
+ filename: 'skills',
+ id: 'root-agent-1',
+ metadata: { lobeSkill: { namespace: 'agent', role: 'namespace-root' } },
+ parentId: null,
+ title: 'skills',
+ })
+ .mockResolvedValueOnce({
+ fileType: 'custom/folder',
+ filename: 'promoted-skill',
+ id: 'agent-folder-1',
+ metadata: {
+ lobeSkill: { namespace: 'agent', role: 'skill-folder', skillName: 'promoted-skill' },
+ },
+ parentId: 'root-agent-1',
+ title: 'promoted-skill',
+ })
+ .mockResolvedValueOnce({
+ content: 'topic content',
+ fileType: 'custom/document',
+ filename: 'SKILL.md',
+ id: 'agent-file-1',
+ metadata: {
+ lobeSkill: { namespace: 'agent', role: 'skill-file', skillName: 'promoted-skill' },
+ },
+ parentId: 'agent-folder-1',
+ title: 'SKILL.md',
+ });
+
+ const provider = new ProviderSkillsAgentDocument('agent-topic', {
+ agentDocumentModel,
+ documentService,
+ });
+
+ if (!provider.promote) {
+ throw new Error('Expected agent-topic provider to support skill promotion');
+ }
+
+ const result = await provider.promote({
+ agentId: 'agent-1',
+ path: './lobe/skills/agent-topic/skills/topic-skill/SKILL.md',
+ targetName: 'promoted-skill',
+ topicId: 'topic-1',
+ });
+
+ expect(documentService.createDocument).toHaveBeenNthCalledWith(2, {
+ editorData: { root: { children: [], type: 'root' } },
+ fileType: 'custom/folder',
+ metadata: {
+ lobeSkill: {
+ lineage: {
+ sourceDocumentId: 'topic-file-1',
+ sourceNamespace: 'agent-topic',
+ sourceSkillName: 'topic-skill',
+ sourceTopicId: 'topic-1',
+ },
+ namespace: 'agent',
+ role: 'skill-folder',
+ skillName: 'promoted-skill',
+ },
+ },
+ parentId: 'root-agent-1',
+ title: 'promoted-skill',
+ });
+ expect(result.namespace).toBe('agent');
+ expect(result.path).toBe('./lobe/skills/agent/skills/promoted-skill/SKILL.md');
+ });
+ });
+});
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.ts
new file mode 100644
index 00000000000..3da1e9bba22
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.ts
@@ -0,0 +1,259 @@
+import { createMarkdownEditorSnapshot } from '@/server/services/agentDocuments/headlessEditor';
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+
+import type {
+ CreateSkillInput,
+ DeleteSkillInput,
+ PromoteSkillInput,
+ SkillMountProviderRequest,
+ UpdateSkillInput,
+ WritableSkillMountProvider,
+} from '../SkillMount';
+import { SkillMountPathResolver } from '../SkillMountPathResolver';
+import type { SkillMountNode } from '../types';
+import type { ProviderSkillsAgentDocumentDeps } from './providerSkillsAgentDocumentUtils';
+import {
+ assertSkillDocument,
+ buildSkillDirectoryNode,
+ buildSkillFileNode,
+ buildSkillNamespaceRootNode,
+ createSkillTree,
+ EMPTY_EDITOR_DATA,
+ getRequiredTopicId,
+ getResolvedSkillName,
+ getScopedSkillDocuments,
+ getSkillFile,
+ getSkillFolder,
+ getSkillMetadata,
+ getValidatedSkillName,
+ listScopedSkillFolders,
+ projectDocumentContent,
+ sortSkillFolders,
+} from './providerSkillsAgentDocumentUtils';
+
+interface ProviderSkillsAgentDocumentConfig {
+ namespace: 'agent' | 'agent-topic';
+}
+
+const DOCUMENT_SKILL_PROVIDER_CONFIGS = {
+ 'agent': {
+ namespace: 'agent',
+ },
+ 'agent-topic': {
+ namespace: 'agent-topic',
+ },
+} as const satisfies Record<'agent' | 'agent-topic', ProviderSkillsAgentDocumentConfig>;
+
+/**
+ * Provides writable VFS operations for document-backed skills.
+ *
+ * Use when:
+ * - Serving agent-level skills from agent documents.
+ * - Serving topic-level draft skills from agent documents.
+ *
+ * Expects:
+ * - Managed skill documents carry `metadata.lobeSkill` with namespace, role, and topic scope.
+ * - Topic-backed requests pass `topicId`.
+ *
+ * Returns:
+ * - Skill VFS nodes whose paths use the target unified `./lobe/skills/...` layout.
+ */
+export class ProviderSkillsAgentDocument implements WritableSkillMountProvider {
+ private readonly config: ProviderSkillsAgentDocumentConfig;
+
+ readonly promote?: (input: PromoteSkillInput) => Promise<SkillMountNode>;
+
+ constructor(
+ namespace: ProviderSkillsAgentDocumentConfig['namespace'],
+ private readonly deps: ProviderSkillsAgentDocumentDeps,
+ ) {
+ this.config = DOCUMENT_SKILL_PROVIDER_CONFIGS[namespace];
+
+ if (namespace === 'agent-topic') {
+ this.promote = (input) => this.promoteTopicSkill(input);
+ }
+ }
+
+ async get(input: SkillMountProviderRequest): Promise<SkillMountNode> {
+ const topicId = this.getTopicId(input.topicId);
+
+ if (!input.resolvedPath.skillName) {
+ return buildSkillNamespaceRootNode(this.config.namespace);
+ }
+
+ const skillName = getResolvedSkillName(
+ input.resolvedPath.skillName,
+ input.resolvedPath.filePath,
+ );
+ const documents = await this.deps.agentDocumentModel.findByAgent(input.agentId);
+
+ if (!input.resolvedPath.filePath) {
+ assertSkillDocument(getSkillFolder(documents, this.config.namespace, skillName, topicId));
+ return buildSkillDirectoryNode(this.config.namespace, skillName);
+ }
+
+ const document = assertSkillDocument(
+ getSkillFile(documents, this.config.namespace, skillName, topicId),
+ );
+ const content = await projectDocumentContent(document);
+
+ return buildSkillFileNode({
+ content,
+ namespace: this.config.namespace,
+ skillName,
+ });
+ }
+
+ async list(input: SkillMountProviderRequest): Promise<SkillMountNode[]> {
+ const topicId = this.getTopicId(input.topicId);
+ const documents = getScopedSkillDocuments(
+ await this.deps.agentDocumentModel.findByAgent(input.agentId),
+ this.config.namespace,
+ topicId,
+ );
+
+ if (!input.resolvedPath.skillName) {
+ return sortSkillFolders(
+ listScopedSkillFolders(documents, this.config.namespace, topicId),
+ ).map((document) =>
+ buildSkillDirectoryNode(
+ this.config.namespace,
+ getSkillMetadata(document)?.skillName ?? document.filename,
+ ),
+ );
+ }
+
+ const skillName = getResolvedSkillName(
+ input.resolvedPath.skillName,
+ input.resolvedPath.filePath,
+ );
+ assertSkillDocument(getSkillFolder(documents, this.config.namespace, skillName, topicId));
+
+ return [
+ buildSkillFileNode({
+ namespace: this.config.namespace,
+ skillName,
+ }),
+ ];
+ }
+
+ async create(input: CreateSkillInput): Promise<SkillMountNode> {
+ const topicId = this.getTopicId(input.topicId);
+ const skillName = getValidatedSkillName(input.skillName, 'skillName');
+ const documents = await this.deps.agentDocumentModel.findByAgent(input.agentId);
+
+ if (getSkillFolder(documents, this.config.namespace, skillName, topicId)) {
+ throw new AgentDocumentVfsError(`Skill "${skillName}" already exists`, 'CONFLICT');
+ }
+
+ const snapshot = await createMarkdownEditorSnapshot(input.content);
+
+ await createSkillTree({
+ agentDocumentModel: this.deps.agentDocumentModel,
+ agentId: input.agentId,
+ content: snapshot.content,
+ documentService: this.deps.documentService,
+ editorData: snapshot.editorData,
+ namespace: this.config.namespace,
+ skillName,
+ topicId,
+ });
+
+ return buildSkillFileNode({
+ content: snapshot.content,
+ namespace: this.config.namespace,
+ skillName,
+ });
+ }
+
+ async update(input: UpdateSkillInput): Promise<SkillMountNode> {
+ const topicId = this.getTopicId(input.topicId);
+ const resolvedPath = SkillMountPathResolver.resolve(input.path);
+ const skillName = getResolvedSkillName(resolvedPath.skillName, resolvedPath.filePath);
+ const documents = await this.deps.agentDocumentModel.findByAgent(input.agentId);
+ const document = assertSkillDocument(
+ getSkillFile(documents, this.config.namespace, skillName, topicId),
+ );
+ const existingContent = await projectDocumentContent(document);
+ const snapshot = await createMarkdownEditorSnapshot(input.content);
+
+ if (existingContent !== snapshot.content) {
+ await this.deps.documentService.trySaveCurrentDocumentHistory(
+ document.documentId,
+ 'llm_call',
+ );
+ }
+
+ await this.deps.agentDocumentModel.update(document.id, {
+ content: snapshot.content,
+ editorData: snapshot.editorData,
+ });
+
+ return buildSkillFileNode({
+ content: snapshot.content,
+ namespace: this.config.namespace,
+ skillName,
+ });
+ }
+
+ async delete(input: DeleteSkillInput): Promise<void> {
+ const topicId = this.getTopicId(input.topicId);
+ const resolvedPath = SkillMountPathResolver.resolve(input.path);
+ const skillName = getResolvedSkillName(resolvedPath.skillName, resolvedPath.filePath);
+ const documents = getScopedSkillDocuments(
+ await this.deps.agentDocumentModel.findByAgent(input.agentId),
+ this.config.namespace,
+ topicId,
+ );
+ const folder = assertSkillDocument(
+ getSkillFolder(documents, this.config.namespace, skillName, topicId),
+ );
+
+ await this.deps.documentService.deleteDocument(folder.documentId);
+ }
+
+ private async promoteTopicSkill(input: PromoteSkillInput): Promise<SkillMountNode> {
+ const topicId = getRequiredTopicId(input.topicId);
+ const resolvedPath = SkillMountPathResolver.resolve(input.path);
+ const skillName = getResolvedSkillName(resolvedPath.skillName, resolvedPath.filePath);
+ const targetName = input.targetName
+ ? getValidatedSkillName(input.targetName, 'targetName')
+ : skillName;
+ const documents = await this.deps.agentDocumentModel.findByAgent(input.agentId);
+
+ if (getSkillFolder(documents, 'agent', targetName)) {
+ throw new AgentDocumentVfsError(`Skill "${targetName}" already exists`, 'CONFLICT');
+ }
+
+ const sourceFile = assertSkillDocument(
+ getSkillFile(documents, 'agent-topic', skillName, topicId),
+ );
+ const content = await projectDocumentContent(sourceFile);
+
+ await createSkillTree({
+ agentDocumentModel: this.deps.agentDocumentModel,
+ agentId: input.agentId,
+ content,
+ documentService: this.deps.documentService,
+ editorData: sourceFile.editorData ?? EMPTY_EDITOR_DATA,
+ lineage: {
+ sourceDocumentId: sourceFile.documentId,
+ sourceNamespace: 'agent-topic',
+ sourceSkillName: skillName,
+ sourceTopicId: topicId,
+ },
+ namespace: 'agent',
+ skillName: targetName,
+ });
+
+ return buildSkillFileNode({
+ content,
+ namespace: 'agent',
+ skillName: targetName,
+ });
+ }
+
+ private getTopicId(topicId?: string) {
+ return this.config.namespace === 'agent-topic' ? getRequiredTopicId(topicId) : undefined;
+ }
+}
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsBuiltin.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsBuiltin.ts
new file mode 100644
index 00000000000..d9a143b2dc3
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsBuiltin.ts
@@ -0,0 +1,69 @@
+import { builtinSkills } from '@lobechat/builtin-skills';
+
+import { filterBuiltinSkills } from '@/helpers/skillFilters';
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+
+import type { SkillMountProvider, SkillMountProviderRequest } from '../SkillMount';
+import type { SkillMountNode } from '../types';
+import {
+ buildReadonlyNamespaceRootNode,
+ listReadonlySkillChildren,
+ listReadonlySkillRootNodes,
+ resolveReadonlySkillNode,
+} from './ProviderSkillsReadonly';
+
+export class ProviderSkillsBuiltin implements SkillMountProvider {
+ private readonly skills = filterBuiltinSkills(builtinSkills);
+
+ async get(input: SkillMountProviderRequest): Promise<SkillMountNode> {
+ if (!input.resolvedPath.skillName) {
+ return buildReadonlyNamespaceRootNode('builtin');
+ }
+
+ const skill = this.skills.find((item) => item.identifier === input.resolvedPath.skillName);
+
+ if (!skill) {
+ throw new AgentDocumentVfsError(
+ `Builtin skill "${input.resolvedPath.skillName}" not found`,
+ 'NOT_FOUND',
+ );
+ }
+
+ if (input.resolvedPath.filePath === 'SKILL.md') {
+ return resolveReadonlySkillNode({
+ content: skill.content,
+ namespace: 'builtin',
+ path: input.resolvedPath.filePath,
+ skill,
+ });
+ }
+
+ const resource = input.resolvedPath.filePath
+ ? skill.resources?.[input.resolvedPath.filePath]
+ : undefined;
+
+ return resolveReadonlySkillNode({
+ content: resource?.content,
+ namespace: 'builtin',
+ path: input.resolvedPath.filePath,
+ skill,
+ });
+ }
+
+ async list(input: SkillMountProviderRequest): Promise<SkillMountNode[]> {
+ if (!input.resolvedPath.skillName) {
+ return listReadonlySkillRootNodes('builtin', this.skills);
+ }
+
+ const skill = this.skills.find((item) => item.identifier === input.resolvedPath.skillName);
+
+ if (!skill) {
+ throw new AgentDocumentVfsError(
+ `Builtin skill "${input.resolvedPath.skillName}" not found`,
+ 'NOT_FOUND',
+ );
+ }
+
+ return listReadonlySkillChildren('builtin', skill, input.resolvedPath.filePath);
+ }
+}
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledActive.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledActive.ts
new file mode 100644
index 00000000000..9db813ab17d
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledActive.ts
@@ -0,0 +1,132 @@
+import type { SkillItem, SkillListItem, SkillResourceMeta } from '@lobechat/types';
+
+import type { AgentModel } from '@/database/models/agent';
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+import type { SkillResourceService } from '@/server/services/skill/resource';
+
+import type { SkillMountProvider, SkillMountProviderRequest } from '../SkillMount';
+import type { SkillMountNode } from '../types';
+import {
+ buildReadonlyNamespaceRootNode,
+ listReadonlySkillChildren,
+ listReadonlySkillRootNodes,
+ resolveReadonlySkillNode,
+} from './ProviderSkillsReadonly';
+
+interface InstalledActiveSkillModelLike {
+ findAll: () => Promise<{ data: SkillListItem[]; total: number }>;
+ findByIdentifier: (identifier: string) => Promise<SkillItem | undefined>;
+}
+
+interface ProviderSkillsInstalledActiveDeps {
+ agentModel: Pick<AgentModel, 'getAgentConfigById'>;
+ skillModel: InstalledActiveSkillModelLike;
+ skillResourceService: Pick<SkillResourceService, 'readResource'>;
+}
+
+interface InstalledSkillProjection {
+ content?: string | null;
+ identifier: string;
+ resources?: Record<string, SkillResourceMeta> | null;
+}
+
+export class ProviderSkillsInstalledActive implements SkillMountProvider {
+ constructor(private readonly deps: ProviderSkillsInstalledActiveDeps) {}
+
+ private async getEnabledIdentifiers(agentId: string) {
+ const agent = await this.deps.agentModel.getAgentConfigById(agentId);
+ return new Set(agent?.plugins ?? []);
+ }
+
+ private async findSkillByIdentifier(
+ agentId: string,
+ identifier: string,
+ ): Promise<InstalledSkillProjection> {
+ const enabledIdentifiers = await this.getEnabledIdentifiers(agentId);
+
+ if (!enabledIdentifiers.has(identifier)) {
+ throw new AgentDocumentVfsError(
+ `Active installed skill "${identifier}" not found`,
+ 'NOT_FOUND',
+ );
+ }
+
+ const skill = await this.deps.skillModel.findByIdentifier(identifier);
+
+ if (!skill) {
+ throw new AgentDocumentVfsError(
+ `Active installed skill "${identifier}" not found`,
+ 'NOT_FOUND',
+ );
+ }
+
+ return skill;
+ }
+
+ private async readResource(skill: InstalledSkillProjection, path: string) {
+ if (!skill.resources) {
+ throw new AgentDocumentVfsError(
+ `Installed skill "${skill.identifier}" has no resources`,
+ 'NOT_FOUND',
+ );
+ }
+
+ const resource = await this.deps.skillResourceService.readResource(skill.resources, path);
+
+ return resource.content;
+ }
+
+ async get(input: SkillMountProviderRequest): Promise<SkillMountNode> {
+ if (!input.resolvedPath.skillName) {
+ return buildReadonlyNamespaceRootNode('installed-active');
+ }
+
+ const skill = await this.findSkillByIdentifier(input.agentId, input.resolvedPath.skillName);
+
+ if (!input.resolvedPath.filePath) {
+ return resolveReadonlySkillNode({ namespace: 'installed-active', skill });
+ }
+
+ if (input.resolvedPath.filePath !== 'SKILL.md') {
+ const node = resolveReadonlySkillNode({
+ namespace: 'installed-active',
+ path: input.resolvedPath.filePath,
+ skill,
+ });
+
+ if (node.type === 'directory') {
+ return node;
+ }
+ }
+
+ const content =
+ input.resolvedPath.filePath === 'SKILL.md'
+ ? (skill.content ?? '')
+ : await this.readResource(skill, input.resolvedPath.filePath);
+
+ return resolveReadonlySkillNode({
+ content,
+ namespace: 'installed-active',
+ path: input.resolvedPath.filePath,
+ skill,
+ });
+ }
+
+ async list(input: SkillMountProviderRequest): Promise<SkillMountNode[]> {
+ if (!input.resolvedPath.skillName) {
+ const enabledIdentifiers = await this.getEnabledIdentifiers(input.agentId);
+ const { data } = await this.deps.skillModel.findAll();
+
+ return listReadonlySkillRootNodes(
+ 'installed-active',
+ data
+ .filter((skill) => enabledIdentifiers.has(skill.identifier))
+ .map((skill) => ({ identifier: skill.identifier })),
+ );
+ }
+
+ const skill = await this.findSkillByIdentifier(input.agentId, input.resolvedPath.skillName);
+
+ return listReadonlySkillChildren('installed-active', skill, input.resolvedPath.filePath);
+ }
+}
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledAll.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledAll.ts
new file mode 100644
index 00000000000..a3bcc8303d0
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsInstalledAll.ts
@@ -0,0 +1,107 @@
+import type { SkillItem, SkillListItem, SkillResourceMeta } from '@lobechat/types';
+
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+import type { SkillResourceService } from '@/server/services/skill/resource';
+
+import type { SkillMountProvider, SkillMountProviderRequest } from '../SkillMount';
+import type { SkillMountNode } from '../types';
+import {
+ buildReadonlyNamespaceRootNode,
+ listReadonlySkillChildren,
+ listReadonlySkillRootNodes,
+ resolveReadonlySkillNode,
+} from './ProviderSkillsReadonly';
+
+interface InstalledSkillModelLike {
+ findAll: () => Promise<{ data: SkillListItem[]; total: number }>;
+ findByIdentifier: (identifier: string) => Promise<SkillItem | undefined>;
+}
+
+interface ProviderSkillsInstalledAllDeps {
+ skillModel: InstalledSkillModelLike;
+ skillResourceService: Pick<SkillResourceService, 'readResource'>;
+}
+
+interface InstalledSkillProjection {
+ content?: string | null;
+ identifier: string;
+ resources?: Record<string, SkillResourceMeta> | null;
+}
+
+export class ProviderSkillsInstalledAll implements SkillMountProvider {
+ constructor(private readonly deps: ProviderSkillsInstalledAllDeps) {}
+
+ private async findSkillByIdentifier(identifier: string): Promise<InstalledSkillProjection> {
+ const skill = await this.deps.skillModel.findByIdentifier(identifier);
+
+ if (!skill) {
+ throw new AgentDocumentVfsError(`Installed skill "${identifier}" not found`, 'NOT_FOUND');
+ }
+
+ return skill;
+ }
+
+ private async readResource(skill: InstalledSkillProjection, path: string) {
+ if (!skill.resources) {
+ throw new AgentDocumentVfsError(
+ `Installed skill "${skill.identifier}" has no resources`,
+ 'NOT_FOUND',
+ );
+ }
+
+ const resource = await this.deps.skillResourceService.readResource(skill.resources, path);
+
+ return resource.content;
+ }
+
+ async get(input: SkillMountProviderRequest): Promise<SkillMountNode> {
+ if (!input.resolvedPath.skillName) {
+ return buildReadonlyNamespaceRootNode('installed-all');
+ }
+
+ const skill = await this.findSkillByIdentifier(input.resolvedPath.skillName);
+
+ if (!input.resolvedPath.filePath) {
+ return resolveReadonlySkillNode({ namespace: 'installed-all', skill });
+ }
+
+ if (input.resolvedPath.filePath !== 'SKILL.md') {
+ const node = resolveReadonlySkillNode({
+ namespace: 'installed-all',
+ path: input.resolvedPath.filePath,
+ skill,
+ });
+
+ if (node.type === 'directory') {
+ return node;
+ }
+ }
+
+ const content =
+ input.resolvedPath.filePath === 'SKILL.md'
+ ? (skill.content ?? '')
+ : await this.readResource(skill, input.resolvedPath.filePath);
+
+ return resolveReadonlySkillNode({
+ content,
+ namespace: 'installed-all',
+ path: input.resolvedPath.filePath,
+ skill,
+ });
+ }
+
+ async list(input: SkillMountProviderRequest): Promise<SkillMountNode[]> {
+ if (!input.resolvedPath.skillName) {
+ const { data } = await this.deps.skillModel.findAll();
+
+ return listReadonlySkillRootNodes(
+ 'installed-all',
+ data.map((skill) => ({ identifier: skill.identifier })),
+ );
+ }
+
+ const skill = await this.findSkillByIdentifier(input.resolvedPath.skillName);
+
+ return listReadonlySkillChildren('installed-all', skill, input.resolvedPath.filePath);
+ }
+}
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.test.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.test.ts
new file mode 100644
index 00000000000..c0689d84134
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.test.ts
@@ -0,0 +1,352 @@
+// @vitest-environment node
+import { builtinSkills } from '@lobechat/builtin-skills';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { filterBuiltinSkills } from '@/helpers/skillFilters';
+
+import { ProviderSkillsBuiltin } from './ProviderSkillsBuiltin';
+import { ProviderSkillsInstalledActive } from './ProviderSkillsInstalledActive';
+import { ProviderSkillsInstalledAll } from './ProviderSkillsInstalledAll';
+
+describe('readonly skill providers', () => {
+ const builtinSkill = filterBuiltinSkills(builtinSkills)[0];
+ const builtinSkillWithResources = filterBuiltinSkills(builtinSkills).find(
+ (skill) => skill.resources && Object.keys(skill.resources).length > 0,
+ );
+
+ describe('ProviderSkillsBuiltin', () => {
+ it('lists builtin skill directories at the namespace root by identifier', async () => {
+ const provider = new ProviderSkillsBuiltin();
+
+ const result = await provider.list({
+ agentId: 'agent-1',
+ path: './lobe/skills/builtin/skills',
+ resolvedPath: {
+ namespace: 'builtin',
+ relativePath: '',
+ },
+ });
+
+ expect(
+ result.some(
+ (node) =>
+ node.name === builtinSkill.identifier &&
+ node.path === `./lobe/skills/builtin/skills/${builtinSkill.identifier}` &&
+ node.type === 'directory',
+ ),
+ ).toBe(true);
+ });
+
+ it('reads SKILL.md content for a builtin skill from the identifier path', async () => {
+ const provider = new ProviderSkillsBuiltin();
+
+ const result = await provider.get({
+ agentId: 'agent-1',
+ path: `./lobe/skills/builtin/skills/${builtinSkill.identifier}/SKILL.md`,
+ resolvedPath: {
+ filePath: 'SKILL.md',
+ namespace: 'builtin',
+ relativePath: `${builtinSkill.identifier}/SKILL.md`,
+ skillName: builtinSkill.identifier,
+ },
+ });
+
+ expect(result.path).toBe(`./lobe/skills/builtin/skills/${builtinSkill.identifier}/SKILL.md`);
+ expect(result.content).toBe(builtinSkill.content);
+ expect(result.readOnly).toBe(true);
+ expect(result.size).toBe(builtinSkill.content.length);
+ });
+
+ it('projects builtin resources as first-class VFS entries when present', async () => {
+ expect(builtinSkillWithResources).toBeDefined();
+
+ const provider = new ProviderSkillsBuiltin();
+ const [resourcePath] = Object.keys(builtinSkillWithResources!.resources!);
+ const topLevelSegment = resourcePath.split('/')[0];
+
+ const result = await provider.list({
+ agentId: 'agent-1',
+ path: `./lobe/skills/builtin/skills/${builtinSkillWithResources!.identifier}`,
+ resolvedPath: {
+ namespace: 'builtin',
+ relativePath: builtinSkillWithResources!.identifier,
+ skillName: builtinSkillWithResources!.identifier,
+ },
+ });
+
+ expect(result).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'SKILL.md',
+ path: `./lobe/skills/builtin/skills/${builtinSkillWithResources!.identifier}/SKILL.md`,
+ size: builtinSkillWithResources!.content.length,
+ type: 'file',
+ }),
+ expect.objectContaining({
+ name: topLevelSegment,
+ path: `./lobe/skills/builtin/skills/${builtinSkillWithResources!.identifier}/${topLevelSegment}`,
+ }),
+ ]),
+ );
+ });
+ });
+
+ describe('ProviderSkillsInstalledAll', () => {
+ const skillModel = {
+ findAll: vi.fn(),
+ findByIdentifier: vi.fn(),
+ };
+ const skillResourceService = {
+ readResource: vi.fn(),
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('lists installed skills from persisted storage by identifier', async () => {
+ skillModel.findAll.mockResolvedValue({
+ data: [{ id: 'skill-1', identifier: 'skill.one', name: 'Skill One' }],
+ total: 1,
+ });
+
+ const provider = new ProviderSkillsInstalledAll({
+ skillModel,
+ skillResourceService,
+ });
+ const result = await provider.list({
+ agentId: 'agent-1',
+ path: './lobe/skills/installed/all/skills',
+ resolvedPath: {
+ namespace: 'installed-all',
+ relativePath: '',
+ },
+ });
+
+ expect(result).toEqual([
+ expect.objectContaining({
+ name: 'skill.one',
+ namespace: 'installed-all',
+ path: './lobe/skills/installed/all/skills/skill.one',
+ type: 'directory',
+ }),
+ ]);
+ });
+
+ it('reads resource files through SkillResourceService', async () => {
+ skillModel.findByIdentifier.mockResolvedValue({
+ content: '# Skill One\n\nPersisted content.',
+ id: 'skill-1',
+ identifier: 'skill.one',
+ name: 'Skill One',
+ resources: {
+ 'docs/guide.md': {
+ fileHash: 'hash-guide',
+ size: 9,
+ },
+ },
+ });
+ skillResourceService.readResource.mockResolvedValue({
+ content: '# Guide',
+ encoding: 'utf8',
+ fileHash: 'hash-guide',
+ fileType: 'text/markdown',
+ path: 'docs/guide.md',
+ size: 7,
+ });
+
+ const provider = new ProviderSkillsInstalledAll({
+ skillModel,
+ skillResourceService,
+ });
+ const result = await provider.get({
+ agentId: 'agent-1',
+ path: './lobe/skills/installed/all/skills/skill.one/docs/guide.md',
+ resolvedPath: {
+ filePath: 'docs/guide.md',
+ namespace: 'installed-all',
+ relativePath: 'skill.one/docs/guide.md',
+ skillName: 'skill.one',
+ },
+ });
+
+ expect(result.content).toBe('# Guide');
+ expect(result.path).toBe('./lobe/skills/installed/all/skills/skill.one/docs/guide.md');
+ expect(skillResourceService.readResource).toHaveBeenCalledWith(
+ {
+ 'docs/guide.md': {
+ fileHash: 'hash-guide',
+ size: 9,
+ },
+ },
+ 'docs/guide.md',
+ );
+ });
+
+ it('returns resource directories as first-class VFS nodes without reading file content', async () => {
+ skillModel.findByIdentifier.mockResolvedValue({
+ content: '# Skill One\n\nPersisted content.',
+ id: 'skill-1',
+ identifier: 'skill.one',
+ name: 'Skill One',
+ resources: {
+ 'docs/guide.md': {
+ fileHash: 'hash-guide',
+ size: 9,
+ },
+ },
+ });
+
+ const provider = new ProviderSkillsInstalledAll({
+ skillModel,
+ skillResourceService,
+ });
+ const result = await provider.get({
+ agentId: 'agent-1',
+ path: './lobe/skills/installed/all/skills/skill.one/docs',
+ resolvedPath: {
+ filePath: 'docs',
+ namespace: 'installed-all',
+ relativePath: 'skill.one/docs',
+ skillName: 'skill.one',
+ },
+ });
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ name: 'docs',
+ path: './lobe/skills/installed/all/skills/skill.one/docs',
+ type: 'directory',
+ }),
+ );
+ expect(skillResourceService.readResource).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('ProviderSkillsInstalledActive', () => {
+ const agentModel = {
+ getAgentConfigById: vi.fn(),
+ };
+ const skillModel = {
+ findAll: vi.fn(),
+ findByIdentifier: vi.fn(),
+ };
+ const skillResourceService = {
+ readResource: vi.fn(),
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('filters installed skills by the agent plugin identifiers', async () => {
+ agentModel.getAgentConfigById.mockResolvedValue({
+ plugins: ['skill.one'],
+ });
+ skillModel.findAll.mockResolvedValue({
+ data: [
+ { id: 'skill-1', identifier: 'skill.one', name: 'Skill One' },
+ { id: 'skill-2', identifier: 'skill.two', name: 'Skill Two' },
+ ],
+ total: 2,
+ });
+
+ const provider = new ProviderSkillsInstalledActive({
+ agentModel,
+ skillModel,
+ skillResourceService,
+ });
+ const result = await provider.list({
+ agentId: 'agent-1',
+ path: './lobe/skills/installed/active/skills',
+ resolvedPath: {
+ namespace: 'installed-active',
+ relativePath: '',
+ },
+ });
+
+ expect(result).toEqual([
+ expect.objectContaining({
+ name: 'skill.one',
+ namespace: 'installed-active',
+ path: './lobe/skills/installed/active/skills/skill.one',
+ type: 'directory',
+ }),
+ ]);
+ });
+
+ it('reads SKILL.md only for active installed skills', async () => {
+ agentModel.getAgentConfigById.mockResolvedValue({
+ plugins: ['skill.one'],
+ });
+ skillModel.findByIdentifier.mockResolvedValue({
+ content: '# Skill One\n\nActive content.',
+ id: 'skill-1',
+ identifier: 'skill.one',
+ name: 'Skill One',
+ });
+
+ const provider = new ProviderSkillsInstalledActive({
+ agentModel,
+ skillModel,
+ skillResourceService,
+ });
+ const result = await provider.get({
+ agentId: 'agent-1',
+ path: './lobe/skills/installed/active/skills/skill.one/SKILL.md',
+ resolvedPath: {
+ filePath: 'SKILL.md',
+ namespace: 'installed-active',
+ relativePath: 'skill.one/SKILL.md',
+ skillName: 'skill.one',
+ },
+ });
+
+ expect(result.content).toBe('# Skill One\n\nActive content.');
+ expect(result.readOnly).toBe(true);
+ });
+
+ it('returns active resource directories as VFS directory nodes', async () => {
+ agentModel.getAgentConfigById.mockResolvedValue({
+ plugins: ['skill.one'],
+ });
+ skillModel.findByIdentifier.mockResolvedValue({
+ content: '# Skill One\n\nActive content.',
+ id: 'skill-1',
+ identifier: 'skill.one',
+ name: 'Skill One',
+ resources: {
+ 'docs/guide.md': {
+ fileHash: 'hash-guide',
+ size: 9,
+ },
+ },
+ });
+
+ const provider = new ProviderSkillsInstalledActive({
+ agentModel,
+ skillModel,
+ skillResourceService,
+ });
+ const result = await provider.get({
+ agentId: 'agent-1',
+ path: './lobe/skills/installed/active/skills/skill.one/docs',
+ resolvedPath: {
+ filePath: 'docs',
+ namespace: 'installed-active',
+ relativePath: 'skill.one/docs',
+ skillName: 'skill.one',
+ },
+ });
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ name: 'docs',
+ path: './lobe/skills/installed/active/skills/skill.one/docs',
+ type: 'directory',
+ }),
+ );
+ expect(skillResourceService.readResource).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.ts
new file mode 100644
index 00000000000..172dff0e525
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsReadonly.ts
@@ -0,0 +1,281 @@
+import type { SkillResourceMeta } from '@lobechat/types';
+
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+
+import { getUnifiedSkillNamespaceRootPath, type SkillNamespace } from '../path';
+import type { SkillMountNode } from '../types';
+
+type ReadonlySkillNamespace = Extract<
+ SkillNamespace,
+ 'builtin' | 'installed-active' | 'installed-all'
+>;
+
+interface ReadonlySkillChild {
+ name: string;
+ path: string;
+ size?: number;
+ type: 'directory' | 'file';
+}
+
+interface ReadonlySkillEntry {
+ content?: string | null;
+ identifier: string;
+ resources?: Record<string, SkillResourceMeta> | null;
+}
+
+const sortChildren = (children: ReadonlySkillChild[]) =>
+ children.sort((left, right) => left.name.localeCompare(right.name));
+
+const normalizeResourcePath = (path: string) => path.replace(/^\/+/, '').replace(/\/+$/, '');
+
+const listResourceChildren = (
+ resources: Record<string, SkillResourceMeta> | null | undefined,
+ parentPath?: string,
+): ReadonlySkillChild[] => {
+ if (!resources) return [];
+
+ const normalizedParentPath = parentPath ? normalizeResourcePath(parentPath) : undefined;
+ const children = new Map<string, ReadonlySkillChild>();
+
+ for (const resourcePath of Object.keys(resources)) {
+ const normalizedResourcePath = normalizeResourcePath(resourcePath);
+ const resource = resources[resourcePath] ?? resources[normalizedResourcePath];
+
+ if (!normalizedResourcePath) continue;
+
+ if (normalizedParentPath && !normalizedResourcePath.startsWith(`${normalizedParentPath}/`))
+ continue;
+
+ const remainder = normalizedParentPath
+ ? normalizedResourcePath.slice(normalizedParentPath.length + 1)
+ : normalizedResourcePath;
+
+ if (!remainder) continue;
+
+ const separatorIndex = remainder.indexOf('/');
+ const childName = separatorIndex === -1 ? remainder : remainder.slice(0, separatorIndex);
+ const childPath = normalizedParentPath ? `${normalizedParentPath}/${childName}` : childName;
+
+ if (!children.has(childPath)) {
+ children.set(childPath, {
+ name: childName,
+ path: childPath,
+ ...(separatorIndex === -1 && resource ? { size: resource.size } : {}),
+ type: separatorIndex === -1 ? 'file' : 'directory',
+ });
+ }
+ }
+
+ return sortChildren([...children.values()]);
+};
+
+const hasResourcePath = (
+ resources: Record<string, SkillResourceMeta> | null | undefined,
+ path: string,
+): boolean => {
+ if (!resources) return false;
+
+ const normalizedPath = normalizeResourcePath(path);
+
+ if (!normalizedPath) return false;
+ if (normalizedPath in resources) return true;
+
+ return Object.keys(resources).some((resourcePath) =>
+ normalizeResourcePath(resourcePath).startsWith(`${normalizedPath}/`),
+ );
+};
+
+export const buildReadonlyNamespaceRootNode = (
+ namespace: ReadonlySkillNamespace,
+): SkillMountNode => ({
+ name: 'skills',
+ namespace,
+ path: getUnifiedSkillNamespaceRootPath(namespace),
+ readOnly: true,
+ type: 'directory',
+});
+
+export const buildReadonlySkillDirectoryNode = (
+ namespace: ReadonlySkillNamespace,
+ skillIdentifier: string,
+): SkillMountNode => ({
+ name: skillIdentifier,
+ namespace,
+ path: `${getUnifiedSkillNamespaceRootPath(namespace)}/${skillIdentifier}`,
+ readOnly: true,
+ type: 'directory',
+});
+
+export const buildReadonlySkillFileNode = ({
+ content,
+ filePath = 'SKILL.md',
+ namespace,
+ size,
+ skillIdentifier,
+}: {
+ content?: string;
+ filePath?: string;
+ namespace: ReadonlySkillNamespace;
+ size?: number;
+ skillIdentifier: string;
+}): SkillMountNode => ({
+ ...(content !== undefined ? { content } : {}),
+ ...(filePath.endsWith('.md') ? { contentType: 'text/markdown' as const } : {}),
+ name: filePath.split('/').pop() || filePath,
+ namespace,
+ path: `${getUnifiedSkillNamespaceRootPath(namespace)}/${skillIdentifier}/${filePath}`,
+ readOnly: true,
+ ...((size ?? content?.length) !== undefined ? { size: size ?? content?.length } : {}),
+ type: 'file',
+});
+
+export const buildReadonlySkillResourceDirectoryNode = ({
+ namespace,
+ resourcePath,
+ skillIdentifier,
+}: {
+ namespace: ReadonlySkillNamespace;
+ resourcePath: string;
+ skillIdentifier: string;
+}): SkillMountNode => ({
+ name: resourcePath.split('/').pop() || resourcePath,
+ namespace,
+ path: `${getUnifiedSkillNamespaceRootPath(namespace)}/${skillIdentifier}/${resourcePath}`,
+ readOnly: true,
+ type: 'directory',
+});
+
+export const listReadonlySkillRootNodes = (
+ namespace: ReadonlySkillNamespace,
+ skills: ReadonlySkillEntry[],
+) =>
+ sortChildren(
+ skills.map((skill) => ({
+ name: skill.identifier,
+ path: `${getUnifiedSkillNamespaceRootPath(namespace)}/${skill.identifier}`,
+ type: 'directory' as const,
+ })),
+ ).map((skill) => buildReadonlySkillDirectoryNode(namespace, skill.name));
+
+export const listReadonlySkillChildren = (
+ namespace: ReadonlySkillNamespace,
+ skill: ReadonlySkillEntry,
+ directoryPath?: string,
+) => {
+ if (!directoryPath) {
+ const children = [
+ buildReadonlySkillFileNode({
+ content: skill.content ?? '',
+ namespace,
+ skillIdentifier: skill.identifier,
+ }),
+ ...listResourceChildren(skill.resources).map((child) =>
+ child.type === 'directory'
+ ? buildReadonlySkillResourceDirectoryNode({
+ namespace,
+ resourcePath: child.path,
+ skillIdentifier: skill.identifier,
+ })
+ : buildReadonlySkillFileNode({
+ filePath: child.path,
+ namespace,
+ size: child.size,
+ skillIdentifier: skill.identifier,
+ }),
+ ),
+ ];
+
+ return children.sort((left, right) => left.name.localeCompare(right.name));
+ }
+
+ if (directoryPath === 'SKILL.md') {
+ return [
+ buildReadonlySkillFileNode({
+ content: skill.content ?? '',
+ namespace,
+ skillIdentifier: skill.identifier,
+ }),
+ ];
+ }
+
+ const children = listResourceChildren(skill.resources, directoryPath);
+
+ if (children.length === 0) {
+ if (!hasResourcePath(skill.resources, directoryPath)) {
+ throw new AgentDocumentVfsError(
+ `Skill resource path "${directoryPath}" not found`,
+ 'NOT_FOUND',
+ );
+ }
+
+ return [
+ buildReadonlySkillFileNode({
+ filePath: directoryPath,
+ namespace,
+ size: skill.resources?.[directoryPath]?.size,
+ skillIdentifier: skill.identifier,
+ }),
+ ];
+ }
+
+ return children.map((child) =>
+ child.type === 'directory'
+ ? buildReadonlySkillResourceDirectoryNode({
+ namespace,
+ resourcePath: child.path,
+ skillIdentifier: skill.identifier,
+ })
+ : buildReadonlySkillFileNode({
+ filePath: child.path,
+ namespace,
+ size: child.size,
+ skillIdentifier: skill.identifier,
+ }),
+ );
+};
+
+export const resolveReadonlySkillNode = ({
+ content,
+ namespace,
+ path,
+ skill,
+}: {
+ content?: string;
+ namespace: ReadonlySkillNamespace;
+ path?: string;
+ skill: ReadonlySkillEntry;
+}): SkillMountNode => {
+ if (!path) {
+ return buildReadonlySkillDirectoryNode(namespace, skill.identifier);
+ }
+
+ if (path === 'SKILL.md') {
+ return buildReadonlySkillFileNode({
+ content: content ?? skill.content ?? '',
+ namespace,
+ skillIdentifier: skill.identifier,
+ });
+ }
+
+ const children = listResourceChildren(skill.resources, path);
+
+ if (children.length > 0) {
+ return buildReadonlySkillResourceDirectoryNode({
+ namespace,
+ resourcePath: path,
+ skillIdentifier: skill.identifier,
+ });
+ }
+
+ if (!hasResourcePath(skill.resources, path)) {
+ throw new AgentDocumentVfsError(`Skill resource path "${path}" not found`, 'NOT_FOUND');
+ }
+
+ return buildReadonlySkillFileNode({
+ content,
+ filePath: path,
+ namespace,
+ size: skill.resources?.[path]?.size,
+ skillIdentifier: skill.identifier,
+ });
+};
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils.ts
new file mode 100644
index 00000000000..a89fa2cca4b
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils.ts
@@ -0,0 +1,479 @@
+import type { AgentDocument } from '@/database/models/agentDocuments';
+import { PolicyLoad } from '@/database/models/agentDocuments';
+import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';
+import { exportEditorDataSnapshot } from '@/server/services/agentDocuments/headlessEditor';
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+
+import { getUnifiedSkillNamespaceRootPath } from '../path';
+import type { SkillMountNode } from '../types';
+
+export interface AgentSkillDocumentModelLike {
+ associate: (params: {
+ agentId: string;
+ documentId: string;
+ policyLoad?: PolicyLoad;
+ uniqueSibling?: boolean;
+ }) => Promise<{
+ id: string;
+ }>;
+ delete: (documentId: string, deleteReason?: string) => Promise<void>;
+ findByAgent: (agentId: string) => Promise<AgentDocument[]>;
+ update: (
+ documentId: string,
+ params?: {
+ content?: string;
+ editorData?: Record<string, any>;
+ metadata?: Record<string, any>;
+ policyLoad?: PolicyLoad;
+ },
+ ) => Promise<void>;
+}
+
+export interface DocumentTreeServiceLike {
+ createDocument: (params: {
+ content?: string;
+ editorData: Record<string, any>;
+ fileType?: string;
+ metadata?: Record<string, any>;
+ parentId?: string;
+ title: string;
+ }) => Promise<{
+ content: string | null;
+ documentId?: string;
+ editorData: Record<string, any> | null;
+ fileType: string;
+ filename: string | null;
+ id: string;
+ metadata: Record<string, any> | null;
+ parentId: string | null;
+ title: string | null;
+ }>;
+ deleteDocument: (id: string) => Promise<unknown>;
+ trySaveCurrentDocumentHistory: (documentId: string, saveSource: 'llm_call') => Promise<unknown>;
+ updateDocument: (
+ id: string,
+ params: {
+ content?: string;
+ editorData?: Record<string, any>;
+ metadata?: Record<string, any>;
+ parentId?: string | null;
+ saveSource?: 'llm_call';
+ title?: string;
+ },
+ ) => Promise<unknown>;
+}
+
+export interface ProviderSkillsAgentDocumentDeps {
+ agentDocumentModel: AgentSkillDocumentModelLike;
+ documentService: DocumentTreeServiceLike;
+}
+
+export interface CreateSkillTreeInput {
+ agentDocumentModel: AgentSkillDocumentModelLike;
+ agentId: string;
+ content: string;
+ documentService: DocumentTreeServiceLike;
+ editorData: Record<string, any>;
+ lineage?: LobeSkillMetadata['lineage'];
+ namespace: 'agent' | 'agent-topic';
+ skillName: string;
+ topicId?: string;
+}
+
+export interface LobeSkillMetadata {
+ lineage?: {
+ sourceDocumentId: string;
+ sourceNamespace: 'agent-topic';
+ sourceSkillName?: string;
+ sourceTopicId?: string;
+ };
+ namespace: 'agent' | 'agent-topic';
+ role: 'namespace-root' | 'skill-file' | 'skill-folder';
+ skillName?: string;
+ topicId?: string;
+}
+
+export const EMPTY_EDITOR_DATA = { root: { children: [], type: 'root' } };
+
+export const SKILL_FILE_NAME = 'SKILL.md';
+
+export const buildSkillDirectoryNode = (
+ namespace: Extract<SkillMountNode['namespace'], 'agent' | 'agent-topic'>,
+ skillName: string,
+): SkillMountNode => ({
+ name: skillName,
+ namespace,
+ path: `${getUnifiedSkillNamespaceRootPath(namespace)}/${skillName}`,
+ readOnly: false,
+ type: 'directory',
+});
+
+export const buildSkillNamespaceRootNode = (
+ namespace: Extract<SkillMountNode['namespace'], 'agent' | 'agent-topic'>,
+): SkillMountNode => ({
+ name: 'skills',
+ namespace,
+ path: getUnifiedSkillNamespaceRootPath(namespace),
+ readOnly: false,
+ type: 'directory',
+});
+
+export const buildSkillFileNode = ({
+ content,
+ namespace,
+ skillName,
+}: {
+ content?: string;
+ namespace: Extract<SkillMountNode['namespace'], 'agent' | 'agent-topic'>;
+ skillName: string;
+}): SkillMountNode => ({
+ ...(content !== undefined ? { content } : {}),
+ contentType: 'text/markdown',
+ name: SKILL_FILE_NAME,
+ namespace,
+ path: `${getUnifiedSkillNamespaceRootPath(namespace)}/${skillName}/${SKILL_FILE_NAME}`,
+ readOnly: false,
+ type: 'file',
+});
+
+export const getValidatedSkillName = (
+ name: string,
+ fieldName: 'skillName' | 'targetName',
+): string => {
+ const trimmed = name.trim();
+
+ if (
+ !trimmed ||
+ trimmed === '.' ||
+ trimmed === '..' ||
+ trimmed.includes('/') ||
+ trimmed.includes('\\')
+ ) {
+ throw new AgentDocumentVfsError(
+ `Invalid ${fieldName}: expected a non-empty single path segment`,
+ 'BAD_REQUEST',
+ );
+ }
+
+ return trimmed;
+};
+
+export const getRequiredTopicId = (topicId?: string) => {
+ if (!topicId) {
+ throw new AgentDocumentVfsError(
+ 'Topic ID is required for the agent-topic namespace',
+ 'BAD_REQUEST',
+ );
+ }
+
+ return topicId;
+};
+
+export const getResolvedSkillName = (skillName?: string, filePath?: string) => {
+ if (!skillName) {
+ throw new AgentDocumentVfsError('Skill path must include a skill name', 'BAD_REQUEST');
+ }
+
+ if (filePath && filePath !== SKILL_FILE_NAME) {
+ throw new AgentDocumentVfsError(`Unsupported skill file path "${filePath}"`, 'BAD_REQUEST');
+ }
+
+ return skillName;
+};
+
+export const projectDocumentContent = async (document: AgentDocument) => {
+ try {
+ const snapshot = await exportEditorDataSnapshot({
+ editorData: document.editorData,
+ fallbackContent: document.content,
+ });
+
+ if (snapshot.content.trim().length === 0 && document.content.trim().length > 0) {
+ return document.content;
+ }
+
+ return snapshot.content;
+ } catch {
+ return document.content;
+ }
+};
+
+export const getSkillMetadata = (document: Pick<AgentDocument, 'metadata'>) => {
+ const metadata = document.metadata as { lobeSkill?: LobeSkillMetadata } | null;
+ return metadata?.lobeSkill;
+};
+
+export const isManagedSkillDocument = (document: Pick<AgentDocument, 'metadata'>) =>
+ Boolean(getSkillMetadata(document));
+
+export const isSkillDocumentInScope = (
+ document: Pick<AgentDocument, 'metadata'>,
+ namespace: 'agent' | 'agent-topic',
+ topicId?: string,
+) => {
+ const metadata = getSkillMetadata(document);
+
+ if (!metadata || metadata.namespace !== namespace) {
+ return false;
+ }
+
+ if (namespace === 'agent-topic') {
+ return metadata.topicId === topicId;
+ }
+
+ return !metadata.topicId;
+};
+
+export const getScopedSkillDocuments = (
+ documents: AgentDocument[],
+ namespace: 'agent' | 'agent-topic',
+ topicId?: string,
+) => documents.filter((document) => isSkillDocumentInScope(document, namespace, topicId));
+
+export const getNamespaceRoot = (
+ documents: AgentDocument[],
+ namespace: 'agent' | 'agent-topic',
+ topicId?: string,
+) =>
+ getScopedSkillDocuments(documents, namespace, topicId).find(
+ (document) => getSkillMetadata(document)?.role === 'namespace-root',
+ );
+
+export const getSkillFolder = (
+ documents: AgentDocument[],
+ namespace: 'agent' | 'agent-topic',
+ skillName: string,
+ topicId?: string,
+) => {
+ const root = getNamespaceRoot(documents, namespace, topicId);
+
+ return getScopedSkillDocuments(documents, namespace, topicId).find((document) => {
+ const metadata = getSkillMetadata(document);
+
+ return (
+ metadata?.role === 'skill-folder' &&
+ metadata.skillName === skillName &&
+ (!root || document.parentId === root.documentId)
+ );
+ });
+};
+
+export const getSkillFile = (
+ documents: AgentDocument[],
+ namespace: 'agent' | 'agent-topic',
+ skillName: string,
+ topicId?: string,
+) => {
+ const folder = getSkillFolder(documents, namespace, skillName, topicId);
+
+ return getScopedSkillDocuments(documents, namespace, topicId).find((document) => {
+ const metadata = getSkillMetadata(document);
+
+ return (
+ metadata?.role === 'skill-file' &&
+ metadata.skillName === skillName &&
+ (!folder || document.parentId === folder.documentId)
+ );
+ });
+};
+
+export const listScopedSkillFolders = (
+ documents: AgentDocument[],
+ namespace: 'agent' | 'agent-topic',
+ topicId?: string,
+) => {
+ const root = getNamespaceRoot(documents, namespace, topicId);
+
+ return getScopedSkillDocuments(documents, namespace, topicId).filter((document) => {
+ const metadata = getSkillMetadata(document);
+
+ return metadata?.role === 'skill-folder' && (!root || document.parentId === root.documentId);
+ });
+};
+
+export const assertSkillDocument = <T>(document: T | undefined, message = 'Skill not found') => {
+ if (!document) {
+ throw new AgentDocumentVfsError(message, 'NOT_FOUND');
+ }
+
+ return document;
+};
+
+export const createSkillMetadata = ({
+ lineage,
+ namespace,
+ role,
+ skillName,
+ topicId,
+}: LobeSkillMetadata) => ({
+ lobeSkill: {
+ ...(lineage ? { lineage } : {}),
+ namespace,
+ role,
+ ...(skillName ? { skillName } : {}),
+ ...(topicId ? { topicId } : {}),
+ } satisfies LobeSkillMetadata,
+});
+
+export const ensureNamespaceRoot = async ({
+ agentId,
+ agentDocumentModel,
+ documentService,
+ namespace,
+ topicId,
+}: {
+ agentDocumentModel: AgentSkillDocumentModelLike;
+ agentId: string;
+ documentService: DocumentTreeServiceLike;
+ namespace: 'agent' | 'agent-topic';
+ topicId?: string;
+}): Promise<{ documentId: string }> => {
+ const documents = await agentDocumentModel.findByAgent(agentId);
+ const existingRoot = getNamespaceRoot(documents, namespace, topicId);
+
+ if (existingRoot) {
+ return { documentId: existingRoot.documentId };
+ }
+
+ const root = await documentService.createDocument({
+ editorData: EMPTY_EDITOR_DATA,
+ fileType: DOCUMENT_FOLDER_TYPE,
+ metadata: createSkillMetadata({ namespace, role: 'namespace-root', topicId }),
+ title: 'skills',
+ });
+
+ await agentDocumentModel.associate({
+ agentId,
+ documentId: root.id,
+ policyLoad: PolicyLoad.DISABLED,
+ uniqueSibling: false,
+ });
+
+ return { documentId: root.id };
+};
+
+export const createSkillTree = async ({
+ agentDocumentModel,
+ agentId,
+ content,
+ documentService,
+ editorData,
+ lineage,
+ namespace,
+ skillName,
+ topicId,
+}: CreateSkillTreeInput) => {
+ const existingDocuments = await agentDocumentModel.findByAgent(agentId);
+ const existingRoot = getNamespaceRoot(existingDocuments, namespace, topicId);
+ const existingFolder = getSkillFolder(existingDocuments, namespace, skillName, topicId);
+
+ const root = existingRoot
+ ? { documentId: existingRoot.documentId }
+ : await ensureNamespaceRoot({
+ agentDocumentModel,
+ agentId,
+ documentService,
+ namespace,
+ topicId,
+ });
+
+ const createdRootId: string | undefined = existingRoot ? undefined : root.documentId;
+ let createdFolderId: string | undefined;
+ let createdFileId: string | undefined;
+
+ try {
+ const folder = existingFolder
+ ? { id: existingFolder.documentId }
+ : await documentService.createDocument({
+ editorData: EMPTY_EDITOR_DATA,
+ fileType: DOCUMENT_FOLDER_TYPE,
+ metadata: createSkillMetadata({
+ lineage,
+ namespace,
+ role: 'skill-folder',
+ skillName,
+ topicId,
+ }),
+ parentId: root.documentId,
+ title: skillName,
+ });
+
+ if (!existingFolder) {
+ createdFolderId = folder.id;
+ await agentDocumentModel.associate({
+ agentId,
+ documentId: folder.id,
+ policyLoad: PolicyLoad.DISABLED,
+ uniqueSibling: false,
+ });
+ }
+
+ const file = await documentService.createDocument({
+ content,
+ editorData,
+ metadata: createSkillMetadata({
+ lineage,
+ namespace,
+ role: 'skill-file',
+ skillName,
+ topicId,
+ }),
+ parentId: folder.id,
+ title: SKILL_FILE_NAME,
+ });
+
+ createdFileId = file.id;
+ await agentDocumentModel.associate({ agentId, documentId: file.id, uniqueSibling: false });
+
+ return { fileDocumentId: file.id, folderDocumentId: folder.id };
+ } catch (error) {
+ if (createdFileId) {
+ await documentService.deleteDocument(createdFileId);
+ }
+
+ if (createdFolderId) {
+ await documentService.deleteDocument(createdFolderId);
+ }
+
+ if (createdRootId) {
+ await documentService.deleteDocument(createdRootId);
+ }
+
+ throw error;
+ }
+};
+
+export const sortSkillFolders = (documents: AgentDocument[]) =>
+ [...documents].sort((left, right) => left.filename.localeCompare(right.filename));
+
+export const collectSubtreeBindings = (documents: AgentDocument[], rootDocumentId: string) => {
+ const byParent = new Map<string, AgentDocument[]>();
+
+ for (const document of documents) {
+ if (!document.parentId) continue;
+
+ const children = byParent.get(document.parentId) ?? [];
+ children.push(document);
+ byParent.set(document.parentId, children);
+ }
+
+ const collected: AgentDocument[] = [];
+ const visit = (documentId: string) => {
+ const children = byParent.get(documentId) ?? [];
+
+ for (const child of children) {
+ visit(child.documentId);
+ collected.push(child);
+ }
+ };
+
+ visit(rootDocumentId);
+
+ const root = documents.find((document) => document.documentId === rootDocumentId);
+
+ if (root) {
+ collected.push(root);
+ }
+
+ return collected;
+};
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/types.ts b/src/server/services/agentDocumentVfs/mounts/skills/types.ts
new file mode 100644
index 00000000000..c36d58c8dfe
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/mounts/skills/types.ts
@@ -0,0 +1,22 @@
+export interface SkillMountContext {
+ agentId: string;
+ topicId?: string;
+}
+
+export interface SkillMountNode {
+ content?: string;
+ contentType?: 'text/markdown';
+ name: string;
+ namespace: 'builtin' | 'installed-all' | 'installed-active' | 'agent' | 'agent-topic';
+ path: string;
+ readOnly: boolean;
+ size?: number;
+ type: 'directory' | 'file';
+}
+
+export interface ResolvedSkillMountPath {
+ filePath?: string;
+ namespace: SkillMountNode['namespace'];
+ relativePath: string;
+ skillName?: string;
+}
diff --git a/src/server/services/agentDocumentVfs/types.ts b/src/server/services/agentDocumentVfs/types.ts
new file mode 100644
index 00000000000..b4caa96cc38
--- /dev/null
+++ b/src/server/services/agentDocumentVfs/types.ts
@@ -0,0 +1,174 @@
+import type { AgentAccess } from '@/database/models/agentDocuments';
+
+/**
+ * Mounted subtree provenance for a VFS node.
+ *
+ * Use when:
+ * - The caller needs to know whether a node comes from ordinary agent documents or a mounted tree
+ * - CLI or tooling wants to surface the mounted namespace for debugging
+ *
+ * Expects:
+ * - `driver` identifies the mounted implementation
+ * - `namespace` and `source` are driver-local strings
+ */
+export interface AgentDocumentMountInfo {
+ /**
+ * Stable mounted driver name such as `agent-documents` or `skills`.
+ */
+ driver: string;
+ /**
+ * Driver-local namespace such as `agent` or `builtin`.
+ */
+ namespace?: string;
+ /**
+ * Driver-local source identifier such as `documents`, `builtin`, or `installed`.
+ */
+ source?: string;
+}
+
+/**
+ * Lightweight VFS node returned from directory listings.
+ *
+ * Use when:
+ * - Rendering `ls` or `tree`
+ * - Paging through a directory without loading document content
+ *
+ * Expects:
+ * - `type` determines whether the entry is a file or directory
+ * - `mode` reuses current self-channel `AgentAccess` bits
+ *
+ * Returns:
+ * - A plain-data node safe to serialize through TRPC/CLI boundaries
+ */
+export interface AgentDocumentNode {
+ agentDocumentId?: string;
+ createdAt?: Date;
+ documentId?: string;
+ id: string;
+ mode: AgentAccess;
+ mount?: AgentDocumentMountInfo;
+ name: string;
+ path: string;
+ size?: number;
+ type: 'directory' | 'file';
+ updatedAt?: Date;
+}
+
+/**
+ * Detailed VFS state for a single node.
+ *
+ * Use when:
+ * - Rendering `stat`
+ * - Inspecting a VFS node without reading its file body
+ *
+ * Expects:
+ * - Stable callers use `readDocumentByPath` / `AgentDocumentReadResult` for file bodies
+ *
+ * Returns:
+ * - A richer node carrying metadata without file content
+ */
+export interface AgentDocumentStats extends AgentDocumentNode {
+ contentType?: string;
+ deletedAt?: Date | null;
+ deleteReason?: string | null;
+ metadata?: Record<string, unknown>;
+}
+
+/**
+ * Flat trash entry returned from VFS trash listings.
+ *
+ * Use when:
+ * - Rendering `agent space fs trash ls`
+ * - Restoring or permanently deleting a soft-deleted entry
+ *
+ * Expects:
+ * - `deletedAt` is always populated for trash entries
+ */
+export interface AgentDocumentTrashEntry extends AgentDocumentStats {
+ deletedAt: Date;
+}
+
+/**
+ * Read result for file content operations.
+ *
+ * Use when:
+ * - A caller wants file content without the rest of the `stat` payload
+ *
+ * Returns:
+ * - File content plus the resolved VFS path
+ */
+export interface AgentDocumentReadResult {
+ content: string;
+ contentType?: string;
+ path: string;
+}
+
+/**
+ * Listing detail level for directory traversal.
+ *
+ * Use when:
+ * - The caller wants the default listing payload or a richer debug-oriented payload
+ */
+export type AgentDocumentListDetail = 'basic' | 'full';
+
+/**
+ * Options accepted by VFS directory listings.
+ *
+ * Use when:
+ * - Paginating a directory
+ * - Asking for richer list payloads
+ *
+ * Expects:
+ * - `detail` defaults to `basic`
+ * - `cursor` and `limit` are optional migration-friendly placeholders while the first pass returns arrays
+ */
+export interface AgentDocumentListOptions {
+ cursor?: string;
+ detail?: AgentDocumentListDetail;
+ limit?: number;
+}
+
+/**
+ * Paged VFS directory listing result.
+ *
+ * Use when:
+ * - A caller needs cursor-aware directory traversal
+ * - Future router APIs should expose pagination without changing node payloads
+ *
+ * Expects:
+ * - `items` contains direct children only
+ * - `nextCursor` is omitted when there are no more entries
+ *
+ * Returns:
+ * - Serializable listing data for ordinary documents and mounted subtrees
+ */
+export interface AgentDocumentListResult {
+ items: AgentDocumentNode[];
+ nextCursor?: string;
+}
+
+/**
+ * Type guard for file-like VFS nodes.
+ *
+ * Before:
+ * - `node.type === 'file'`
+ *
+ * After:
+ * - `isAgentDocumentFile(node) === true`
+ */
+export const isAgentDocumentFile = (
+ node: Pick<AgentDocumentNode, 'type'>,
+): node is Pick<AgentDocumentNode, 'type'> & { type: 'file' } => node.type === 'file';
+
+/**
+ * Type guard for directory-like VFS nodes.
+ *
+ * Before:
+ * - `node.type === 'directory'`
+ *
+ * After:
+ * - `isAgentDocumentDirectory(node) === true`
+ */
+export const isAgentDocumentDirectory = (
+ node: Pick<AgentDocumentNode, 'type'>,
+): node is Pick<AgentDocumentNode, 'type'> & { type: 'directory' } => node.type === 'directory';
diff --git a/src/server/services/agentDocuments.test.ts b/src/server/services/agentDocuments/index.test.ts
similarity index 87%
rename from src/server/services/agentDocuments.test.ts
rename to src/server/services/agentDocuments/index.test.ts
index b0655fd15d8..81f9e372e42 100644
--- a/src/server/services/agentDocuments.test.ts
+++ b/src/server/services/agentDocuments/index.test.ts
@@ -1,16 +1,19 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { AgentModel } from '@/database/models/agent';
import {
AgentDocumentModel,
buildDocumentFilename,
extractMarkdownH1Title,
} from '@/database/models/agentDocuments';
+import { AgentSkillModel } from '@/database/models/agentSkill';
import { TopicDocumentModel } from '@/database/models/topicDocument';
import type { LobeChatDatabase } from '@/database/type';
-import { AgentDocumentsService } from './agentDocuments';
-import { DocumentService } from './document';
+import { DocumentService } from '../document';
+import { SkillResourceService } from '../skill/resource';
+import { AgentDocumentsService } from './index';
const headlessEditorMocks = vi.hoisted(() => ({
applyLiteXML: vi.fn(),
@@ -26,14 +29,26 @@ vi.mock('@/database/models/agentDocuments', () => ({
extractMarkdownH1Title: vi.fn((content: string) => ({ content })),
}));
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/agentSkill', () => ({
+ AgentSkillModel: vi.fn(),
+}));
+
vi.mock('@/database/models/topicDocument', () => ({
TopicDocumentModel: vi.fn(),
}));
-vi.mock('./document', () => ({
+vi.mock('../document', () => ({
DocumentService: vi.fn(),
}));
+vi.mock('../skill/resource', () => ({
+ SkillResourceService: vi.fn(),
+}));
+
vi.mock('@lobehub/editor/headless', () => ({
createHeadlessEditor: vi.fn(() => {
let markdown = '';
@@ -72,6 +87,7 @@ describe('AgentDocumentsService', () => {
const mockModel = {
associate: vi.fn(),
+ copy: vi.fn(),
create: vi.fn(),
findById: vi.fn(),
findByAgent: vi.fn(),
@@ -83,17 +99,34 @@ describe('AgentDocumentsService', () => {
upsert: vi.fn(),
};
const mockDocumentService = {
+ createDocument: vi.fn(),
+ deleteDocument: vi.fn(),
trySaveCurrentDocumentHistory: vi.fn(),
+ updateDocument: vi.fn(),
+ };
+ const mockAgentModel = {
+ getAgentConfigById: vi.fn(),
+ };
+ const mockSkillModel = {
+ findAll: vi.fn(),
+ findById: vi.fn(),
+ findByName: vi.fn(),
};
const mockTopicDocumentModel = {
associate: vi.fn(),
findByTopicId: vi.fn(),
};
+ const mockSkillResourceService = {
+ readResource: vi.fn(),
+ };
beforeEach(() => {
vi.clearAllMocks();
(AgentDocumentModel as any).mockImplementation(() => mockModel);
+ (AgentModel as any).mockImplementation(() => mockAgentModel);
+ (AgentSkillModel as any).mockImplementation(() => mockSkillModel);
(DocumentService as any).mockImplementation(() => mockDocumentService);
+ (SkillResourceService as any).mockImplementation(() => mockSkillResourceService);
(TopicDocumentModel as any).mockImplementation(() => mockTopicDocumentModel);
vi.mocked(buildDocumentFilename).mockImplementation((title: string) => title);
vi.mocked(extractMarkdownH1Title).mockImplementation((content: string) => ({ content }));
@@ -530,6 +563,56 @@ describe('AgentDocumentsService', () => {
mockDocumentService.trySaveCurrentDocumentHistory.mock.invocationCallOrder[0],
).toBeLessThan(mockModel.rename.mock.invocationCallOrder[0]);
});
+
+ it('should reject renaming skill-managed documents', async () => {
+ mockModel.findById.mockResolvedValue({
+ agentId: 'agent-1',
+ content: 'content',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent',
+ role: 'skill-folder',
+ skillName: 'writer',
+ },
+ },
+ title: 'writer',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+
+ await expect(service.renameDocumentById('agent-doc-1', 'renamed', 'agent-1')).rejects.toThrow(
+ 'Skill VFS documents must be renamed through skill-specific APIs',
+ );
+ expect(mockModel.rename).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('copyDocumentById', () => {
+ it('should reject copying skill-managed documents', async () => {
+ mockModel.findById.mockResolvedValue({
+ agentId: 'agent-1',
+ content: 'content',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent',
+ role: 'skill-file',
+ skillName: 'writer',
+ },
+ },
+ title: 'SKILL.md',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+
+ await expect(service.copyDocumentById('agent-doc-1', 'copy', 'agent-1')).rejects.toThrow(
+ 'Skill VFS documents must be copied through skill-specific APIs',
+ );
+ expect(mockModel.copy).not.toHaveBeenCalled();
+ });
});
describe('hasDocuments', () => {
diff --git a/src/server/services/agentDocuments.ts b/src/server/services/agentDocuments/index.ts
similarity index 95%
rename from src/server/services/agentDocuments.ts
rename to src/server/services/agentDocuments/index.ts
index 4f07fb17a76..88a9c7b14fa 100644
--- a/src/server/services/agentDocuments.ts
+++ b/src/server/services/agentDocuments/index.ts
@@ -20,13 +20,15 @@ import {
} from '@/database/models/agentDocuments';
import { TopicDocumentModel } from '@/database/models/topicDocument';
+import { AgentDocumentVfsError } from '../agentDocumentVfs/errors';
+import { isManagedSkillDocument } from '../agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';
+import { DocumentService } from '../document';
import {
type AgentDocumentLiteXMLOperation,
applyLiteXMLOperations,
createMarkdownEditorSnapshot,
exportEditorDataSnapshot,
-} from './agentDocuments/headlessEditor';
-import { DocumentService } from './document';
+} from './headlessEditor';
const MAX_UNIQUE_FILENAME_ATTEMPTS = 1000;
@@ -78,7 +80,12 @@ export class AgentDocumentsService {
fallbackContent: doc.content,
});
- return { ...doc, content: snapshot.content };
+ const content =
+ snapshot.content.trim().length === 0 && doc.content.trim().length > 0
+ ? doc.content
+ : snapshot.content;
+
+ return { ...doc, content };
} catch (error) {
console.error('[AgentDocumentsService] Failed to project editorData to Markdown:', error);
return doc;
@@ -197,27 +204,6 @@ export class AgentDocumentsService {
await this.initializeFromTemplate(agentId, newTemplateId as keyof typeof DOCUMENT_TEMPLATES);
}
- /**
- * Backward-compatible alias.
- */
- async initializeFromPolicy(agentId: string, policyId: keyof typeof DOCUMENT_TEMPLATES = 'claw') {
- return this.initializeFromTemplate(agentId, policyId);
- }
-
- /**
- * Backward-compatible alias.
- */
- async initializeFromCustomPolicy(agentId: string, policy: DocumentTemplateSet) {
- return this.initializeFromCustomTemplate(agentId, policy);
- }
-
- /**
- * Backward-compatible alias.
- */
- async switchPolicy(agentId: string, newPolicyId: string, preserveCustomizations = false) {
- return this.switchTemplate(agentId, newPolicyId, preserveCustomizations);
- }
-
async getAgentDocuments(agentId: string): Promise<AgentDocumentWithRules[]> {
const docs = await this.agentDocumentModel.findByAgent(agentId);
return this.projectDocuments(docs);
@@ -535,6 +521,12 @@ export class AgentDocumentsService {
async renameDocumentById(documentId: string, newTitle: string, expectedAgentId?: string) {
const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);
if (!doc) return undefined;
+ if (isManagedSkillDocument(doc)) {
+ throw new AgentDocumentVfsError(
+ 'Skill VFS documents must be renamed through skill-specific APIs',
+ 'METHOD_NOT_SUPPORTED',
+ );
+ }
const title = newTitle.trim();
if (title && title !== doc.title) {
@@ -547,6 +539,12 @@ export class AgentDocumentsService {
async copyDocumentById(documentId: string, newTitle?: string, expectedAgentId?: string) {
const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);
if (!doc) return undefined;
+ if (isManagedSkillDocument(doc)) {
+ throw new AgentDocumentVfsError(
+ 'Skill VFS documents must be copied through skill-specific APIs',
+ 'METHOD_NOT_SUPPORTED',
+ );
+ }
return this.agentDocumentModel.copy(documentId, newTitle);
}