From 8c1e59d131bb3baf13fa79b52fa960f1b442ecaf Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Sun, 6 Sep 2026 17:15:58 +0800 Subject: [PATCH] feat(agent): add asset management tools and CLI commands (#387) * feat(agent): add asset management tools and CLI commands * fix(core): resolve code review findings for reparenting cycles, agent deniedTools update, and CLI folder delete --- apps/cli/README.md | 34 +++ apps/cli/src/commands/commands.test.ts | 196 ++++++++++++++++++ apps/cli/src/commands/delete.ts | 60 ++++++ apps/cli/src/commands/move.ts | 59 ++++++ apps/cli/src/commands/rename.ts | 55 +++++ apps/cli/src/index.ts | 45 +++- docs/using-shumai/agent-tools.mdx | 17 +- packages/agent/src/activities/agent.ts | 2 +- packages/agent/src/index.test.ts | 58 ++++++ packages/agent/src/index.ts | 13 +- packages/agent/src/tools/delete-asset.test.ts | 128 ++++++++++++ packages/agent/src/tools/delete-asset.ts | 74 +++++++ packages/agent/src/tools/move-assets.test.ts | 118 +++++++++++ packages/agent/src/tools/move-assets.ts | 84 ++++++++ packages/agent/src/tools/rename-asset.test.ts | 112 ++++++++++ packages/agent/src/tools/rename-asset.ts | 69 ++++++ packages/core/src/agent/agent.test.ts | 62 ++++++ packages/core/src/agent/agent.ts | 8 +- packages/core/src/asset/asset.test.ts | 33 +++ packages/core/src/asset/asset.ts | 14 ++ .../migration.sql | 15 ++ packages/dtos/src/agent.ts | 2 + .../settings/AgentFormDialog.test.tsx | 3 + .../components/settings/AgentFormDialog.tsx | 25 ++- .../components/settings/QuotaRuleDialog.tsx | 3 + packages/webui/messages/en.json | 6 + packages/webui/messages/zh.json | 6 + packages/webui/stores/chatbot.ts | 9 +- 28 files changed, 1300 insertions(+), 10 deletions(-) create mode 100644 apps/cli/src/commands/delete.ts create mode 100644 apps/cli/src/commands/move.ts create mode 100644 apps/cli/src/commands/rename.ts create mode 100644 packages/agent/src/tools/delete-asset.test.ts create mode 100644 packages/agent/src/tools/delete-asset.ts create mode 100644 packages/agent/src/tools/move-assets.test.ts create mode 100644 packages/agent/src/tools/move-assets.ts create mode 100644 packages/agent/src/tools/rename-asset.test.ts create mode 100644 packages/agent/src/tools/rename-asset.ts create mode 100644 packages/db/prisma/migrations/20260906081230_default_denied_tools_delete_asset/migration.sql diff --git a/apps/cli/README.md b/apps/cli/README.md index 92dfb742..30d00fec 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -89,6 +89,40 @@ shumai-cli create-version -p - **Options:** - `-p`, `--parent `: The parent asset ID (file or version stack) to version (required). +#### 6. Rename an Asset + +Rename an existing file or folder in Shumai. + +```bash +shumai-cli rename +``` + +#### 7. Move Assets + +Move one or more assets (files or folders) to a destination parent folder. Note that all assets to be moved must belong to the same current parent folder. + +```bash +shumai-cli move -p +# or using the short alias: +shumai-cli mv -p +``` + +- **Options:** + - `-p`, `--parent `: The destination parent folder ID (required). + +#### 8. Delete an Asset + +Delete a single file or folder by moving it to the Trash bin. For safety, this command only deletes one asset at a time and strictly requires the `--allow-delete` flag. + +```bash +shumai-cli delete --allow-delete +# or using the short alias: +shumai-cli rm --allow-delete +``` + +- **Options:** + - `--allow-delete`: Required authorization flag to confirm asset deletion. + --- ## Development diff --git a/apps/cli/src/commands/commands.test.ts b/apps/cli/src/commands/commands.test.ts index 5abf1776..ff571300 100644 --- a/apps/cli/src/commands/commands.test.ts +++ b/apps/cli/src/commands/commands.test.ts @@ -5,6 +5,9 @@ import { mkdir } from './mkdir' import { getClient } from '../client' import { upload } from './upload' import { createVersion } from './create-version' +import { rename } from './rename' +import { move } from './move' +import { deleteAsset } from './delete' import fs from 'node:fs' import http from 'node:http' @@ -34,17 +37,29 @@ describe('CLI Commands', () => { $get: vi.fn(), ':projectId': { $get: vi.fn(), + reparent: { + $post: vi.fn(), + }, }, }, folders: { $post: vi.fn(), + $delete: vi.fn(), ':folderId': { $get: vi.fn(), + $put: vi.fn(), children: { $get: vi.fn(), }, }, }, + files: { + $delete: vi.fn(), + ':fileId': { + $get: vi.fn(), + $put: vi.fn(), + }, + }, teams: { ':teamId': { upload: { @@ -361,4 +376,185 @@ describe('CLI Commands', () => { } }) }) + + describe('rename', () => { + it('exits with error when assetId or newName is missing', async () => { + await expect(rename('', 'new-name')).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Asset ID is required')) + + await expect(rename('asset-1', '')).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('New name is required')) + }) + + it('renames a folder when asset type is folder', async () => { + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ id: 'f-1', type: 'folder' }), + } as unknown as Response) + mockClient.api.folders[':folderId'].$put.mockResolvedValue({ + ok: true, + json: async () => ({ id: 'f-1', name: 'Renamed Folder' }), + } as unknown as Response) + + await rename('f-1', 'Renamed Folder') + + expect(mockClient.api.folders[':folderId'].$put).toHaveBeenCalledWith({ + param: { folderId: 'f-1' }, + json: { name: 'Renamed Folder' }, + }) + expect(logSpy).toHaveBeenCalledWith('Renamed asset f-1 to "Renamed Folder"') + }) + + it('renames a file when asset type is file', async () => { + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ id: 'file-1', type: 'file' }), + } as unknown as Response) + mockClient.api.files[':fileId'].$put.mockResolvedValue({ + ok: true, + json: async () => ({ id: 'file-1', name: 'new.mp4' }), + } as unknown as Response) + + await rename('file-1', 'new.mp4') + + expect(mockClient.api.files[':fileId'].$put).toHaveBeenCalledWith({ + param: { fileId: 'file-1' }, + json: { name: 'new.mp4' }, + }) + expect(logSpy).toHaveBeenCalledWith('Renamed asset file-1 to "new.mp4"') + }) + + it('exits with error when asset fetch fails', async () => { + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: false, + json: async () => ({ error: 'Asset not found' }), + } as unknown as Response) + + await expect(rename('unknown-id', 'name')).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith('Error: Asset not found') + }) + }) + + describe('move', () => { + it('exits with error when assetIds or parentId is missing', async () => { + await expect(move([], 'parent-1')).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith( + expect.stringContaining('At least one asset ID is required'), + ) + + await expect(move(['a-1'], '')).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith( + expect.stringContaining('Option -p/--parent is required'), + ) + }) + + it('successfully moves assets', async () => { + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ id: 'parent-1', projectId: 'proj-1' }), + } as unknown as Response) + mockClient.api.projects[':projectId'].reparent.$post.mockResolvedValue({ + ok: true, + } as unknown as Response) + + await move(['a-1', 'a-2'], 'parent-1') + + expect(mockClient.api.projects[':projectId'].reparent.$post).toHaveBeenCalledWith({ + param: { projectId: 'proj-1' }, + json: { + assetIds: ['a-1', 'a-2'], + newParentId: 'parent-1', + }, + }) + expect(logSpy).toHaveBeenCalledWith('Moved 2 asset(s) to parent parent-1') + }) + + it('exits with error when destination parent is not found', async () => { + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: false, + json: async () => ({ error: 'Folder not found' }), + } as unknown as Response) + + await expect(move(['a-1'], 'missing-parent')).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith('Error: Folder not found') + }) + }) + + describe('deleteAsset', () => { + it('exits with error when --allow-delete is false', async () => { + await expect(deleteAsset(['a-1'], false)).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith( + 'Error: Deleting an asset requires the --allow-delete flag.', + ) + }) + + it('exits with error when assetIds is empty', async () => { + await expect(deleteAsset([], true)).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Asset ID is required')) + }) + + it('exits with error when more than one asset ID is passed', async () => { + await expect(deleteAsset(['a-1', 'a-2'], true)).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith('Error: Can only delete one asset at a time.') + }) + + it('exits with error when asset is not found', async () => { + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: false, + json: async () => ({ error: 'Asset not found' }), + } as unknown as Response) + + await expect(deleteAsset(['a-1'], true)).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith('Error: Asset not found') + }) + + it('successfully deletes a file when --allow-delete is provided', async () => { + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ id: 'a-1', type: 'file' }), + } as unknown as Response) + mockClient.api.files.$delete.mockResolvedValue({ + ok: true, + } as unknown as Response) + + await deleteAsset(['a-1'], true) + + expect(mockClient.api.files.$delete).toHaveBeenCalledWith({ + json: { ids: ['a-1'] }, + }) + expect(mockClient.api.folders.$delete).not.toHaveBeenCalled() + expect(logSpy).toHaveBeenCalledWith('Deleted asset a-1') + }) + + it('successfully deletes a folder when --allow-delete is provided', async () => { + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ id: 'folder-1', type: 'folder' }), + } as unknown as Response) + mockClient.api.folders.$delete.mockResolvedValue({ + ok: true, + } as unknown as Response) + + await deleteAsset(['folder-1'], true) + + expect(mockClient.api.folders.$delete).toHaveBeenCalledWith({ + json: { ids: ['folder-1'] }, + }) + expect(logSpy).toHaveBeenCalledWith('Deleted asset folder-1') + }) + + it('exits with error when delete API returns an error', async () => { + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ id: 'a-1', type: 'file' }), + } as unknown as Response) + mockClient.api.files.$delete.mockResolvedValue({ + ok: false, + json: async () => ({ error: 'Failed to delete' }), + } as unknown as Response) + + await expect(deleteAsset(['a-1'], true)).rejects.toThrow('process.exit(1)') + expect(errorSpy).toHaveBeenCalledWith('Error: Failed to delete') + }) + }) }) diff --git a/apps/cli/src/commands/delete.ts b/apps/cli/src/commands/delete.ts new file mode 100644 index 00000000..72beb3cd --- /dev/null +++ b/apps/cli/src/commands/delete.ts @@ -0,0 +1,60 @@ +import { getClient } from '../client' + +export async function deleteAsset(assetIds: string[], allowDelete: boolean) { + if (!allowDelete) { + console.error('Error: Deleting an asset requires the --allow-delete flag.') + process.exit(1) + } + + if (!assetIds || assetIds.length === 0) { + console.error('Error: Asset ID is required. Usage: shumai-cli delete --allow-delete') + process.exit(1) + } + + if (assetIds.length > 1) { + console.error('Error: Can only delete one asset at a time.') + process.exit(1) + } + + const assetId = assetIds[0] + const client = getClient() + + try { + // Inspect asset to determine whether it is a folder or file + const getRes = await client.api.folders[':folderId'].$get({ + param: { folderId: assetId }, + }) + + if (!getRes.ok) { + const err = (await getRes.json().catch(() => ({ error: 'Asset not found' }))) as { + error?: string + } + console.error(`Error: ${err.error || 'Asset not found'}`) + process.exit(1) + } + + const asset = await getRes.json() + const isFolder = asset.type === 'folder' + + const res = isFolder + ? await client.api.folders.$delete({ + json: { ids: [assetId] }, + }) + : await client.api.files.$delete({ + json: { ids: [assetId] }, + }) + + if (!res.ok) { + const err = (await res.json().catch(() => ({ error: 'Failed to delete asset' }))) as { + error?: string + } + console.error(`Error: ${err.error || 'Failed to delete asset'}`) + process.exit(1) + } + + console.log(`Deleted asset ${assetId}`) + } catch (err) { + console.error('Error connecting to API server:', err instanceof Error ? err.message : err) + process.exit(1) + } +} diff --git a/apps/cli/src/commands/move.ts b/apps/cli/src/commands/move.ts new file mode 100644 index 00000000..90daa710 --- /dev/null +++ b/apps/cli/src/commands/move.ts @@ -0,0 +1,59 @@ +import { getClient } from '../client' + +export async function move(assetIds: string[], parentId: string) { + if (!assetIds || assetIds.length === 0) { + console.error( + 'Error: At least one asset ID is required. Usage: shumai-cli move -p ', + ) + process.exit(1) + } + if (!parentId) { + console.error('Error: Option -p/--parent is required.') + process.exit(1) + } + + const client = getClient() + + try { + // Fetch destination folder to get its projectId + const parentRes = await client.api.folders[':folderId'].$get({ + param: { folderId: parentId }, + }) + + if (!parentRes.ok) { + const err = (await parentRes.json().catch(() => ({ error: 'Parent folder not found' }))) as { + error?: string + } + console.error(`Error: ${err.error || 'Parent folder not found'}`) + process.exit(1) + } + + const parentInfo = await parentRes.json() + const projectId = parentInfo.projectId + if (!projectId) { + console.error('Error: Destination parent folder is not associated with a project.') + process.exit(1) + } + + const res = await client.api.projects[':projectId'].reparent.$post({ + param: { projectId }, + json: { + assetIds, + newParentId: parentId, + }, + }) + + if (!res.ok) { + const err = (await res.json().catch(() => ({ error: 'Failed to move assets' }))) as { + error?: string + } + console.error(`Error: ${err.error || 'Failed to move assets'}`) + process.exit(1) + } + + console.log(`Moved ${assetIds.length} asset(s) to parent ${parentId}`) + } catch (err) { + console.error('Error connecting to API server:', err instanceof Error ? err.message : err) + process.exit(1) + } +} diff --git a/apps/cli/src/commands/rename.ts b/apps/cli/src/commands/rename.ts new file mode 100644 index 00000000..d4e27bba --- /dev/null +++ b/apps/cli/src/commands/rename.ts @@ -0,0 +1,55 @@ +import { getClient } from '../client' + +export async function rename(assetId: string, newName: string) { + if (!assetId) { + console.error('Error: Asset ID is required. Usage: shumai-cli rename ') + process.exit(1) + } + if (!newName) { + console.error('Error: New name is required. Usage: shumai-cli rename ') + process.exit(1) + } + + const client = getClient() + + try { + // Determine whether asset is a folder or a file + const getRes = await client.api.folders[':folderId'].$get({ + param: { folderId: assetId }, + }) + + if (!getRes.ok) { + const err = (await getRes.json().catch(() => ({ error: 'Asset not found' }))) as { + error?: string + } + console.error(`Error: ${err.error || 'Asset not found'}`) + process.exit(1) + } + + const asset = await getRes.json() + const isFolder = asset.type === 'folder' + + const updateRes = isFolder + ? await client.api.folders[':folderId'].$put({ + param: { folderId: assetId }, + json: { name: newName }, + }) + : await client.api.files[':fileId'].$put({ + param: { fileId: assetId }, + json: { name: newName }, + }) + + if (!updateRes.ok) { + const err = (await updateRes.json().catch(() => ({ error: 'Failed to rename asset' }))) as { + error?: string + } + console.error(`Error: ${err.error || 'Failed to rename asset'}`) + process.exit(1) + } + + console.log(`Renamed asset ${assetId} to "${newName}"`) + } catch (err) { + console.error('Error connecting to API server:', err instanceof Error ? err.message : err) + process.exit(1) + } +} diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts index d503f784..a9d1a832 100644 --- a/apps/cli/src/index.ts +++ b/apps/cli/src/index.ts @@ -3,6 +3,9 @@ import { ls } from './commands/ls' import { mkdir } from './commands/mkdir' import { upload } from './commands/upload' import { createVersion } from './commands/create-version' +import { rename } from './commands/rename' +import { move } from './commands/move' +import { deleteAsset } from './commands/delete' function printHelp() { console.log(` @@ -14,9 +17,13 @@ Commands: mkdir -p Create a new folder in a parent folder upload -p Upload a local file or folder to a parent folder create-version -p Create a new version of an existing file or version stack + rename Rename an existing file or folder + move -p Move one or more assets to a destination parent folder (alias: mv) + delete --allow-delete Delete a single file or folder (alias: rm) Options: - -p, --parent The parent folder/asset ID (required for ls, mkdir, upload, create-version) + -p, --parent The parent folder/asset ID (required for ls, mkdir, upload, create-version, move) + --allow-delete Required flag to authorize deleting an asset -h, --help Show help details `) } @@ -36,10 +43,14 @@ async function main() { parentId = args[parentIdx + 1] } + const allowDelete = args.includes('--allow-delete') + const cleanArgs: string[] = [] for (let i = 0; i < args.length; i++) { if (args[i] === '-p' || args[i] === '--parent') { i++ + } else if (args[i] === '--allow-delete') { + // skip flag } else { cleanArgs.push(args[i]) } @@ -92,6 +103,38 @@ async function main() { process.exit(1) } await createVersion(localPath, parentId) + } else if (cmd === 'rename') { + const assetId = cleanArgs[1] + const newName = cleanArgs[2] + if (!assetId || !newName) { + console.error( + 'Error: Asset ID and new name are required. Usage: shumai-cli rename ', + ) + process.exit(1) + } + await rename(assetId, newName) + } else if (cmd === 'move' || cmd === 'mv') { + const assetIds = cleanArgs.slice(1) + if (assetIds.length === 0) { + console.error( + 'Error: At least one asset ID is required. Usage: shumai-cli move -p ', + ) + process.exit(1) + } + if (!parentId) { + console.error('Error: Option -p/--parent is required.') + process.exit(1) + } + await move(assetIds, parentId) + } else if (cmd === 'delete' || cmd === 'rm') { + const assetIds = cleanArgs.slice(1) + if (assetIds.length === 0) { + console.error( + 'Error: Asset ID is required. Usage: shumai-cli delete --allow-delete', + ) + process.exit(1) + } + await deleteAsset(assetIds, allowDelete) } else { console.error(`Error: Unknown command "${cmd}". Run "shumai-cli --help" for usage.`) process.exit(1) diff --git a/docs/using-shumai/agent-tools.mdx b/docs/using-shumai/agent-tools.mdx index c2e2e741..eb2a6f23 100644 --- a/docs/using-shumai/agent-tools.mdx +++ b/docs/using-shumai/agent-tools.mdx @@ -5,7 +5,7 @@ description: Configure the tools and capabilities permitted for each agent. Shumai agents are equipped with built-in tools that allow them to interact with the file system, view files, extract video frames, and execute commands. -By default, **all tools are enabled** for new agents. Team Owners can deny specific tools to restrict agent capabilities. +By default, most tools are enabled for new agents, while sensitive or destructive tools (such as **Delete Asset**) are disabled by default. Team Owners can toggle specific tools to customize agent capabilities. **Caution:** Disabling tools can cause agents or skills to fail. For example, disabling the @@ -60,6 +60,21 @@ The following tools can be individually toggled in the agent configuration dialo - **Description:** Allows the agent to download a workspace asset or specific storage S3 key to the local `.pi` directory for processing with local scripts or bash commands. - **Why it matters:** Enables agents executing custom skill scripts to fetch files or intermediate transcode artifacts to local disk. +### 9. Rename Asset (`rename_asset`) + +- **Description:** Allows the agent to rename an existing file or folder in Shumai. +- **Why it matters:** Enables agents to keep project files neatly named and organized according to workspace naming conventions. Enabled by default. + +### 10. Move Assets (`move_assets`) + +- **Description:** Allows the agent to move one or more assets to a destination parent folder. +- **Why it matters:** Enables agents to reorganize workspace structures, relocate generated outputs, or tidy up project folders. Enabled by default. + +### 11. Delete Asset (`delete_asset`) + +- **Description:** Allows the agent to delete a single file or folder by moving it to the Trash bin. +- **Why it matters:** Provides agents with the ability to clean up outdated or redundant assets. To prevent accidental data loss, this tool is **disabled by default** and strictly limited to deleting one asset at a time. Team Owners must explicitly enable this tool for an agent. + --- ## Restricting Tools diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 6d8a0eba..427d2dff 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -111,7 +111,7 @@ async function executeAgentPrompt(params: { let systemPrompt = `You are the AI assistant for shumai. shumai is a professional creative collaboration platform similar to frame.io, where users can upload creative files, manage projects, assign tasks, get precise feedback, and share their work. As the agent, your role is to help users use and manage this platform. -shumai has its own cloud file system. If a user asks you to perform file system operations (for example: creating a folder, creating a file, stacking a version, or listing assets), you MUST use the corresponding agent system tools (e.g., 'create_folder', 'create_file', 'create_version', 'list_assets'). Before calling 'create_folder', first check if the folder exists using 'list_assets'. Do NOT use local bash commands or the local bash tool to perform these operations locally on the host environment; all operations must be executed through the platform's cloud file system tools so they are correctly registered and visible within the platform. +shumai has its own cloud file system. If a user asks you to perform file system operations (for example: creating a folder, creating a file, stacking a version, listing assets, renaming an asset, moving assets, or deleting an asset), you MUST use the corresponding agent system tools (e.g., 'create_folder', 'create_file', 'create_version', 'list_assets', 'rename_asset', 'move_assets', 'delete_asset'). Before calling 'create_folder', first check if the folder exists using 'list_assets'. Do NOT use local bash commands or the local bash tool to perform these operations locally on the host environment; all operations must be executed through the platform's cloud file system tools so they are correctly registered and visible within the platform. If you need to create files in the local filesystem (for example, a temporary file for uploading), only the '.pi' folder in the current directory has write permissions. Do NOT attempt to create files in any other directories. diff --git a/packages/agent/src/index.test.ts b/packages/agent/src/index.test.ts index df8ab323..960a48bc 100644 --- a/packages/agent/src/index.test.ts +++ b/packages/agent/src/index.test.ts @@ -1029,6 +1029,64 @@ describe('createAgentSession typed metadata schema', () => { expect('metadata' in fileProps).toBe(false) expect('metadata' in versionProps).toBe(false) }) + + it('should include rename_asset and move_assets by default, but exclude delete_asset', async () => { + const { harness } = await setupSessionWithProject({ withCreationFields: false }) + const toolNames = harness.getTools().map((t) => t.name) + + expect(toolNames).toContain('rename_asset') + expect(toolNames).toContain('move_assets') + expect(toolNames).not.toContain('delete_asset') + }) + + it('should include delete_asset when deniedTools is explicitly empty', async () => { + const team = await prisma.team.create({ data: { name: 'Delete Asset Team' } }) + const user = await prisma.user.create({ + data: { name: 'Owner', email: 'owner-del@shumai.ai' }, + }) + await prisma.teamMember.create({ + data: { teamId: team.id, userId: user.id, role: 'owner' }, + }) + await prisma.user.create({ + data: { + id: 'del-agent', + name: 'Del Agent', + email: 'del-agent@shumai.ai', + type: 'agent', + }, + }) + await prisma.agent.create({ + data: { + id: 'del-agent', + teamId: team.id, + type: 'chat', + config: { + provider: 'google', + model: 'gemini', + deniedTools: [], + }, + }, + }) + + const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue() + try { + const { harness } = await createAgentSession({ + teamId: team.id, + agentId: 'del-agent', + providerName: 'google', + modelId: 'gemini', + systemPrompt: 'prompt', + teamSkills: [], + allowedDomains: [], + providers: mockProviders, + userId: user.id, + }) + const toolNames = harness.getTools().map((t) => t.name) + expect(toolNames).toContain('delete_asset') + } finally { + initializeSpy.mockRestore() + } + }) }) describe('createAgentSession enabled skill filtering', () => { diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index c9b60886..03b2af04 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -30,9 +30,12 @@ import { createReadThreadTool } from './tools/read-thread' import { createSandboxedBashTool } from './tools/sandboxed-bash' import { createGenerateImageTool } from './tools/generate-image' import { createGenerateVideoTool } from './tools/generate-video' +import { createRenameAssetTool } from './tools/rename-asset' +import { createMoveAssetsTool } from './tools/move-assets' +import { createDeleteAssetTool } from './tools/delete-asset' import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation' import { serializeContextToXml } from './context/serialize-context' -import type { ShumaiMessageContext } from '@shumai/dtos' +import { DEFAULT_DENIED_TOOLS, type ShumaiMessageContext } from '@shumai/dtos' export interface DbModelInfo { modelId: string @@ -322,7 +325,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) { where: { id: agentId }, }) const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined - const deniedTools = agentConfig?.deniedTools || [] + const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS] if (!deniedTools.includes('generate_image') || !deniedTools.includes('generate_video')) { try { @@ -387,6 +390,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) { createCreateFileTool(userId, metadataSchema, agentContext), createCreateVersionTool(userId, metadataSchema, agentContext), createDownloadAssetTool(userId), + createRenameAssetTool(userId, agentContext), + createMoveAssetsTool(userId, agentContext), + createDeleteAssetTool(userId, agentContext), ) } @@ -680,3 +686,6 @@ export * from './workflows/agent-embedding' export * from './workflows/query-embedding-for-search' export * from './tools/generate-image' export * from './tools/generate-video' +export * from './tools/rename-asset' +export * from './tools/move-assets' +export * from './tools/delete-asset' diff --git a/packages/agent/src/tools/delete-asset.test.ts b/packages/agent/src/tools/delete-asset.test.ts new file mode 100644 index 00000000..2452451b --- /dev/null +++ b/packages/agent/src/tools/delete-asset.test.ts @@ -0,0 +1,128 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createDeleteAssetTool } from './delete-asset' +import { assetService } from '@shumai/core/src/asset/asset' +import { auditLogService } from '@shumai/core/src/auditLog/auditLog' +import { authzService } from '@shumai/core/src/authz/authz' +import { prisma } from '@shumai/db' +import { AuditAction } from '@shumai/dtos' + +vi.mock('@shumai/core/src/authz/authz', () => ({ + authzService: { + hasPermission: vi.fn().mockResolvedValue(undefined), + }, + Permission: { Edit: 'edit', Read: 'read' }, + ResourceType: { Asset: 'asset' }, +})) + +vi.mock('@shumai/core/src/asset/asset', () => ({ + assetService: { + deleteAssets: vi.fn().mockResolvedValue(undefined), + getAssetContext: vi.fn().mockResolvedValue({ + teamId: 'team-1', + projectId: 'proj-1', + }), + }, +})) + +vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ + auditLogService: { + logAction: vi.fn().mockResolvedValue(undefined), + }, +})) + +vi.mock('@shumai/db', () => ({ + prisma: { + asset: { + findUnique: vi.fn(), + }, + }, +})) + +describe('createDeleteAssetTool', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('checks edit permission, deletes asset, and returns success for a file', async () => { + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-1', + type: 'file', + projectId: 'proj-1', + } as unknown as never) + + const tool = createDeleteAssetTool('user-1') + const result = await tool.execute('call-1', { assetId: 'asset-1' }) + + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user-1' }, + permission: 'edit', + type: 'asset', + id: 'asset-1', + }) + + expect(assetService.deleteAssets).toHaveBeenCalledWith(['asset-1']) + expect(result.details).toEqual({}) + expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({ + success: true, + deletedAssetId: 'asset-1', + }) + }) + + it('logs file_delete audit action when deleting a file with agentContext', async () => { + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-1', + type: 'file', + projectId: 'proj-1', + } as unknown as never) + + const tool = createDeleteAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' }) + await tool.execute('call-1', { assetId: 'asset-1' }) + + expect(auditLogService.logAction).toHaveBeenCalledWith({ + action: AuditAction.file_delete, + teamId: 'team-1', + userId: 'user-1', + agentId: 'agent-1', + projectId: 'proj-1', + itemId: 'asset-1', + }) + }) + + it('logs folder_delete audit action when deleting a folder with agentContext', async () => { + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'folder-1', + type: 'folder', + projectId: 'proj-1', + } as unknown as never) + + const tool = createDeleteAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' }) + await tool.execute('call-1', { assetId: 'folder-1' }) + + expect(auditLogService.logAction).toHaveBeenCalledWith({ + action: AuditAction.folder_delete, + teamId: 'team-1', + userId: 'user-1', + agentId: 'agent-1', + projectId: 'proj-1', + itemId: 'folder-1', + }) + }) + + it('throws when asset is not found', async () => { + vi.mocked(prisma.asset.findUnique).mockResolvedValue(null) + + const tool = createDeleteAssetTool('user-1') + await expect(tool.execute('call-1', { assetId: 'missing-asset' })).rejects.toThrow( + 'Asset not found', + ) + }) + + it('fails when permission check fails', async () => { + vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Permission denied')) + const tool = createDeleteAssetTool('user-1') + + await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow( + 'Permission denied', + ) + }) +}) diff --git a/packages/agent/src/tools/delete-asset.ts b/packages/agent/src/tools/delete-asset.ts new file mode 100644 index 00000000..091e8311 --- /dev/null +++ b/packages/agent/src/tools/delete-asset.ts @@ -0,0 +1,74 @@ +import { Type } from 'typebox' +import { type AgentTool } from '@earendil-works/pi-agent-core' +import { assetService } from '@shumai/core/src/asset/asset' +import { auditLogService } from '@shumai/core/src/auditLog/auditLog' +import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' +import { prisma, type User } from '@shumai/db' +import { AuditAction } from '@shumai/dtos' + +const deleteAssetSchema = Type.Object( + { + assetId: Type.String({ + description: + 'The ID of the single asset (file or folder) to delete. This parameter is required.', + }), + }, + { additionalProperties: false }, +) + +export function createDeleteAssetTool( + userId: string, + agentContext?: { teamId?: string; agentId?: string }, +): AgentTool { + return { + name: 'delete_asset', + label: 'Delete Asset', + description: + 'Delete a single asset (file or folder) by its ID. Can only delete one asset at a time.', + parameters: deleteAssetSchema, + execute: async (_toolCallId, params) => { + await authzService.hasPermission({ + user: { id: userId } as User, + permission: Permission.Edit, + type: ResourceType.Asset, + id: params.assetId, + }) + + const asset = await prisma.asset.findUnique({ + where: { id: params.assetId }, + select: { id: true, type: true, projectId: true }, + }) + if (!asset) { + throw new Error('Asset not found') + } + + const ctx = await assetService.getAssetContext(params.assetId).catch(() => ({ + teamId: agentContext?.teamId || '', + projectId: asset.projectId ?? undefined, + })) + + await assetService.deleteAssets([params.assetId]) + + if (agentContext?.teamId) { + await auditLogService.logAction({ + action: asset.type === 'folder' ? AuditAction.folder_delete : AuditAction.file_delete, + teamId: agentContext.teamId || ctx.teamId, + userId, + agentId: agentContext.agentId, + projectId: ctx.projectId ?? asset.projectId ?? undefined, + itemId: params.assetId, + }) + } + + const result = { + success: true, + deletedAssetId: params.assetId, + } + + return { + content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], + details: {}, + } + }, + } +} diff --git a/packages/agent/src/tools/move-assets.test.ts b/packages/agent/src/tools/move-assets.test.ts new file mode 100644 index 00000000..7dc23b34 --- /dev/null +++ b/packages/agent/src/tools/move-assets.test.ts @@ -0,0 +1,118 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createMoveAssetsTool } from './move-assets' +import { assetService } from '@shumai/core/src/asset/asset' +import { auditLogService } from '@shumai/core/src/auditLog/auditLog' +import { authzService } from '@shumai/core/src/authz/authz' +import { AuditAction } from '@shumai/dtos' + +vi.mock('@shumai/core/src/authz/authz', () => ({ + authzService: { + hasPermission: vi.fn().mockResolvedValue(undefined), + }, + Permission: { Edit: 'edit', Read: 'read' }, + ResourceType: { Asset: 'asset' }, +})) + +vi.mock('@shumai/core/src/asset/asset', () => ({ + assetService: { + reparentAssets: vi.fn().mockResolvedValue(undefined), + getAssetContext: vi.fn().mockResolvedValue({ + teamId: 'team-1', + projectId: 'proj-1', + }), + }, +})) + +vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ + auditLogService: { + logAction: vi.fn().mockResolvedValue(undefined), + }, +})) + +describe('createMoveAssetsTool', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('checks permissions on destination and all assets, and calls reparentAssets', async () => { + const tool = createMoveAssetsTool('user-1') + const result = await tool.execute('call-1', { + assetIds: ['asset-1', 'asset-2'], + newParentId: 'folder-dest', + }) + + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user-1' }, + permission: 'edit', + type: 'asset', + id: 'folder-dest', + }) + + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user-1' }, + permission: 'edit', + type: 'asset', + id: 'asset-1', + }) + + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user-1' }, + permission: 'edit', + type: 'asset', + id: 'asset-2', + }) + + expect(assetService.reparentAssets).toHaveBeenCalledWith({ + assetIds: ['asset-1', 'asset-2'], + newParentId: 'folder-dest', + creatorId: 'user-1', + }) + + expect(result.details).toEqual({}) + expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({ + success: true, + movedAssetIds: ['asset-1', 'asset-2'], + newParentId: 'folder-dest', + }) + }) + + it('logs asset_reparent for each asset when agentContext is provided', async () => { + const tool = createMoveAssetsTool('user-1', { teamId: 'team-1', agentId: 'agent-1' }) + await tool.execute('call-1', { + assetIds: ['asset-1', 'asset-2'], + newParentId: 'folder-dest', + }) + + expect(auditLogService.logAction).toHaveBeenCalledTimes(2) + expect(auditLogService.logAction).toHaveBeenCalledWith({ + action: AuditAction.asset_reparent, + teamId: 'team-1', + userId: 'user-1', + agentId: 'agent-1', + projectId: 'proj-1', + itemId: 'asset-1', + }) + expect(auditLogService.logAction).toHaveBeenCalledWith({ + action: AuditAction.asset_reparent, + teamId: 'team-1', + userId: 'user-1', + agentId: 'agent-1', + projectId: 'proj-1', + itemId: 'asset-2', + }) + }) + + it('fails when permission check on target folder fails', async () => { + vi.mocked(authzService.hasPermission).mockRejectedValueOnce( + new Error('Access denied to destination'), + ) + const tool = createMoveAssetsTool('user-1') + + await expect( + tool.execute('call-1', { + assetIds: ['asset-1'], + newParentId: 'folder-dest', + }), + ).rejects.toThrow('Access denied to destination') + }) +}) diff --git a/packages/agent/src/tools/move-assets.ts b/packages/agent/src/tools/move-assets.ts new file mode 100644 index 00000000..ad514c64 --- /dev/null +++ b/packages/agent/src/tools/move-assets.ts @@ -0,0 +1,84 @@ +import { Type } from 'typebox' +import { type AgentTool } from '@earendil-works/pi-agent-core' +import { assetService } from '@shumai/core/src/asset/asset' +import { auditLogService } from '@shumai/core/src/auditLog/auditLog' +import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' +import { type User } from '@shumai/db' +import { AuditAction } from '@shumai/dtos' + +const moveAssetsSchema = Type.Object({ + assetIds: Type.Array(Type.String(), { + description: + 'The IDs of the assets to move. All assets must belong to the same parent folder. At least one asset ID is required.', + minItems: 1, + }), + newParentId: Type.String({ + description: + 'The destination parent folder ID to move the assets into. This parameter is required.', + }), +}) + +export function createMoveAssetsTool( + userId: string, + agentContext?: { teamId?: string; agentId?: string }, +): AgentTool { + return { + name: 'move_assets', + label: 'Move Assets', + description: + 'Move one or more assets (files or folders) to a specified parent folder. Note: All assets to be moved must belong to the same current parent folder.', + parameters: moveAssetsSchema, + execute: async (_toolCallId, params) => { + // Check Edit permission on destination folder + await authzService.hasPermission({ + user: { id: userId } as User, + permission: Permission.Edit, + type: ResourceType.Asset, + id: params.newParentId, + }) + + // Check Edit permission on all source assets + for (const assetId of params.assetIds) { + await authzService.hasPermission({ + user: { id: userId } as User, + permission: Permission.Edit, + type: ResourceType.Asset, + id: assetId, + }) + } + + await assetService.reparentAssets({ + assetIds: params.assetIds, + newParentId: params.newParentId, + creatorId: userId, + }) + + if (agentContext?.teamId) { + const ctx = await assetService + .getAssetContext(params.newParentId) + .catch(() => ({ teamId: agentContext.teamId!, projectId: undefined })) + for (const assetId of params.assetIds) { + await auditLogService.logAction({ + action: AuditAction.asset_reparent, + teamId: agentContext.teamId || ctx.teamId, + userId, + agentId: agentContext.agentId, + projectId: ctx.projectId, + itemId: assetId, + }) + } + } + + const result = { + success: true, + movedAssetIds: params.assetIds, + newParentId: params.newParentId, + } + + return { + content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], + details: {}, + } + }, + } +} diff --git a/packages/agent/src/tools/rename-asset.test.ts b/packages/agent/src/tools/rename-asset.test.ts new file mode 100644 index 00000000..939b8351 --- /dev/null +++ b/packages/agent/src/tools/rename-asset.test.ts @@ -0,0 +1,112 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createRenameAssetTool } from './rename-asset' +import { assetService } from '@shumai/core/src/asset/asset' +import { auditLogService } from '@shumai/core/src/auditLog/auditLog' +import { authzService } from '@shumai/core/src/authz/authz' +import { AuditAction, type AssetInfo } from '@shumai/dtos' + +vi.mock('@shumai/core/src/authz/authz', () => ({ + authzService: { + hasPermission: vi.fn().mockResolvedValue(undefined), + }, + Permission: { Edit: 'edit', Read: 'read' }, + ResourceType: { Asset: 'asset' }, +})) + +vi.mock('@shumai/core/src/asset/asset', () => ({ + assetService: { + updateAssetName: vi.fn().mockResolvedValue({ + id: 'asset-1', + name: 'Renamed Asset', + type: 'file', + sizeByte: 1024, + projectId: 'proj-1', + }), + getAssetContext: vi.fn().mockResolvedValue({ + teamId: 'team-1', + projectId: 'proj-1', + }), + }, +})) + +vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ + auditLogService: { + logAction: vi.fn().mockResolvedValue(undefined), + }, +})) + +describe('createRenameAssetTool', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('checks edit permission and calls assetService.updateAssetName', async () => { + const tool = createRenameAssetTool('user-1') + const result = await tool.execute('call-1', { assetId: 'asset-1', name: 'Renamed Asset' }) + + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user-1' }, + permission: 'edit', + type: 'asset', + id: 'asset-1', + }) + + expect(assetService.updateAssetName).toHaveBeenCalledWith({ + id: 'asset-1', + name: 'Renamed Asset', + }) + + expect(result.details).toEqual({}) + expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({ + id: 'asset-1', + name: 'Renamed Asset', + type: 'file', + size: 1024, + }) + }) + + it('logs file_update audit action when renaming a file with agentContext', async () => { + const tool = createRenameAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' }) + await tool.execute('call-1', { assetId: 'asset-1', name: 'Renamed File' }) + + expect(auditLogService.logAction).toHaveBeenCalledWith({ + action: AuditAction.file_update, + teamId: 'team-1', + userId: 'user-1', + agentId: 'agent-1', + projectId: 'proj-1', + itemId: 'asset-1', + }) + }) + + it('logs folder_update audit action when renaming a folder with agentContext', async () => { + vi.mocked(assetService.updateAssetName).mockResolvedValueOnce({ + id: 'folder-1', + name: 'Renamed Folder', + type: 'folder', + sizeByte: 0, + projectId: 'proj-1', + } as unknown as AssetInfo) + + const tool = createRenameAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' }) + await tool.execute('call-1', { assetId: 'folder-1', name: 'Renamed Folder' }) + + expect(auditLogService.logAction).toHaveBeenCalledWith({ + action: AuditAction.folder_update, + teamId: 'team-1', + userId: 'user-1', + agentId: 'agent-1', + projectId: 'proj-1', + itemId: 'folder-1', + }) + }) + + it('fails when permission check rejects', async () => { + vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Permission denied')) + const tool = createRenameAssetTool('user-1') + + await expect(tool.execute('call-1', { assetId: 'asset-1', name: 'New' })).rejects.toThrow( + 'Permission denied', + ) + }) +}) diff --git a/packages/agent/src/tools/rename-asset.ts b/packages/agent/src/tools/rename-asset.ts new file mode 100644 index 00000000..1d364bf6 --- /dev/null +++ b/packages/agent/src/tools/rename-asset.ts @@ -0,0 +1,69 @@ +import { Type } from 'typebox' +import { type AgentTool } from '@earendil-works/pi-agent-core' +import { assetService } from '@shumai/core/src/asset/asset' +import { auditLogService } from '@shumai/core/src/auditLog/auditLog' +import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' +import { type User } from '@shumai/db' +import { AuditAction } from '@shumai/dtos' + +const renameAssetSchema = Type.Object({ + assetId: Type.String({ + description: 'The ID of the asset (file or folder) to rename. This parameter is required.', + }), + name: Type.String({ + description: 'The new name for the asset. This parameter is required.', + }), +}) + +export function createRenameAssetTool( + userId: string, + agentContext?: { teamId?: string; agentId?: string }, +): AgentTool { + return { + name: 'rename_asset', + label: 'Rename Asset', + description: 'Rename an existing asset (file or folder).', + parameters: renameAssetSchema, + execute: async (_toolCallId, params) => { + await authzService.hasPermission({ + user: { id: userId } as User, + permission: Permission.Edit, + type: ResourceType.Asset, + id: params.assetId, + }) + + const updatedAsset = await assetService.updateAssetName({ + id: params.assetId, + name: params.name, + }) + + if (agentContext?.teamId) { + const ctx = await assetService.getAssetContext(params.assetId).catch(() => ({ + teamId: agentContext.teamId!, + projectId: updatedAsset.projectId ?? undefined, + })) + await auditLogService.logAction({ + action: + updatedAsset.type === 'folder' ? AuditAction.folder_update : AuditAction.file_update, + teamId: agentContext.teamId || ctx.teamId, + userId, + agentId: agentContext.agentId, + projectId: ctx.projectId ?? updatedAsset.projectId ?? undefined, + itemId: params.assetId, + }) + } + + const result = { + id: updatedAsset.id, + name: updatedAsset.name, + type: updatedAsset.type, + size: Number(updatedAsset.sizeByte), + } + + return { + content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], + details: {}, + } + }, + } +} diff --git a/packages/core/src/agent/agent.test.ts b/packages/core/src/agent/agent.test.ts index cf26bdf7..e566b9f2 100644 --- a/packages/core/src/agent/agent.test.ts +++ b/packages/core/src/agent/agent.test.ts @@ -257,6 +257,68 @@ describe('AgentService', () => { expect(updated.user.image).toBe('files/01JK23456789ABCDEF01234567') }) + test('Update Agent preserves deniedTools when omitted, and allows explicit empty array', async () => { + const db = prisma + const svc = new AgentService() + const { team, provider, model, agent: legacyAgent } = await setupTestData(db) + + // Legacy agent has no deniedTools in config, update without deniedTools should fall back to DEFAULT_DENIED_TOOLS + const updatedLegacy = await svc.updateAgent({ + agentId: legacyAgent.id, + name: 'Updated Legacy', + type: 'chat', + enabled: true, + providerId: legacyAgent.providerId!, + modelId: legacyAgent.modelId!, + thinkingLevel: 'medium', + }) + expect((updatedLegacy.config as PrismaJson.AgentConfig).deniedTools).toEqual(['delete_asset']) + + // Create new agent with default deniedTools + const agent = await svc.createAgent({ + teamId: team.id, + name: 'New Agent with Defaults', + type: 'chat', + enabled: true, + providerId: provider.id, + modelId: model.id, + thinkingLevel: 'medium', + }) + + expect(agent).not.toBeNull() + + // Agent created with default deniedTools: ['delete_asset'] + const createdConfig = agent!.config as PrismaJson.AgentConfig + expect(createdConfig.deniedTools).toEqual(['delete_asset']) + + // Update without deniedTools: should preserve ['delete_asset'] + const updatedWithoutDenied = await svc.updateAgent({ + agentId: agent!.id, + name: 'Updated Name', + type: 'chat', + enabled: true, + providerId: agent!.providerId!, + modelId: agent!.modelId!, + thinkingLevel: 'medium', + }) + const config1 = updatedWithoutDenied.config as PrismaJson.AgentConfig + expect(config1.deniedTools).toEqual(['delete_asset']) + + // Update with explicit deniedTools: [] + const updatedWithEmptyDenied = await svc.updateAgent({ + agentId: agent!.id, + name: 'Updated Name 2', + type: 'chat', + enabled: true, + providerId: agent!.providerId!, + modelId: agent!.modelId!, + thinkingLevel: 'medium', + deniedTools: [], + }) + const config2 = updatedWithEmptyDenied.config as PrismaJson.AgentConfig + expect(config2.deniedTools).toEqual([]) + }) + test('Create and Update Agent with Preset Avatars', async () => { const db = prisma const svc = new AgentService() diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index 2494aea6..0a0068c0 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -7,6 +7,7 @@ import { AgentSessionInfo, AgentInfo, AgentType, + DEFAULT_DENIED_TOOLS, } from '@shumai/dtos' import { paginateQuery, @@ -208,7 +209,7 @@ export class AgentService { model: modelId || '', thinkingLevel, systemPrompt, - deniedTools: deniedTools || [], + deniedTools: deniedTools ?? [...DEFAULT_DENIED_TOOLS], avatarPreset, } @@ -351,7 +352,10 @@ export class AgentService { model: modelId || '', thinkingLevel, systemPrompt, - deniedTools: deniedTools || [], + deniedTools: + deniedTools !== undefined + ? deniedTools + : (currentConfig.deniedTools ?? [...DEFAULT_DENIED_TOOLS]), avatarPreset: newAvatarPreset, } diff --git a/packages/core/src/asset/asset.test.ts b/packages/core/src/asset/asset.test.ts index 114f5b77..c4bae647 100644 --- a/packages/core/src/asset/asset.test.ts +++ b/packages/core/src/asset/asset.test.ts @@ -626,6 +626,39 @@ describe('AssetService', () => { ).rejects.toThrow('Can only move one file at a time into a version stack') }) + it('rejects reparenting a folder into itself', async () => { + const { user, assets } = await setupBasicAssets() + await expect( + assetService.reparentAssets({ + assetIds: [assets.folderA.id], + newParentId: assets.folderA.id, + creatorId: user.id, + }), + ).rejects.toThrow('Cannot move an asset into itself or its own descendant') + }) + + it('rejects reparenting a folder into its own descendant', async () => { + const { user, assets, project } = await setupBasicAssets() + const subfolder = await prisma.asset.create({ + data: { + name: 'subfolderA', + type: AssetType.folder, + projectId: project.id, + parentId: assets.folderA.id, + creatorId: user.id, + status: 'uploaded', + }, + }) + + await expect( + assetService.reparentAssets({ + assetIds: [assets.folderA.id], + newParentId: subfolder.id, + creatorId: user.id, + }), + ).rejects.toThrow('Cannot move an asset into itself or its own descendant') + }) + describe('fileCount verification', () => { it('createAsset should increment parent fileCount', async () => { const { user, assets, project } = await setupBasicAssets() diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index dabdb033..7720e7a0 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -223,6 +223,20 @@ export class AssetService { if (assetsToMove.length === 0) return + // Check if newParentId is equal to or a descendant of any asset being moved + const ancestors = await tx.$queryRaw<{ id: string }[]>` + WITH RECURSIVE ancestor AS ( + SELECT id, parent_id FROM assets WHERE id = ${newParent.id} + UNION ALL + SELECT a.id, a.parent_id FROM assets a + INNER JOIN ancestor d ON a.id = d.parent_id + ) + SELECT id FROM ancestor WHERE id IN (${Prisma.join(req.assetIds)}) LIMIT 1; + ` + if (ancestors.length > 0) { + throw new Error('Cannot move an asset into itself or its own descendant') + } + if (newParent.type === AssetType.version_stack) { for (const a of assetsToMove) { if (a.type !== AssetType.file) { diff --git a/packages/db/prisma/migrations/20260906081230_default_denied_tools_delete_asset/migration.sql b/packages/db/prisma/migrations/20260906081230_default_denied_tools_delete_asset/migration.sql new file mode 100644 index 00000000..a2236d30 --- /dev/null +++ b/packages/db/prisma/migrations/20260906081230_default_denied_tools_delete_asset/migration.sql @@ -0,0 +1,15 @@ +-- Append 'delete_asset' to deniedTools of existing agents if not already present +UPDATE "agents" +SET "config" = jsonb_set( + "config"::jsonb, + '{deniedTools}', + CASE + WHEN "config"::jsonb ? 'deniedTools' AND jsonb_typeof("config"::jsonb->'deniedTools') = 'array' THEN + CASE + WHEN "config"::jsonb->'deniedTools' @> '["delete_asset"]'::jsonb THEN "config"::jsonb->'deniedTools' + ELSE ("config"::jsonb->'deniedTools') || '["delete_asset"]'::jsonb + END + ELSE + '["delete_asset"]'::jsonb + END +); \ No newline at end of file diff --git a/packages/dtos/src/agent.ts b/packages/dtos/src/agent.ts index 172fd962..f6e887e6 100644 --- a/packages/dtos/src/agent.ts +++ b/packages/dtos/src/agent.ts @@ -12,6 +12,8 @@ export type ThinkingLevel = z.infer export const agentPermissionSchema = z.enum(['owner', 'editor', 'reviewer']) export type AgentPermission = z.infer +export const DEFAULT_DENIED_TOOLS = ['delete_asset'] as const + export const agentSkillSchema = z.object({ id: z.string().optional(), skillId: z.string(), diff --git a/packages/webui/components/settings/AgentFormDialog.test.tsx b/packages/webui/components/settings/AgentFormDialog.test.tsx index f6d1db8a..c94d8f55 100644 --- a/packages/webui/components/settings/AgentFormDialog.test.tsx +++ b/packages/webui/components/settings/AgentFormDialog.test.tsx @@ -88,5 +88,8 @@ describe('AgentFormDialog', () => { expect(screen.getByText('Generate Video')).toBeDefined() expect(screen.getByText('Sandboxed Terminal')).toBeDefined() expect(screen.getByText('Read Asset')).toBeDefined() + expect(screen.getByText('Rename Asset')).toBeDefined() + expect(screen.getByText('Move Assets')).toBeDefined() + expect(screen.getByText('Delete Asset')).toBeDefined() }) }) diff --git a/packages/webui/components/settings/AgentFormDialog.tsx b/packages/webui/components/settings/AgentFormDialog.tsx index cc713055..bd150cc9 100644 --- a/packages/webui/components/settings/AgentFormDialog.tsx +++ b/packages/webui/components/settings/AgentFormDialog.tsx @@ -27,7 +27,13 @@ import { Check, ChevronDown, Loader2, Puzzle, Search, Server, Terminal, Zap } fr import { useEffect, useMemo, useState } from 'react' import { m } from '@/ui/paraglide/messages.js' import { toast } from 'sonner' -import { AgentInfo, AgentType, ThinkingLevel, thinkingLevelSchema } from '@shumai/dtos' +import { + AgentInfo, + AgentType, + DEFAULT_DENIED_TOOLS, + ThinkingLevel, + thinkingLevelSchema, +} from '@shumai/dtos' import { usePermissions } from '@/ui/hooks/use-permissions' import { Textarea } from '@/ui/components/ui/textarea' import { ScrollArea } from '@/ui/components/ui/scroll-area' @@ -105,6 +111,21 @@ const BUILTIN_TOOLS = [ name: () => m.agent_tool_generate_video_name(), description: () => m.agent_tool_generate_video_desc(), }, + { + id: 'rename_asset', + name: () => m.agent_tool_rename_asset_name(), + description: () => m.agent_tool_rename_asset_desc(), + }, + { + id: 'move_assets', + name: () => m.agent_tool_move_assets_name(), + description: () => m.agent_tool_move_assets_desc(), + }, + { + id: 'delete_asset', + name: () => m.agent_tool_delete_asset_name(), + description: () => m.agent_tool_delete_asset_desc(), + }, ] type AgentFormValues = z.infer @@ -197,7 +218,7 @@ export function AgentFormDialog({ systemPrompt: initialValues?.systemPrompt || '', skills: initialValues?.skills?.map((s) => s.skillId) || ([] as string[]), mcpServerIds: initialValues?.mcpServerIds || ([] as string[]), - deniedTools: initialValues?.deniedTools || ([] as string[]), + deniedTools: initialValues?.deniedTools ?? [...DEFAULT_DENIED_TOOLS], } as AgentFormValues, validators: { onChange: schema, diff --git a/packages/webui/components/settings/QuotaRuleDialog.tsx b/packages/webui/components/settings/QuotaRuleDialog.tsx index 2cb2db2f..40ee94e8 100644 --- a/packages/webui/components/settings/QuotaRuleDialog.tsx +++ b/packages/webui/components/settings/QuotaRuleDialog.tsx @@ -76,6 +76,9 @@ const STANDARD_TOOLS = [ { value: 'create_version', label: () => m.agent_tool_create_version_name() }, { value: 'generate_image', label: () => m.agent_tool_generate_image_name() }, { value: 'generate_video', label: () => m.agent_tool_generate_video_name() }, + { value: 'rename_asset', label: () => m.agent_tool_rename_asset_name() }, + { value: 'move_assets', label: () => m.agent_tool_move_assets_name() }, + { value: 'delete_asset', label: () => m.agent_tool_delete_asset_name() }, ] /* eslint-disable @typescript-eslint/naming-convention */ diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index f7fde921..4eb14aad 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -533,6 +533,12 @@ "agent_tool_generate_image_desc": "Allows the agent to generate images from prompts and reference images using configured AI image models.", "agent_tool_generate_video_name": "Generate Video", "agent_tool_generate_video_desc": "Allows the agent to generate videos from text, images, or frame sequences using configured AI video models.", + "agent_tool_rename_asset_name": "Rename Asset", + "agent_tool_rename_asset_desc": "Allows the agent to rename an existing file or folder in Shumai.", + "agent_tool_move_assets_name": "Move Assets", + "agent_tool_move_assets_desc": "Allows the agent to move one or more assets to another folder in Shumai.", + "agent_tool_delete_asset_name": "Delete Asset", + "agent_tool_delete_asset_desc": "Allows the agent to delete a single file or folder in Shumai.", "enabled": "Enabled", "disabled": "Disabled", "no_skills_available": "No skills available.", diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index d9e7a548..d255231f 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -533,6 +533,12 @@ "agent_tool_generate_image_desc": "允许智能体使用已配置的 AI 图片模型根据提示词和参考图片生成图片。", "agent_tool_generate_video_name": "生成视频", "agent_tool_generate_video_desc": "允许智能体使用已配置的 AI 视频模型根据提示词、图片或首尾帧生成视频。", + "agent_tool_rename_asset_name": "重命名资产", + "agent_tool_rename_asset_desc": "允许智能体在 Shumai 中重命名现有的文件或文件夹。", + "agent_tool_move_assets_name": "移动资产", + "agent_tool_move_assets_desc": "允许智能体将一个或多个资产移动到 Shumai 中的其他文件夹。", + "agent_tool_delete_asset_name": "删除资产", + "agent_tool_delete_asset_desc": "允许智能体在 Shumai 中删除单个文件或文件夹。", "enabled": "已启用", "disabled": "已禁用", "no_skills_available": "暂无可用技能。", diff --git a/packages/webui/stores/chatbot.ts b/packages/webui/stores/chatbot.ts index fc2d3ee1..8072df77 100644 --- a/packages/webui/stores/chatbot.ts +++ b/packages/webui/stores/chatbot.ts @@ -307,7 +307,14 @@ export const useChatbotStore = create((set) => ({ if ( entryObj.role === 'toolResult' && typeof entryObj.toolName === 'string' && - ['create_file', 'create_folder', 'create_version'].includes(entryObj.toolName) && + [ + 'create_file', + 'create_folder', + 'create_version', + 'rename_asset', + 'move_assets', + 'delete_asset', + ].includes(entryObj.toolName) && !entryObj.isError ) { onAssetMutation?.()