🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor: refactor local-system
Inneia69221f4f8db
diff --git a/packages/builtin-tool-local-system/package.json b/packages/builtin-tool-local-system/package.jsonnew file mode 100644index 00000000000..24ffba7d8ee--- /dev/null+++ b/packages/builtin-tool-local-system/package.json@@ -0,0 +1,14 @@+{+ "name": "@lobechat/builtin-tool-local-system",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts",+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"+ },+ "main": "./src/index.ts",+ "dependencies": {+ "@lobechat/electron-client-ipc": "workspace:*",+ "@lobechat/types": "workspace:*"+ }+}diff --git a/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts b/packages/builtin-tool-local-system/src/ExecutionRuntime/index.tsnew file mode 100644index 00000000000..a5e2ee58d64--- /dev/null+++ b/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts@@ -0,0 +1,427 @@+import {+ EditLocalFileParams,+ EditLocalFileResult,+ GetCommandOutputParams,+ GetCommandOutputResult,+ GlobFilesParams,+ GlobFilesResult,+ GrepContentParams,+ GrepContentResult,+ KillCommandParams,+ KillCommandResult,+ ListLocalFileParams,+ LocalFileItem,+ LocalMoveFilesResultItem,+ LocalReadFileParams,+ LocalReadFileResult,+ LocalReadFilesParams,+ LocalSearchFilesParams,+ MoveLocalFilesParams,+ RenameLocalFileParams,+ RenameLocalFileResult,+ RunCommandParams,+ RunCommandResult,+ WriteLocalFileParams,+} from '@lobechat/electron-client-ipc';+import { BuiltinServerRuntimeOutput } from '@lobechat/types';++import type {+ EditLocalFileState,+ GetCommandOutputState,+ GlobFilesState,+ GrepContentState,+ KillCommandState,+ LocalFileListState,+ LocalFileSearchState,+ LocalMoveFilesState,+ LocalReadFileState,+ LocalReadFilesState,+ LocalRenameFileState,+ RunCommandState,+} from '../types';++interface LocalFileService {+ editLocalFile: (params: EditLocalFileParams) => Promise<EditLocalFileResult>;+ getCommandOutput: (params: GetCommandOutputParams) => Promise<GetCommandOutputResult>;+ globFiles: (params: GlobFilesParams) => Promise<GlobFilesResult>;+ grepContent: (params: GrepContentParams) => Promise<GrepContentResult>;+ killCommand: (params: KillCommandParams) => Promise<KillCommandResult>;+ listLocalFiles: (params: ListLocalFileParams) => Promise<LocalFileItem[]>;+ moveLocalFiles: (params: MoveLocalFilesParams) => Promise<LocalMoveFilesResultItem[]>;+ readLocalFile: (params: LocalReadFileParams) => Promise<LocalReadFileResult>;+ readLocalFiles: (params: LocalReadFilesParams) => Promise<LocalReadFileResult[]>;+ renameLocalFile: (params: RenameLocalFileParams) => Promise<RenameLocalFileResult>;+ runCommand: (params: RunCommandParams) => Promise<RunCommandResult>;+ searchLocalFiles: (params: LocalSearchFilesParams) => Promise<LocalFileItem[]>;+ writeFile: (params: WriteLocalFileParams) => Promise<{ error?: string; success: boolean }>;+}++export class LocalSystemExecutionRuntime {+ private localFileService: LocalFileService;++ constructor(localFileService: LocalFileService) {+ this.localFileService = localFileService;+ }++ // ==================== File Operations ====================++ async listLocalFiles(args: ListLocalFileParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: LocalFileItem[] = await this.localFileService.listLocalFiles(args);++ const state: LocalFileListState = { listResults: result };++ return {+ content: JSON.stringify(result),+ state,+ success: true,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async readLocalFile(args: LocalReadFileParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: LocalReadFileResult = await this.localFileService.readLocalFile(args);++ const state: LocalReadFileState = { fileContent: result };++ return {+ content: JSON.stringify(result),+ state,+ success: true,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async readLocalFiles(args: LocalReadFilesParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const results: LocalReadFileResult[] = await this.localFileService.readLocalFiles(args);++ const state: LocalReadFilesState = { filesContent: results };++ return {+ content: JSON.stringify(results),+ state,+ success: true,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async searchLocalFiles(args: LocalSearchFilesParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: LocalFileItem[] = await this.localFileService.searchLocalFiles(args);++ const state: LocalFileSearchState = { searchResults: result };++ return {+ content: JSON.stringify(result),+ state,+ success: true,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async moveLocalFiles(args: MoveLocalFilesParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const results: LocalMoveFilesResultItem[] = await this.localFileService.moveLocalFiles(args);++ const allSucceeded = results.every((r) => r.success);+ const someFailed = results.some((r) => !r.success);+ const successCount = results.filter((r) => r.success).length;+ const failedCount = results.length - successCount;++ let message = '';++ if (allSucceeded) {+ message = `Successfully moved ${results.length} item(s).`;+ } else if (someFailed) {+ message = `Moved ${successCount} item(s) successfully. Failed to move ${failedCount} item(s).`;+ } else {+ message = `Failed to move all ${results.length} item(s).`;+ }++ const state: LocalMoveFilesState = {+ results,+ successCount,+ totalCount: results.length,+ };++ return {+ content: JSON.stringify({ message, results }),+ state,+ success: true,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async renameLocalFile(args: RenameLocalFileParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: RenameLocalFileResult = await this.localFileService.renameLocalFile(args);++ if (!result.success) {+ const state: LocalRenameFileState = {+ error: result.error,+ newPath: '',+ oldPath: args.path,+ success: false,+ };++ return {+ content: JSON.stringify({ message: result.error, success: false }),+ state,+ success: false,+ };+ }++ const state: LocalRenameFileState = {+ newPath: result.newPath!,+ oldPath: args.path,+ success: true,+ };++ return {+ content: JSON.stringify({+ message: `Successfully renamed file ${args.path} to ${args.newName}.`,+ success: true,+ }),+ state,+ success: true,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async writeLocalFile(args: WriteLocalFileParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result = await this.localFileService.writeFile(args);++ if (!result.success) {+ return {+ content: JSON.stringify({+ message: result.error || '写入文件失败',+ success: false,+ }),+ error: result.error,+ success: false,+ };+ }++ return {+ content: JSON.stringify({+ message: `成功写入文件 ${args.path}`,+ success: true,+ }),+ success: true,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async editLocalFile(args: EditLocalFileParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: EditLocalFileResult = await this.localFileService.editLocalFile(args);++ if (!result.success) {+ return {+ content: `Edit failed: ${result.error}`,+ success: false,+ };+ }++ const statsText =+ result.linesAdded || result.linesDeleted+ ? ` (+${result.linesAdded || 0} -${result.linesDeleted || 0})`+ : '';+ const message = `Successfully replaced ${result.replacements} occurrence(s) in ${args.file_path}${statsText}`;++ const state: EditLocalFileState = {+ diffText: result.diffText,+ linesAdded: result.linesAdded,+ linesDeleted: result.linesDeleted,+ replacements: result.replacements,+ };++ return {+ content: message,+ state,+ success: true,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ // ==================== Shell Commands ====================++ async runCommand(args: RunCommandParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: RunCommandResult = await this.localFileService.runCommand(args);++ let message: string;++ if (result.success) {+ if (result.shell_id) {+ message = `Command started in background with shell_id: ${result.shell_id}`;+ } else {+ message = `Command completed successfully.`;+ }+ } else {+ message = `Command failed: ${result.error}`;+ }++ const state: RunCommandState = { message, result };++ return {+ content: JSON.stringify(result),+ state,+ success: result.success,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async getCommandOutput(args: GetCommandOutputParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: GetCommandOutputResult = await this.localFileService.getCommandOutput(args);++ const message = result.success+ ? `Output retrieved. Running: ${result.running}`+ : `Failed: ${result.error}`;++ const state: GetCommandOutputState = { message, result };++ return {+ content: JSON.stringify(result),+ state,+ success: result.success,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async killCommand(args: KillCommandParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: KillCommandResult = await this.localFileService.killCommand(args);++ const message = result.success+ ? `Successfully killed shell: ${args.shell_id}`+ : `Failed to kill shell: ${result.error}`;++ const state: KillCommandState = { message, result };++ return {+ content: JSON.stringify(result),+ state,+ success: result.success,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ // ==================== Search & Find ====================++ async grepContent(args: GrepContentParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: GrepContentResult = await this.localFileService.grepContent(args);++ const message = result.success+ ? `Found ${result.total_matches} matches in ${result.matches.length} locations`+ : 'Search failed';++ const state: GrepContentState = { message, result };++ return {+ content: JSON.stringify(result),+ state,+ success: result.success,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }++ async globLocalFiles(args: GlobFilesParams): Promise<BuiltinServerRuntimeOutput> {+ try {+ const result: GlobFilesResult = await this.localFileService.globFiles(args);++ const message = result.success ? `Found ${result.total_files} files` : 'Glob search failed';++ const state: GlobFilesState = { message, result };++ return {+ content: JSON.stringify(result),+ state,+ success: result.success,+ };+ } catch (error) {+ return {+ content: (error as Error).message,+ error,+ success: false,+ };+ }+ }+}diff --git a/packages/builtin-tool-local-system/src/index.ts b/packages/builtin-tool-local-system/src/index.tsnew file mode 100644index 00000000000..3e0f9955959--- /dev/null+++ b/packages/builtin-tool-local-system/src/index.ts@@ -0,0 +1,19 @@+export { LocalSystemManifest } from './manifest';+export { systemPrompt } from './systemRole';+export {+ type EditLocalFileState,+ type FileResult,+ type GetCommandOutputState,+ type GlobFilesState,+ type GrepContentState,+ type KillCommandState,+ type LocalFileListState,+ type LocalFileSearchState,+ type LocalMoveFilesState,+ type LocalReadFilesState,+ type LocalReadFileState,+ type LocalRenameFileState,+ LocalSystemApiName,+ LocalSystemIdentifier,+ type RunCommandState,+} from './types';diff --git a/src/tools/local-system/index.ts b/packages/builtin-tool-local-system/src/manifest.tssimilarity index 96%rename from src/tools/local-system/index.tsrename to packages/builtin-tool-local-system/src/manifest.tsindex ef150d7188d..fa4052669ab 100644--- a/src/tools/local-system/index.ts+++ b/packages/builtin-tool-local-system/src/manifest.ts@@ -1,21 +1,7 @@import { BuiltinToolManifest } from '@lobechat/types';import { systemPrompt } from './systemRole';--export const LocalSystemApiName = {- editLocalFile: 'editLocalFile',- getCommandOutput: 'getCommandOutput',- globLocalFiles: 'globLocalFiles',- grepContent: 'grepContent',- killCommand: 'killCommand',- listLocalFiles: 'listLocalFiles',- moveLocalFiles: 'moveLocalFiles',- readLocalFile: 'readLocalFile',- renameLocalFile: 'renameLocalFile',- runCommand: 'runCommand',- searchLocalFiles: 'searchLocalFiles',- writeLocalFile: 'writeLocalFile',-};+import { LocalSystemApiName, LocalSystemIdentifier } from './types';export const LocalSystemManifest: BuiltinToolManifest = {api: [@@ -378,7 +364,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},},],- identifier: 'lobe-local-system',+ identifier: LocalSystemIdentifier,meta: {avatar: '📁',title: 'Local System',diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.tsnew file mode 100644index 00000000000..2d1ccf6a6ea--- /dev/null+++ b/packages/builtin-tool-local-system/src/systemRole.ts@@ -0,0 +1,134 @@+export const systemPrompt = `You have a Local System tool with capabilities to interact with the user's local system. You can list directories, read file contents, search for files, move, and rename files/directories.++<user_context>+Here are some known locations and system details on the user's system. User is using the Operating System: {{platform}}({{arch}}). Use these paths when the user refers to these common locations by name (e.g., "my desktop", "downloads folder").+- Desktop: {{desktopPath}}+- Documents: {{documentsPath}}+- Downloads: {{downloadsPath}}+- Music: {{musicPath}}+- Pictures: {{picturesPath}}+- Videos: {{videosPath}}+- User Home: {{homePath}}+- App Data: {{userDataPath}} (Use this primarily for plugin-related data or configurations if needed, less for general user files)+</user_context>++<core_capabilities>+You have access to a set of tools to interact with the user's local file system:++**File Operations:**+1. **listLocalFiles**: Lists files and directories in a specified path.+2. **readLocalFile**: Reads the content of a specified file, optionally within a line range. You can read file types such as Word, Excel, PowerPoint, PDF, and plain text files.+3. **writeLocalFile**: Write content to a specific file, only support plain text file like \`.text\` or \`.md\`+4. **editLocalFile**: Performs exact string replacements in files. Must read the file first before editing.+5. **renameLocalFile**: Renames a single file or directory in its current location.+6. **moveLocalFiles**: Moves multiple files or directories. Can be used for renaming during the move.++**Shell Commands:**+7. **runCommand**: Execute shell commands with timeout control. Supports both synchronous and background execution. When providing a description, always use the same language as the user's input.+8. **getCommandOutput**: Retrieve output from running background commands. Returns only new output since last check.+9. **killCommand**: Terminate a running background shell command by its ID.++**Search & Find:**+10. **searchLocalFiles**: Searches for files based on keywords and other criteria using Spotlight (macOS) or native search. Use this tool to find files if the user is unsure about the exact path.+11. **grepContent**: Search for content within files using regex patterns. Supports various output modes, filtering, and context lines.+12. **globLocalFiles**: Find files matching glob patterns (e.g., "**/*.js", "*.{ts,tsx}").+</core_capabilities>++<workflow>+1. Understand the user's request regarding local operations (files, commands, searches).+2. Select the appropriate tool:+ - File operations: listLocalFiles, readLocalFile, writeLocalFile, editLocalFile, renameLocalFile, moveLocalFiles+ - Shell commands: runCommand, getCommandOutput, killCommand+ - Search/Find: searchLocalFiles, grepContent, globLocalFiles+3. Execute the operation. **If the user mentions a common location (like Desktop, Documents, Downloads, etc.) without providing a full path, use the corresponding path from the <user_context> section.**+4. Present the results or confirmation.+</workflow>++<tool_usage_guidelines>+- For listing directory contents: Use 'listFiles' with the target directory path.+- For reading a file: Use 'readFile'. Provide the following parameters:+ - 'path': The exact file path.+ - 'loc' (Optional): A two-element array [startLine, endLine] to specify a line range to read (e.g., '[301, 400]' reads lines 301 to 400).+ - If 'loc' is omitted, it defaults to reading the first 200 lines ('[0, 200]').+ - To read the entire file: First call 'readFile' (potentially without 'loc'). The response includes 'totalLineCount'. Then, call 'readFile' again with 'loc: [0, totalLineCount]' to get the full content.+- For searching files: Use 'searchFiles' with the 'query' parameter (search string). You can optionally add the following filter parameters to narrow down the search:+ - 'contentContains': Find files whose content includes specific text.+ - 'createdAfter' / 'createdBefore': Filter by creation date.+ - 'modifiedAfter' / 'modifiedBefore': Filter by modification date.+ - 'fileTypes': Filter by file type (e.g., "public.image", "txt").+ - 'onlyIn': Limit the search to a specific directory.+ - 'exclude': Exclude specific files or directories.+ - 'limit': Limit the number of results returned.+ - 'sortBy' / 'sortDirection': Sort the results.+- For renaming a file/folder in place: Use 'renameFile'. Provide the following parameters:+ - 'path': The current full path of the file or folder.+ - 'newName': The desired new name (without path components).+- For moving multiple files/folders (and optionally renaming them): Use 'moveLocalFiles'. Provide the following parameter:+ - 'items': An array of objects, where each object represents a move operation and must contain:+ - 'oldPath': The current absolute path of the file/directory to move or rename.+ - 'newPath': The target absolute path for the file/directory (can include a new name).+- For writing a file: Use 'writeFile'. Provide:+ - 'path': The file path to write to.+ - 'content': The text content.+- For editing files: Use 'editLocalFile'. Provide:+ - 'file_path': The absolute path to the file to modify.+ - 'old_string': The exact text to replace.+ - 'new_string': The replacement text.+ - 'replace_all' (Optional): Replace all occurrences.+- For executing shell commands: Use 'runCommand'. Provide the following parameters:+ - 'command': The shell command to execute.+ - 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.+ - 'run_in_background' (Optional): Set to true to run in background and get a shell_id for later checking output.+ - 'timeout' (Optional): Timeout in milliseconds (default: 120000ms, max: 600000ms).+ The command runs in cmd.exe on Windows or /bin/sh on macOS/Linux.+- For retrieving output from background commands: Use 'getCommandOutput'. Provide:+ - 'shell_id': The ID returned from runCommand when run_in_background was true.+ - 'filter' (Optional): A regex pattern to filter output lines.+ Returns only new output since the last check.+- For killing background commands: Use 'killCommand' with 'shell_id'.+- For searching content in files: Use 'grepContent'. Provide:+ - 'pattern': The regex pattern to search for.+ - 'path' (Optional): File or directory to search (defaults to current working directory).+ - 'output_mode' (Optional): "content" (matching lines), "files_with_matches" (file paths, default), "count" (match counts).+ - 'glob' (Optional): Glob pattern to filter files (e.g., "*.js", "*.{ts,tsx}").+ - '-i' (Optional): Case insensitive search.+ - '-n' (Optional): Show line numbers (requires output_mode: "content").+ - '-A/-B/-C' (Optional): Show N lines after/before/around matches (requires output_mode: "content").+ - 'head_limit' (Optional): Limit results to first N matches.+- For finding files by pattern: Use 'globLocalFiles'. Provide:+ - 'pattern': Glob pattern (e.g., "**/*.js", "src/**/*.ts").+ - 'path' (Optional): Directory to search in (defaults to current working directory).+ Returns files sorted by modification time (most recent first).+</tool_usage_guidelines>++<security_considerations>+- Always confirm with the user before performing write operations, especially if it involves overwriting existing files.+- Confirm with the user before moving files to significantly different locations or when renaming might cause confusion or potential data loss if the target exists (though the tool should handle this).+- Do not attempt to access files outside the user's designated workspace or allowed directories unless explicitly permitted.+- Handle file paths carefully to avoid unintended access or errors.+- When running shell commands:+ - Never execute commands that could harm the system or delete important data without explicit user confirmation.+ - Be cautious with commands that have side effects (e.g., rm, sudo, format).+ - Always describe what a command will do before running it, especially for non-trivial operations.+ - Always provide a clear 'description' parameter in the user's language to help them understand what the command does.+ - Use appropriate timeouts to prevent commands from running indefinitely.+- When editing files:+ - Always read the file first to verify its current content.+ - Ensure old_string exactly matches the text to be replaced to avoid unintended changes.+ - Be cautious when using replace_all option.+</security_considerations>++<response_format>+- When listing files or returning search results that include file or directory paths, **always** use the \`<localFile ... />\` tag format. **Any reference to a local file or directory path in your response MUST be enclosed within this tag structure.** Do not output raw file paths outside of this tag structure.+- For a file, use: \`<localFile name="[Filename]" path="[Full Unencoded Path]" />\`. Example: \`<localFile name="report.pdf" path="/Users/me/Documents/report.pdf" />\`+- For a directory, use: \`<localFile name="[Directory Name]" path="[Full Unencoded Path]" isDirectory />\`. Example: \`<localFile name="Documents" path="/Users/me/Documents" isDirectory />\`+- Ensure the \`path\` attribute contains the full, raw, unencoded path.+- Ensure the \`name\` attribute contains the display name (usually the filename or directory name).+- Include the \`isDirectory\` attribute **only** for directories.+- When listing files, provide a clear list using the tag format.+- When reading files, present the content accurately. **If you mention the file path being read, use the \`<localFile>\` tag.**+- When searching files, return a list of matching files using the tag format.+- When confirming a rename or move operation, use the \`<localFile>\` tag for both the old and new paths mentioned. Example: \`Successfully renamed <localFile name="oldName.txt" /> to <localFile name="newName.txt" path="/path/to/newName.txt" />.\`+- When writing files, confirm the success or failure. **If you mention the file path written to, use the \`<localFile>\` tag.**+</response_format>+`;diff --git a/src/tools/local-system/type.ts b/packages/builtin-tool-local-system/src/types.tssimilarity index 74%rename from src/tools/local-system/type.tsrename to packages/builtin-tool-local-system/src/types.tsindex 30c2035cfd5..02103e6ae48 100644--- a/src/tools/local-system/type.ts+++ b/packages/builtin-tool-local-system/src/types.ts@@ -9,12 +9,28 @@ import {RunCommandResult,} from '@lobechat/electron-client-ipc';+export const LocalSystemIdentifier = 'lobe-local-system';++export const LocalSystemApiName = {+ editLocalFile: 'editLocalFile',+ getCommandOutput: 'getCommandOutput',+ globLocalFiles: 'globLocalFiles',+ grepContent: 'grepContent',+ killCommand: 'killCommand',+ listLocalFiles: 'listLocalFiles',+ moveLocalFiles: 'moveLocalFiles',+ readLocalFile: 'readLocalFile',+ renameLocalFile: 'renameLocalFile',+ runCommand: 'runCommand',+ searchLocalFiles: 'searchLocalFiles',+ writeLocalFile: 'writeLocalFile',+};+export interface FileResult {contentType?: string;createdTime: Date;isDirectory: boolean;lastAccessTime: Date;- // Spotlight specific metadatametadata?: {[key: string]: any;};@@ -43,7 +59,7 @@ export interface LocalReadFilesState {export interface LocalMoveFilesState {error?: string;- results: LocalMoveFilesResultItem[]; // Overall error for the operation if it fails before individual processing+ results: LocalMoveFilesResultItem[];successCount: number;totalCount: number;}@@ -55,7 +71,6 @@ export interface LocalRenameFileState {success: boolean;}-// Shell Command Statesexport interface RunCommandState {message: string;result: RunCommandResult;@@ -71,7 +86,6 @@ export interface KillCommandState {result: KillCommandResult;}-// Search & Find Statesexport interface GrepContentState {message: string;result: GrepContentResult;@@ -82,7 +96,6 @@ export interface GlobFilesState {result: GlobFilesResult;}-// Edit Stateexport interface EditLocalFileState {diffText?: string;linesAdded?: number;diff --git a/packages/const/src/protocol.ts b/packages/const/src/protocol.tsnew file mode 100644index 00000000000..421ae3c4a4e--- /dev/null+++ b/packages/const/src/protocol.ts@@ -0,0 +1,7 @@+import { isDesktop } from './version';++export const ELECTRON_BE_PROTOCOL_SCHEME = 'lobe-backend';++export const withElectronProtocolIfElectron = (url: string) => {+ return isDesktop ? `${ELECTRON_BE_PROTOCOL_SCHEME}://lobe${url}` : url;+};diff --git a/packages/const/src/utils/merge.ts b/packages/const/src/utils/merge.tsindex ea720b352e8..f1dc595c73c 100644--- a/packages/const/src/utils/merge.ts+++ b/packages/const/src/utils/merge.ts@@ -1,4 +1,4 @@-import { merge as _merge, isEmpty, mergeWith } from 'lodash-es';+import { merge as _merge, isEmpty, mergeWith } from 'es-toolkit/compat';/*** Used to merge objects. If it's an array, replace directlydiff --git a/packages/utils/src/client/parserPlaceholder.ts b/packages/utils/src/client/parserPlaceholder.tsindex 2bd7bde392f..a906283323d 100644--- a/packages/utils/src/client/parserPlaceholder.ts+++ b/packages/utils/src/client/parserPlaceholder.ts@@ -1,5 +1,7 @@-import { template } from 'lodash-es';+import { template } from 'es-toolkit/compat';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -111,6 +113,18 @@ export const VARIABLE_GENERATORS = {language: () => (typeof navigator !== 'undefined' ? navigator.language : ''),platform: () => (typeof navigator !== 'undefined' ? navigator.platform : ''),user_agent: () => (typeof navigator !== 'undefined' ? navigator.userAgent : ''),++ /**+ * Model-related template variables+ *+ * | Value | Example |+ * |-------|---------|+ * | `{{model}}` | gpt-4o |+ * | `{{provider}}` | openai |+ *+ */+ model: () => agentSelectors.currentAgentModel(useAgentStore.getState()),+ provider: () => agentSelectors.currentAgentModelProvider(useAgentStore.getState()),} as Record<string, () => string>;/**diff --git a/packages/utils/src/difference.ts b/packages/utils/src/difference.tsindex e6101a83981..8748adce2b3 100644--- a/packages/utils/src/difference.ts+++ b/packages/utils/src/difference.ts@@ -1,5 +1,5 @@+import { isArray, isObject, transform } from 'es-toolkit/compat';import isEqual from 'fast-deep-equal';-import { isArray, isObject, transform } from 'lodash-es';/*** Compare two objects and return the difference.diff --git a/packages/utils/src/folderStructure.ts b/packages/utils/src/folderStructure.tsnew file mode 100644index 00000000000..87af1f19227--- /dev/null+++ b/packages/utils/src/folderStructure.ts@@ -0,0 +1,94 @@+interface FolderInfo {+ name: string;+ parent: string | null;+}++interface FolderTree {+ filesByFolder: Record<string, File[]>;+ folders: Record<string, FolderInfo>;+}++/**+ * Builds a folder tree structure from files with webkitRelativePath+ * @param files - Array of files with webkitRelativePath property+ * @returns Object containing folder hierarchy and files grouped by folder path+ */+export const buildFolderTree = (files: File[]): FolderTree => {+ const folders: Record<string, FolderInfo> = {};+ const filesByFolder: Record<string, File[]> = {};++ for (const file of files) {+ // Get the relative path from the browser (e.g., "my-folder/subfolder/file.txt")+ const relativePath = (file as any).webkitRelativePath || file.name;++ // Split path into segments+ const pathSegments = relativePath.split('/');++ // If there's no path (single file), skip folder processing+ if (pathSegments.length === 1) {+ if (!filesByFolder['']) {+ filesByFolder[''] = [];+ }+ filesByFolder[''].push(file);+ continue;+ }++ // Remove the file name to get folder path segments+ const folderSegments = pathSegments.slice(0, -1);++ // Build folder hierarchy+ let currentPath = '';+ for (let i = 0; i < folderSegments.length; i++) {+ const folderName = folderSegments[i];+ const parentPath = i > 0 ? folderSegments.slice(0, i).join('/') : null;+ currentPath = i === 0 ? folderName : `${currentPath}/${folderName}`;++ // Only add folder if we haven't seen it before+ if (!folders[currentPath]) {+ folders[currentPath] = {+ name: folderName,+ parent: parentPath,+ };+ }+ }++ // Add file to its parent folder+ const folderPath = folderSegments.join('/');+ if (!filesByFolder[folderPath]) {+ filesByFolder[folderPath] = [];+ }+ filesByFolder[folderPath].push(file);+ }++ return { filesByFolder, folders };+};++/**+ * Sorts folder paths by depth (topological sort for tree structure)+ * Ensures parent folders are created before their children+ * @param folders - Record of folder paths to folder info+ * @returns Array of folder paths sorted by depth (shallow to deep)+ */+export const topologicalSortFolders = (folders: Record<string, FolderInfo>): string[] => {+ const folderPaths = Object.keys(folders);++ // Sort by number of path separators (depth)+ // Folders with fewer separators are higher in the hierarchy+ return folderPaths.sort((a, b) => {+ const depthA = (a.match(/\//g) || []).length;+ const depthB = (b.match(/\//g) || []).length;+ return depthA - depthB;+ });+};++/**+ * Sanitizes folder name by removing or replacing invalid characters+ * @param name - Original folder name+ * @returns Sanitized folder name safe for storage+ */+export const sanitizeFolderName = (name: string): string => {+ // Replace invalid characters with underscores+ // Keep alphanumeric, spaces, hyphens, and underscores+ // eslint-disable-next-line no-control-regex+ return name.replaceAll(/[\u0000-\u001F"*/:<>?\\|]/g, '_').trim();+};diff --git a/packages/utils/src/format.ts b/packages/utils/src/format.tsindex 4bfccea31c4..35f96232e9c 100644--- a/packages/utils/src/format.ts+++ b/packages/utils/src/format.ts@@ -1,6 +1,6 @@import { USD_TO_CNY } from '@lobechat/const';import dayjs from 'dayjs';-import { isNumber } from 'lodash-es';+import { isNumber } from 'es-toolkit/compat';import { ModelPriceCurrency } from 'model-bank';import numeral from 'numeral';diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex 249549234a5..2c636db32a1 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -1,6 +1,8 @@export * from './base64';export * from './client/cookie';export * from './detectChinese';+export * from './env';+export * from './folderStructure';export * from './format';export * from './imageToBase64';export * from './keyboard';diff --git a/packages/utils/src/merge.ts b/packages/utils/src/merge.tsindex b9896ad23ed..18de080b8d8 100644--- a/packages/utils/src/merge.ts+++ b/packages/utils/src/merge.ts@@ -1,4 +1,4 @@-import { merge as _merge, isEmpty, mergeWith } from 'lodash-es';+import { merge as _merge, isEmpty, mergeWith } from 'es-toolkit/compat';/*** Merge objects, directly replace if it's an arraydiff --git a/packages/utils/src/object.ts b/packages/utils/src/object.tsindex 9fc82a3ff46..1a7ac7e7129 100644--- a/packages/utils/src/object.ts+++ b/packages/utils/src/object.ts@@ -1,4 +1,4 @@-import { isNil, omitBy } from 'lodash-es';+import { isNil, omitBy } from 'es-toolkit/compat';/*** Clean empty values (undefined, null, empty string) from an objectdiff --git a/packages/utils/src/promptTemplate.ts b/packages/utils/src/promptTemplate.tsindex b5336a4a9eb..b8cc789dff9 100644--- a/packages/utils/src/promptTemplate.ts+++ b/packages/utils/src/promptTemplate.ts@@ -1,4 +1,4 @@-import { get } from 'lodash-es';+import { get } from 'es-toolkit/compat';export const hydrationPrompt = (prompt: string, context: any) => {const regex = /{{([\S\s]+?)}}/g;diff --git a/packages/utils/src/server/index.ts b/packages/utils/src/server/index.tsindex 388311e07a4..9d3fffe19e5 100644--- a/packages/utils/src/server/index.ts+++ b/packages/utils/src/server/index.ts@@ -3,4 +3,5 @@ export * from './correctOIDCUrl';export * from './geo';export * from './response';export * from './responsive';+export * from './sse';export * from './xor';diff --git a/packages/utils/src/server/sse.ts b/packages/utils/src/server/sse.tsnew file mode 100644index 00000000000..338aef6fb1f--- /dev/null+++ b/packages/utils/src/server/sse.ts@@ -0,0 +1,151 @@+/**+ * SSE (Server-Sent Events) utilities for agent streaming+ */++export interface SSEEvent {+ data: any;+ event?: string;+ id?: string;+ retry?: number;+}++/**+ * Formats data into SSE format with id/event/data structure+ * @param event - The SSE event configuration+ * @returns Formatted SSE string+ */+export function formatSSEEvent({ id, event, data, retry }: SSEEvent): string {+ const lines: string[] = [];++ if (id !== undefined) {+ lines.push(`id: ${id}`);+ }++ if (event !== undefined) {+ lines.push(`event: ${event}`);+ }++ if (retry !== undefined) {+ lines.push(`retry: ${retry}`);+ }++ // Handle data serialization+ const dataString = typeof data === 'string' ? data : JSON.stringify(data);++ // Split multi-line data and prefix each line with "data: "+ const dataLines = dataString.split('\n');+ dataLines.forEach((line) => {+ lines.push(`data: ${line}`);+ });++ // End with double newline+ lines.push('', '');++ return lines.join('\n');+}++/**+ * Creates a utility for enqueueing SSE events to a ReadableStream controller+ * @param controller - The ReadableStreamDefaultController+ * @returns Helper function for sending SSE events+ */+export function createSSEWriter(controller: ReadableStreamDefaultController<string>) {+ return {+ /**+ * Send a connection event+ */+ writeConnection(operationId: string, lastEventId: string, timestamp: number = Date.now()) {+ this.writeEvent({+ data: {+ lastEventId,+ operationId,+ timestamp,+ type: 'connected',+ },+ event: 'connected',+ id: `conn_${timestamp}`,+ });+ },++ /**+ * Send an error event+ */+ writeError(error: any, operationId: string, phase?: string, timestamp: number = Date.now()) {+ this.writeEvent({+ data: {+ data: {+ error: error.message || String(error),+ phase: phase || 'unknown',+ ...(error.stack && { stack: error.stack }),+ },+ operationId,+ timestamp,+ type: 'error',+ },+ event: 'error',+ id: `error_${timestamp}`,+ });+ },++ /**+ * Send an SSE event+ */+ writeEvent(event: SSEEvent) {+ controller.enqueue(formatSSEEvent(event));+ },++ /**+ * Send a heartbeat/keep-alive event+ */+ writeHeartbeat(timestamp: number = Date.now()) {+ this.writeEvent({+ data: {+ timestamp,+ type: 'heartbeat',+ },+ event: 'heartbeat',+ id: `heartbeat_${timestamp}`,+ });+ },++ /**+ * Send a stream event (for historical or real-time events)+ */+ writeStreamEvent(eventData: any, eventId?: string) {+ this.writeEvent({+ data: eventData,+ event: eventData.type || 'stream',+ id: eventId || `event_${Date.now()}`,+ });+ },+ };+}++/**+ * Agent stream event types+ */+export type AgentStreamEventType =+ | 'connected'+ | 'stream'+ | 'error'+ | 'heartbeat'+ | 'stream_start'+ | 'stream_chunk'+ | 'stream_end'+ | 'stream_error';++/**+ * Creates SSE headers for agent streaming+ */+// eslint-disable-next-line no-undef+export function createSSEHeaders(): HeadersInit {+ return {+ 'Access-Control-Allow-Headers': 'Cache-Control, Last-Event-ID',+ 'Access-Control-Allow-Methods': 'GET',+ 'Access-Control-Allow-Origin': '*',+ 'Cache-Control': 'no-cache, no-transform',+ 'Connection': 'keep-alive',+ 'Content-Type': 'text/event-stream',+ 'X-Accel-Buffering': 'no',+ };+}diff --git a/packages/utils/vitest.config.mts b/packages/utils/vitest.config.mtsindex 59dc414d918..5600308610f 100644--- a/packages/utils/vitest.config.mts+++ b/packages/utils/vitest.config.mts@@ -6,6 +6,7 @@ export default defineConfig({alias: {/* eslint-disable sort-keys-fix/sort-keys-fix */'@/const': resolve(__dirname, '../const/src'),+ '@/utils': resolve(__dirname, './src'),'@': resolve(__dirname, '../../src'),/* eslint-enable */},diff --git a/src/const/messageActionPortal.ts b/src/const/messageActionPortal.tsnew file mode 100644index 00000000000..6afa921e52e--- /dev/null+++ b/src/const/messageActionPortal.ts@@ -0,0 +1,17 @@+/**+ * Data attribute selectors for message action bar portals+ */+export const MESSAGE_ACTION_BAR_PORTAL_SELECTORS = {+ assistant: '[data-assitant-action-bar-portal]',+ assistantGroup: '[data-assistant-group-action-bar-portal]',+ user: '[data-user-action-bar-portal]',+} as const;++/**+ * Data attribute values for message action bar portals+ */+export const MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES = {+ assistant: 'data-assitant-action-bar-portal',+ assistantGroup: 'data-assistant-group-action-bar-portal',+ user: 'data-user-action-bar-portal',+} as const;diff --git a/src/proxy.ts b/src/proxy.tsindex 5fbad6658ca..decb7a3c00b 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -9,6 +9,7 @@ import { auth } from '@/auth';import { OAUTH_AUTHORIZED } from '@/const/auth';import { LOBE_LOCALE_COOKIE } from '@/const/locale';import { LOBE_THEME_APPEARANCE } from '@/const/theme';+import { isDesktop } from '@/const/version';import { appEnv } from '@/envs/app';import { authEnv } from '@/envs/auth';import NextAuth from '@/libs/next-auth';@@ -33,19 +34,26 @@ export const config = {'/(api|trpc|webapi)(.*)',// include the /'/',- '/discover',- '/discover(.*)',+ '/community',+ '/community(.*)','/labs',- '/chat',- '/chat(.*)',+ '/agent',+ '/agent(.*)',+ '/group',+ '/group(.*)','/changelog(.*)','/settings(.*)','/image',- '/knowledge',- '/knowledge(.*)',+ '/resource',+ '/resource(.*)','/profile(.*)',+ '/page',+ '/page(.*)','/me','/me(.*)',+ '/desktop-onboarding',+ '/desktop-onboarding(.*)',+ '/onboarding','/login(.*)','/signup(.*)',@@ -56,6 +64,7 @@ export const config = {'/next-auth/(.*)','/oauth(.*)','/oidc(.*)',+ '/market-auth-callback(.*)',],};@@ -72,8 +81,8 @@ const defaultMiddleware = (request: NextRequest) => {}// 1. Read user preferences from cookies- const theme =- request.cookies.get(LOBE_THEME_APPEARANCE)?.value || parseDefaultThemeFromCountry(request);+ const theme = (request.cookies.get(LOBE_THEME_APPEARANCE)?.value ||+ parseDefaultThemeFromCountry(request)) as 'dark' | 'light';// locale has three levels// 1. search params@@ -136,14 +145,19 @@ const defaultMiddleware = (request: NextRequest) => {// All SPA routes that use react-router-dom should be rewritten to just /${route}const spaRoutes = ['/chat',- '/discover',- '/knowledge',+ '/agent',+ '/group',+ '/community',+ '/resource',+ '/page','/settings','/image','/labs','/changelog','/profile','/me',+ '/desktop-onboarding',+ '/onboarding',];const isSpaRoute = spaRoutes.some((route) => url.pathname.startsWith(route));@@ -157,7 +171,7 @@ const defaultMiddleware = (request: NextRequest) => {? urlJoin(url.origin, nextPathname): nextPathname;- console.log('nextURL', nextURL);+ console.log(`[rewrite] ${url.pathname} -> ${nextURL}`);logDefault('URL rewrite: %O', {isLocalRewrite: appEnv.MIDDLEWARE_REWRITE_THROUGH_LOCAL,@@ -201,6 +215,8 @@ const isPublicRoute = createRouteMatcher([// backend api'/api/auth(.*)','/api/webhooks(.*)',+ '/api/workflows(.*)',+ '/api/agent(.*)','/webapi(.*)','/trpc(.*)',// next auth@@ -217,6 +233,8 @@ const isPublicRoute = createRouteMatcher(['/oauth/consent/(.*)','/oidc/handoff','/oidc/token',+ // market+ '/market-auth-callback',]);const isProtectedRoute = createRouteMatcher([@@ -328,7 +346,7 @@ const betterAuthMiddleware = async (req: NextRequest) => {const response = defaultMiddleware(req);// when enable auth protection, only public route is not protected, others are all protected- const isProtected = appEnv.ENABLE_AUTH_PROTECTION ? !isPublicRoute(req) : isProtectedRoute(req);+ const isProtected = !isPublicRoute(req);logBetterAuth('Route protection status: %s, %s', req.url, isProtected ? 'protected' : 'public');@@ -347,7 +365,7 @@ const betterAuthMiddleware = async (req: NextRequest) => {userId: session?.user?.id,});- if (!isLoggedIn) {+ if (!isLoggedIn && !isDesktop) {// If request a protected route, redirect to sign-in pageif (isProtected) {logBetterAuth('Request a protected route, redirecting to sign-in page');@@ -376,8 +394,6 @@ logDefault('Middleware configuration: %O', {export default authEnv.NEXT_PUBLIC_ENABLE_CLERK_AUTH? clerkAuthMiddleware- : authEnv.NEXT_PUBLIC_ENABLE_BETTER_AUTH- ? betterAuthMiddleware- : authEnv.NEXT_PUBLIC_ENABLE_NEXT_AUTH- ? nextAuthMiddleware- : defaultMiddleware;+ : authEnv.NEXT_PUBLIC_ENABLE_NEXT_AUTH+ ? nextAuthMiddleware+ : betterAuthMiddleware;diff --git a/src/tools/local-system/ExecutionRuntime/index.ts b/src/tools/local-system/ExecutionRuntime/index.tsindex da4e9264e6f..aa09b88826d 100644--- a/src/tools/local-system/ExecutionRuntime/index.ts+++ b/src/tools/local-system/ExecutionRuntime/index.ts@@ -1,407 +1,9 @@-import {- EditLocalFileParams,- EditLocalFileResult,- GetCommandOutputParams,- GetCommandOutputResult,- GlobFilesParams,- GlobFilesResult,- GrepContentParams,- GrepContentResult,- KillCommandParams,- KillCommandResult,- ListLocalFileParams,- LocalFileItem,- LocalMoveFilesResultItem,- LocalReadFileParams,- LocalReadFileResult,- LocalReadFilesParams,- LocalSearchFilesParams,- MoveLocalFilesParams,- RenameLocalFileParams,- RenameLocalFileResult,- RunCommandParams,- RunCommandResult,- WriteLocalFileParams,-} from '@lobechat/electron-client-ipc';-import { BuiltinServerRuntimeOutput } from '@lobechat/types';+import { LocalSystemExecutionRuntime as BaseLocalSystemExecutionRuntime } from '@lobechat/builtin-tool-local-system/executionRuntime';import { localFileService } from '@/services/electron/localFileService';-import {- EditLocalFileState,- GetCommandOutputState,- GlobFilesState,- GrepContentState,- KillCommandState,- LocalFileListState,- LocalFileSearchState,- LocalMoveFilesState,- LocalReadFileState,- LocalReadFilesState,- LocalRenameFileState,- RunCommandState,-} from '../type';--export class LocalSystemExecutionRuntime {- // ==================== File Operations ====================-- async listLocalFiles(args: ListLocalFileParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: LocalFileItem[] = await localFileService.listLocalFiles(args);-- const state: LocalFileListState = { listResults: result };-- return {- content: JSON.stringify(result),- state,- success: true,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async readLocalFile(args: LocalReadFileParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: LocalReadFileResult = await localFileService.readLocalFile(args);-- const state: LocalReadFileState = { fileContent: result };-- return {- content: JSON.stringify(result),- state,- success: true,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async readLocalFiles(args: LocalReadFilesParams): Promise<BuiltinServerRuntimeOutput> {- try {- const results: LocalReadFileResult[] = await localFileService.readLocalFiles(args);-- const state: LocalReadFilesState = { filesContent: results };-- return {- content: JSON.stringify(results),- state,- success: true,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async searchLocalFiles(args: LocalSearchFilesParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: LocalFileItem[] = await localFileService.searchLocalFiles(args);-- const state: LocalFileSearchState = { searchResults: result };-- return {- content: JSON.stringify(result),- state,- success: true,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async moveLocalFiles(args: MoveLocalFilesParams): Promise<BuiltinServerRuntimeOutput> {- try {- const results: LocalMoveFilesResultItem[] = await localFileService.moveLocalFiles(args);-- const allSucceeded = results.every((r) => r.success);- const someFailed = results.some((r) => !r.success);- const successCount = results.filter((r) => r.success).length;- const failedCount = results.length - successCount;-- let message = '';-- if (allSucceeded) {- message = `Successfully moved ${results.length} item(s).`;- } else if (someFailed) {- message = `Moved ${successCount} item(s) successfully. Failed to move ${failedCount} item(s).`;- } else {- message = `Failed to move all ${results.length} item(s).`;- }-- const state: LocalMoveFilesState = {- results,- successCount,- totalCount: results.length,- };-- return {- content: JSON.stringify({ message, results }),- state,- success: true,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async renameLocalFile(args: RenameLocalFileParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: RenameLocalFileResult = await localFileService.renameLocalFile(args);-- if (!result.success) {- const state: LocalRenameFileState = {- error: result.error,- newPath: '',- oldPath: args.path,- success: false,- };-- return {- content: JSON.stringify({ message: result.error, success: false }),- state,- success: false,- };- }-- const state: LocalRenameFileState = {- newPath: result.newPath!,- oldPath: args.path,- success: true,- };-- return {- content: JSON.stringify({- message: `Successfully renamed file ${args.path} to ${args.newName}.`,- success: true,- }),- state,- success: true,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async writeLocalFile(args: WriteLocalFileParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result = await localFileService.writeFile(args);-- if (!result.success) {- return {- content: JSON.stringify({- message: result.error || '写入文件失败',- success: false,- }),- error: result.error,- success: false,- };- }-- return {- content: JSON.stringify({- message: `成功写入文件 ${args.path}`,- success: true,- }),- success: true,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async editLocalFile(args: EditLocalFileParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: EditLocalFileResult = await localFileService.editLocalFile(args);-- if (!result.success) {- return {- content: `Edit failed: ${result.error}`,- success: false,- };- }-- const statsText =- result.linesAdded || result.linesDeleted- ? ` (+${result.linesAdded || 0} -${result.linesDeleted || 0})`- : '';- const message = `Successfully replaced ${result.replacements} occurrence(s) in ${args.file_path}${statsText}`;-- const state: EditLocalFileState = {- diffText: result.diffText,- linesAdded: result.linesAdded,- linesDeleted: result.linesDeleted,- replacements: result.replacements,- };-- return {- content: message,- state,- success: true,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- // ==================== Shell Commands ====================-- async runCommand(args: RunCommandParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: RunCommandResult = await localFileService.runCommand(args);-- let message: string;-- if (result.success) {- if (result.shell_id) {- message = `Command started in background with shell_id: ${result.shell_id}`;- } else {- message = `Command completed successfully.`;- }- } else {- message = `Command failed: ${result.error}`;- }-- const state: RunCommandState = { message, result };-- return {- content: JSON.stringify(result),- state,- success: result.success,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async getCommandOutput(args: GetCommandOutputParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: GetCommandOutputResult = await localFileService.getCommandOutput(args);-- const message = result.success- ? `Output retrieved. Running: ${result.running}`- : `Failed: ${result.error}`;-- const state: GetCommandOutputState = { message, result };-- return {- content: JSON.stringify(result),- state,- success: result.success,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async killCommand(args: KillCommandParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: KillCommandResult = await localFileService.killCommand(args);-- const message = result.success- ? `Successfully killed shell: ${args.shell_id}`- : `Failed to kill shell: ${result.error}`;-- const state: KillCommandState = { message, result };-- return {- content: JSON.stringify(result),- state,- success: result.success,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- // ==================== Search & Find ====================-- async grepContent(args: GrepContentParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: GrepContentResult = await localFileService.grepContent(args);-- const message = result.success- ? `Found ${result.total_matches} matches in ${result.matches.length} locations`- : 'Search failed';-- const state: GrepContentState = { message, result };-- return {- content: JSON.stringify(result),- state,- success: result.success,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }- }-- async globLocalFiles(args: GlobFilesParams): Promise<BuiltinServerRuntimeOutput> {- try {- const result: GlobFilesResult = await localFileService.globFiles(args);-- const message = result.success ? `Found ${result.total_files} files` : 'Glob search failed';-- const state: GlobFilesState = { message, result };-- return {- content: JSON.stringify(result),- state,- success: result.success,- };- } catch (error) {- return {- content: (error as Error).message,- error,- success: false,- };- }+export class LocalSystemExecutionRuntime extends BaseLocalSystemExecutionRuntime {+ constructor() {+ super(localFileService);}}diff --git a/src/tools/local-system/Intervention/EditLocalFile/index.tsx b/src/tools/local-system/Intervention/EditLocalFile/index.tsxindex d9e1a307f42..d6e92694cc3 100644--- a/src/tools/local-system/Intervention/EditLocalFile/index.tsx+++ b/src/tools/local-system/Intervention/EditLocalFile/index.tsx@@ -1,7 +1,7 @@import { EditLocalFileParams } from '@lobechat/electron-client-ipc';import { BuiltinInterventionProps } from '@lobechat/types';-import { Icon, Text } from '@lobehub/ui';-import { Skeleton } from 'antd';+import { Icon, Skeleton, Text } from '@lobehub/ui';+import { useThemeMode } from 'antd-style';import { createPatch } from 'diff';import { ChevronRight } from 'lucide-react';import path from 'path-browserify-esm';@@ -14,6 +14,7 @@ import useSWR from 'swr';import { LocalFile, LocalFolder } from '@/features/LocalFile';import { localFileService } from '@/services/electron/localFileService';+import '@/styles/react-diff-view.dark.css';const EditLocalFile = memo<BuiltinInterventionProps<EditLocalFileParams>>(({ args }) => {const { t } = useTranslation('tool');@@ -29,6 +30,7 @@ const EditLocalFile = memo<BuiltinInterventionProps<EditLocalFileParams>>(({ arg},);+ const { isDarkMode } = useThemeMode();// Generate diff from full file contentconst files = useMemo(() => {if (!fileData?.content) return [];@@ -73,7 +75,12 @@ const EditLocalFile = memo<BuiltinInterventionProps<EditLocalFileParams>>(({ arg</Text>{files.map((file, index) => (<div key={`${file.oldPath}-${index}`} style={{ fontSize: '12px' }}>- <Diff diffType={file.type} hunks={file.hunks} viewType="split">+ <Diff+ data-theme={isDarkMode ? 'dark' : 'light'}+ diffType={file.type}+ hunks={file.hunks}+ viewType="split"+ >{(hunks) => hunks.map((hunk) => <Hunk hunk={hunk} key={hunk.content} />)}</Diff></div>diff --git a/src/tools/local-system/Intervention/index.ts b/src/tools/local-system/Intervention/index.tsindex 28183923f4c..783197bfc67 100644--- a/src/tools/local-system/Intervention/index.ts+++ b/src/tools/local-system/Intervention/index.ts@@ -1,4 +1,5 @@-import { LocalSystemApiName } from '../index';+import { LocalSystemApiName } from '@lobechat/builtin-tool-local-system';+import EditLocalFile from './EditLocalFile';import MoveLocalFiles from './MoveLocalFiles';import RunCommand from './RunCommand';diff --git a/src/tools/local-system/Placeholder/ListFiles.tsx b/src/tools/local-system/Placeholder/ListFiles.tsxindex bb7519f0c82..8ab8732ec12 100644--- a/src/tools/local-system/Placeholder/ListFiles.tsx+++ b/src/tools/local-system/Placeholder/ListFiles.tsx@@ -1,6 +1,6 @@import { ListLocalFileParams } from '@lobechat/electron-client-ipc';import { BuiltinPlaceholderProps } from '@lobechat/types';-import { Skeleton } from 'antd';+import { Skeleton } from '@lobehub/ui';import React, { memo } from 'react';import { Center, Flexbox } from 'react-layout-kit';diff --git a/src/tools/local-system/Placeholder/SearchFiles.tsx b/src/tools/local-system/Placeholder/SearchFiles.tsxindex 2fec7d988b1..ec84908f3ef 100644--- a/src/tools/local-system/Placeholder/SearchFiles.tsx+++ b/src/tools/local-system/Placeholder/SearchFiles.tsx@@ -1,7 +1,6 @@import { LocalSearchFilesParams } from '@lobechat/electron-client-ipc';import { BuiltinPlaceholderProps } from '@lobechat/types';-import { Icon } from '@lobehub/ui';-import { Skeleton } from 'antd';+import { Icon, Skeleton } from '@lobehub/ui';import { createStyles } from 'antd-style';import { SearchIcon } from 'lucide-react';import React, { memo } from 'react';@@ -33,11 +32,11 @@ const SearchFiles = memo<BuiltinPlaceholderProps<LocalSearchFilesParams>>(({ arg{args.keywords ? (args.keywords) : (- <Skeleton.Node active style={{ height: 20, width: 40 }} />+ <Skeleton.Block active style={{ height: 20, width: 40 }} />)}</Flexbox>- <Skeleton.Node active style={{ height: 20, width: 40 }} />+ <Skeleton.Block active style={{ height: 20, width: 40 }} /></Flexbox><Center height={140}><Flexbox gap={4} width={'90%'}>diff --git a/src/tools/local-system/Render/EditLocalFile/index.tsx b/src/tools/local-system/Render/EditLocalFile/index.tsxindex 5c96d04e9ad..3735ece8e12 100644--- a/src/tools/local-system/Render/EditLocalFile/index.tsx+++ b/src/tools/local-system/Render/EditLocalFile/index.tsx@@ -1,7 +1,8 @@+import { EditLocalFileState } from '@lobechat/builtin-tool-local-system';import { EditLocalFileParams } from '@lobechat/electron-client-ipc';import { BuiltinRenderProps } from '@lobechat/types';-import { Alert, Icon } from '@lobehub/ui';-import { Skeleton } from 'antd';+import { Alert, Icon, Skeleton } from '@lobehub/ui';+import { useThemeMode } from 'antd-style';import { ChevronRight } from 'lucide-react';import path from 'path-browserify-esm';import React, { memo, useMemo } from 'react';@@ -10,8 +11,7 @@ import 'react-diff-view/style/index.css';import { Flexbox } from 'react-layout-kit';import { LocalFile, LocalFolder } from '@/features/LocalFile';--import { EditLocalFileState } from '../../type';+import '@/styles/react-diff-view.dark.css';const EditLocalFile = memo<BuiltinRenderProps<EditLocalFileParams, EditLocalFileState>>(({ args, pluginState, pluginError }) => {@@ -29,6 +29,7 @@ const EditLocalFile = memo<BuiltinRenderProps<EditLocalFileParams, EditLocalFilereturn [];}}, [pluginState?.diffText]);+ const { isDarkMode } = useThemeMode();if (!args) return <Skeleton active />;@@ -47,7 +48,7 @@ const EditLocalFile = memo<BuiltinRenderProps<EditLocalFileParams, EditLocalFiletype="error"/>) : (- <Flexbox gap={12}>+ <Flexbox data-theme={isDarkMode ? 'dark' : 'light'} gap={12}>{files.map((file, index) => (<div key={`${file.oldPath}-${index}`} style={{ fontSize: '12px' }}><Diff diffType={file.type} gutterType="default" hunks={file.hunks} viewType="split">diff --git a/src/tools/local-system/Render/ListFiles/Result.tsx b/src/tools/local-system/Render/ListFiles/Result.tsxindex 54dc039e3f8..13ef31a3f60 100644--- a/src/tools/local-system/Render/ListFiles/Result.tsx+++ b/src/tools/local-system/Render/ListFiles/Result.tsx@@ -1,6 +1,6 @@import { LocalFileItem } from '@lobechat/electron-client-ipc';import { ChatMessagePluginError } from '@lobechat/types';-import { Skeleton } from 'antd';+import { Skeleton } from '@lobehub/ui';import { memo } from 'react';import { Flexbox } from 'react-layout-kit';diff --git a/src/tools/local-system/Render/ListFiles/index.tsx b/src/tools/local-system/Render/ListFiles/index.tsxindex 34b44ba6de1..33c54dc8e5a 100644--- a/src/tools/local-system/Render/ListFiles/index.tsx+++ b/src/tools/local-system/Render/ListFiles/index.tsx@@ -1,10 +1,10 @@+import { LocalFileListState } from '@lobechat/builtin-tool-local-system';import { ListLocalFileParams } from '@lobechat/electron-client-ipc';import { BuiltinRenderProps } from '@lobechat/types';import React, { memo } from 'react';import { LocalFolder } from '@/features/LocalFile';-import { LocalFileListState } from '../../type';import SearchResult from './Result';const ListFiles = memo<BuiltinRenderProps<ListLocalFileParams, LocalFileListState>>(diff --git a/src/tools/local-system/Render/ReadLocalFile/ReadFileSkeleton.tsx b/src/tools/local-system/Render/ReadLocalFile/ReadFileSkeleton.tsxindex 23462968247..d66bfa3e688 100644--- a/src/tools/local-system/Render/ReadLocalFile/ReadFileSkeleton.tsx+++ b/src/tools/local-system/Render/ReadLocalFile/ReadFileSkeleton.tsx@@ -1,4 +1,4 @@-import { Skeleton } from 'antd';+import { Skeleton } from '@lobehub/ui';import { createStyles } from 'antd-style';import React, { memo } from 'react';import { Flexbox } from 'react-layout-kit';@@ -22,17 +22,17 @@ const ReadFileSkeleton = memo(() => {<Flexbox className={styles.container} gap={2}><Flexbox align={'center'} gap={24} horizontal justify={'space-between'}><Flexbox align={'center'} flex={1} gap={8} horizontal style={{ overflow: 'hidden' }}>- <Skeleton.Node active style={{ flex: 1, height: 16, width: 20 }} />+ <Skeleton.Block active style={{ flex: 1, height: 16, width: 20 }} />- <Skeleton.Node active style={{ flex: 1, height: 16, minWidth: 100 }} />+ <Skeleton.Block active style={{ flex: 1, height: 16, minWidth: 100 }} /></Flexbox><Flexbox align={'center'} className={styles.meta} gap={16}>- <Skeleton.Node active style={{ height: 16, maxWidth: 40 }} />+ <Skeleton.Block active style={{ height: 16, maxWidth: 40 }} /></Flexbox></Flexbox>{/* Path */}- <Skeleton.Node active style={{ height: 16, width: '100%' }} />+ <Skeleton.Block active style={{ height: 16, width: '100%' }} /></Flexbox>);});diff --git a/src/tools/local-system/Render/ReadLocalFile/index.tsx b/src/tools/local-system/Render/ReadLocalFile/index.tsxindex e3a24416e1e..3698bea596d 100644--- a/src/tools/local-system/Render/ReadLocalFile/index.tsx+++ b/src/tools/local-system/Render/ReadLocalFile/index.tsx@@ -1,10 +1,10 @@+import type { LocalReadFileState } from '@lobechat/builtin-tool-local-system';import { LocalReadFileParams } from '@lobechat/electron-client-ipc';import { ChatMessagePluginError } from '@lobechat/types';import { memo } from 'react';import { useChatStore } from '@/store/chat';import { chatToolSelectors } from '@/store/chat/slices/builtinTool/selectors';-import { LocalReadFileState } from '@/tools/local-system/type';import ReadFileSkeleton from './ReadFileSkeleton';import ReadFileView from './ReadFileView';diff --git a/src/tools/local-system/Render/RenameLocalFile/index.tsx b/src/tools/local-system/Render/RenameLocalFile/index.tsxindex 5d84c4bab46..88c930172e0 100644--- a/src/tools/local-system/Render/RenameLocalFile/index.tsx+++ b/src/tools/local-system/Render/RenameLocalFile/index.tsx@@ -1,3 +1,4 @@+import type { LocalReadFileState } from '@lobechat/builtin-tool-local-system';import { RenameLocalFileParams } from '@lobechat/electron-client-ipc';import { BuiltinRenderProps } from '@lobechat/types';import { Icon } from '@lobehub/ui';@@ -8,7 +9,6 @@ import React, { memo } from 'react';import { Flexbox } from 'react-layout-kit';import { LocalFile } from '@/features/LocalFile';-import { LocalReadFileState } from '@/tools/local-system/type';const useStyles = createStyles(({ css, token }) => ({container: css`diff --git a/src/tools/local-system/Render/SearchFiles/Result.tsx b/src/tools/local-system/Render/SearchFiles/Result.tsxindex c88da7ffcd7..43089d21ab5 100644--- a/src/tools/local-system/Render/SearchFiles/Result.tsx+++ b/src/tools/local-system/Render/SearchFiles/Result.tsx@@ -1,5 +1,6 @@+import { FileResult } from '@lobechat/builtin-tool-local-system';import { ChatMessagePluginError } from '@lobechat/types';-import { Skeleton } from 'antd';+import { Skeleton } from '@lobehub/ui';import { memo } from 'react';import { Flexbox } from 'react-layout-kit';@@ -7,7 +8,6 @@ import { useChatStore } from '@/store/chat';import { chatToolSelectors } from '@/store/chat/selectors';import FileItem from '../../components/FileItem';-import { FileResult } from '../../type';interface SearchFilesProps {messageId: string;diff --git a/src/tools/local-system/Render/SearchFiles/SearchQuery/index.tsx b/src/tools/local-system/Render/SearchFiles/SearchQuery/index.tsxindex 0ef4e5cff2d..324f7d9e2ff 100644--- a/src/tools/local-system/Render/SearchFiles/SearchQuery/index.tsx+++ b/src/tools/local-system/Render/SearchFiles/SearchQuery/index.tsx@@ -1,3 +1,4 @@+import type { LocalFileSearchState } from '@lobechat/builtin-tool-local-system';import { LocalSearchFilesParams } from '@lobechat/electron-client-ipc';import { ActionIcon, Button, Icon, SearchBar } from '@lobehub/ui';import { SearchIcon, XIcon } from 'lucide-react';@@ -7,7 +8,6 @@ import { Flexbox } from 'react-layout-kit';import { useChatStore } from '@/store/chat';import { chatToolSelectors } from '@/store/chat/selectors';-import { LocalFileSearchState } from '@/tools/local-system/type';import SearchView from './SearchView';diff --git a/src/tools/local-system/Render/SearchFiles/index.tsx b/src/tools/local-system/Render/SearchFiles/index.tsxindex a587ceb67e8..ca4a2dfb30e 100644--- a/src/tools/local-system/Render/SearchFiles/index.tsx+++ b/src/tools/local-system/Render/SearchFiles/index.tsx@@ -1,10 +1,9 @@+import type { LocalFileSearchState } from '@lobechat/builtin-tool-local-system';import { LocalSearchFilesParams } from '@lobechat/electron-client-ipc';import { BuiltinRenderProps } from '@lobechat/types';import { memo } from 'react';import { Flexbox } from 'react-layout-kit';-import { LocalFileSearchState } from '@/tools/local-system/type';-import SearchResult from './Result';import SearchQuery from './SearchQuery';diff --git a/src/tools/local-system/Render/WriteFile/index.tsx b/src/tools/local-system/Render/WriteFile/index.tsxindex c4e3989eb9a..ed61bc03c1b 100644--- a/src/tools/local-system/Render/WriteFile/index.tsx+++ b/src/tools/local-system/Render/WriteFile/index.tsx@@ -1,7 +1,6 @@import { WriteLocalFileParams } from '@lobechat/electron-client-ipc';import { BuiltinRenderProps } from '@lobechat/types';-import { Icon } from '@lobehub/ui';-import { Skeleton } from 'antd';+import { Icon , Skeleton } from '@lobehub/ui';import { ChevronRight } from 'lucide-react';import path from 'path-browserify-esm';import { memo } from 'react';diff --git a/src/tools/local-system/Render/index.ts b/src/tools/local-system/Render/index.tsindex 4076cb4ba8a..a6cb6c90e3c 100644--- a/src/tools/local-system/Render/index.ts+++ b/src/tools/local-system/Render/index.ts@@ -1,4 +1,5 @@-import { LocalSystemApiName } from '../index';+import { LocalSystemApiName } from '@lobechat/builtin-tool-local-system';+import EditLocalFile from './EditLocalFile';import ListFiles from './ListFiles';import MoveLocalFiles from './MoveLocalFiles';diff --git a/src/tools/local-system/systemRole.ts b/src/tools/local-system/systemRole.tsindex 457bee776b1..8ee2669e42b 100644--- a/src/tools/local-system/systemRole.ts+++ b/src/tools/local-system/systemRole.ts@@ -1,134 +1 @@-export const systemPrompt = `You have a Local System tool with capabilities to interact with the user's local system. You can list directories, read file contents, search for files, move, and rename files/directories.--<user_context>-Here are some known locations and system details on the user's system. User is using the Operating System: {{platform}}({{arch}}). Use these paths when the user refers to these common locations by name (e.g., "my desktop", "downloads folder").-- Desktop: {{desktopPath}}-- Documents: {{documentsPath}}-- Downloads: {{downloadsPath}}-- Music: {{musicPath}}-- Pictures: {{picturesPath}}-- Videos: {{videosPath}}-- User Home: {{homePath}}-- App Data: {{userDataPath}} (Use this primarily for plugin-related data or configurations if needed, less for general user files)-</user_context>--<core_capabilities>-You have access to a set of tools to interact with the user's local file system:--**File Operations:**-1. **listLocalFiles**: Lists files and directories in a specified path.-2. **readLocalFile**: Reads the content of a specified file, optionally within a line range. You can read file types such as Word, Excel, PowerPoint, PDF, and plain text files.-3. **writeLocalFile**: Write content to a specific file, only support plain text file like \`.text\` or \`.md\`-4. **editLocalFile**: Performs exact string replacements in files. Must read the file first before editing.-5. **renameLocalFile**: Renames a single file or directory in its current location.-6. **moveLocalFiles**: Moves multiple files or directories. Can be used for renaming during the move.--**Shell Commands:**-7. **runCommand**: Execute shell commands with timeout control. Supports both synchronous and background execution. When providing a description, always use the same language as the user's input.-8. **getCommandOutput**: Retrieve output from running background commands. Returns only new output since last check.-9. **killCommand**: Terminate a running background shell command by its ID.--**Search & Find:**-10. **searchLocalFiles**: Searches for files based on keywords and other criteria using Spotlight (macOS) or native search. Use this tool to find files if the user is unsure about the exact path.-11. **grepContent**: Search for content within files using regex patterns. Supports various output modes, filtering, and context lines.-12. **globLocalFiles**: Find files matching glob patterns (e.g., "**/*.js", "*.{ts,tsx}").-</core_capabilities>--<workflow>-1. Understand the user's request regarding local operations (files, commands, searches).-2. Select the appropriate tool:- - File operations: listLocalFiles, readLocalFile, writeLocalFile, editLocalFile, renameLocalFile, moveLocalFiles- - Shell commands: runCommand, getCommandOutput, killCommand- - Search/Find: searchLocalFiles, grepContent, globLocalFiles-3. Execute the operation. **If the user mentions a common location (like Desktop, Documents, Downloads, etc.) without providing a full path, use the corresponding path from the <user_context> section.**-4. Present the results or confirmation.-</workflow>--<tool_usage_guidelines>-- For listing directory contents: Use 'listFiles' with the target directory path.-- For reading a file: Use 'readFile'. Provide the following parameters:- - 'path': The exact file path.- - 'loc' (Optional): A two-element array [startLine, endLine] to specify a line range to read (e.g., '[301, 400]' reads lines 301 to 400).- - If 'loc' is omitted, it defaults to reading the first 200 lines ('[0, 200]').- - To read the entire file: First call 'readFile' (potentially without 'loc'). The response includes 'totalLineCount'. Then, call 'readFile' again with 'loc: [0, totalLineCount]' to get the full content.-- For searching files: Use 'searchFiles' with the 'query' parameter (search string). You can optionally add the following filter parameters to narrow down the search:- - 'contentContains': Find files whose content includes specific text.- - 'createdAfter' / 'createdBefore': Filter by creation date.- - 'modifiedAfter' / 'modifiedBefore': Filter by modification date.- - 'fileTypes': Filter by file type (e.g., "public.image", "txt").- - 'onlyIn': Limit the search to a specific directory.- - 'exclude': Exclude specific files or directories.- - 'limit': Limit the number of results returned.- - 'sortBy' / 'sortDirection': Sort the results.-- For renaming a file/folder in place: Use 'renameFile'. Provide the following parameters:- - 'path': The current full path of the file or folder.- - 'newName': The desired new name (without path components).-- For moving multiple files/folders (and optionally renaming them): Use 'moveLocalFiles'. Provide the following parameter:- - 'items': An array of objects, where each object represents a move operation and must contain:- - 'oldPath': The current absolute path of the file/directory to move or rename.- - 'newPath': The target absolute path for the file/directory (can include a new name).- Example: items: [{ oldPath: "/path/to/file1.txt", newPath: "/new/path/to/fileA.txt" }, { oldPath: "/path/to/folderB", newPath: "/archive/folderB_renamed" }]-- For writing to a file: Use 'writeLocalFile' with the file path and the content to be written. Be cautious as this might overwrite existing files.-- For editing a file: Use 'editLocalFile'. Provide the following parameters:- - 'file_path': The absolute path to the file to modify.- - 'old_string': The exact text to replace.- - 'new_string': The text to replace with.- - 'replace_all' (Optional): Set to true to replace all occurrences (default: false, replaces only first occurrence).- Note: You MUST read the file first using 'readLocalFile' before editing to verify the content.-- For executing shell commands: Use 'runCommand'. Provide the following parameters:- - 'command': The shell command to execute.- - 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.- - 'run_in_background' (Optional): Set to true to run in background and get a shell_id for later checking output.- - 'timeout' (Optional): Timeout in milliseconds (default: 120000ms, max: 600000ms).- The command runs in cmd.exe on Windows or /bin/sh on macOS/Linux.-- For retrieving output from background commands: Use 'getCommandOutput'. Provide:- - 'shell_id': The ID returned from runCommand when run_in_background was true.- - 'filter' (Optional): A regex pattern to filter output lines.- Returns only new output since the last check.-- For killing background commands: Use 'killCommand' with 'shell_id'.-- For searching content in files: Use 'grepContent'. Provide:- - 'pattern': The regex pattern to search for.- - 'path' (Optional): File or directory to search (defaults to current working directory).- - 'output_mode' (Optional): "content" (matching lines), "files_with_matches" (file paths, default), "count" (match counts).- - 'glob' (Optional): Glob pattern to filter files (e.g., "*.js", "*.{ts,tsx}").- - '-i' (Optional): Case insensitive search.- - '-n' (Optional): Show line numbers (requires output_mode: "content").- - '-A/-B/-C' (Optional): Show N lines after/before/around matches (requires output_mode: "content").- - 'head_limit' (Optional): Limit results to first N matches.-- For finding files by pattern: Use 'globLocalFiles'. Provide:- - 'pattern': Glob pattern (e.g., "**/*.js", "src/**/*.ts").- - 'path' (Optional): Directory to search in (defaults to current working directory).- Returns files sorted by modification time (most recent first).-</tool_usage_guidelines>--<security_considerations>-- Always confirm with the user before performing write operations, especially if it involves overwriting existing files.-- Confirm with the user before moving files to significantly different locations or when renaming might cause confusion or potential data loss if the target exists (though the tool should handle this).-- Do not attempt to access files outside the user's designated workspace or allowed directories unless explicitly permitted.-- Handle file paths carefully to avoid unintended access or errors.-- When running shell commands:- - Never execute commands that could harm the system or delete important data without explicit user confirmation.- - Be cautious with commands that have side effects (e.g., rm, sudo, format).- - Always describe what a command will do before running it, especially for non-trivial operations.- - Always provide a clear 'description' parameter in the user's language to help them understand what the command does.- - Use appropriate timeouts to prevent commands from running indefinitely.-- When editing files:- - Always read the file first to verify its current content.- - Ensure old_string exactly matches the text to be replaced to avoid unintended changes.- - Be cautious when using replace_all option.-</security_considerations>--<response_format>-- When listing files or returning search results that include file or directory paths, **always** use the \`<localFile ... />\` tag format. **Any reference to a local file or directory path in your response MUST be enclosed within this tag.** Do not output raw file paths outside of this tag structure.-- For a file, use: \`<localFile name="[Filename]" path="[Full Unencoded Path]" />\`. Example: \`<localFile name="report.pdf" path="/Users/me/Documents/report.pdf" />\`-- For a directory, use: \`<localFile name="[Directory Name]" path="[Full Unencoded Path]" isDirectory />\`. Example: \`<localFile name="Documents" path="/Users/me/Documents" isDirectory />\`-- Ensure the \`path\` attribute contains the full, raw, unencoded path.-- Ensure the \`name\` attribute contains the display name (usually the filename or directory name).-- Include the \`isDirectory\` attribute **only** for directories.-- When listing files, provide a clear list using the tag format.-- When reading files, present the content accurately. **If you mention the file path being read, use the \`<localFile>\` tag.**-- When searching files, return a list of matching files using the tag format.-- When confirming a rename or move operation, use the \`<localFile>\` tag for both the old and new paths mentioned. Example: \`Successfully renamed <localFile name="oldName.txt" /> to <localFile name="newName.txt" path="/path/to/newName.txt" />.\`-- When writing files, confirm the success or failure. **If you mention the file path written to, use the \`<localFile>\` tag.**-</response_format>-`;+export { systemPrompt } from '@lobechat/builtin-tool-local-system';