Skip to content

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

✨ feat: code-interpreter tool

Shinji-Libaa29c882ba3
diff --git a/src/services/codeInterpreter.ts b/src/services/codeInterpreter.ts
new file mode 100644
index 00000000000..39b5800eee4
--- /dev/null
+++ b/src/services/codeInterpreter.ts
@@ -0,0 +1,75 @@
+import { toolsClient } from '@/libs/trpc/client';
+import type {
+ CallToolInput,
+ CallToolResult,
+ GetExportFileUploadUrlInput,
+ GetExportFileUploadUrlResult,
+ SaveExportedFileContentInput,
+ SaveExportedFileContentResult,
+} from '@/server/routers/tools/codeInterpreter';
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/slices/settings/selectors/settings';
+
+/**
+ * Get Market access token from user settings (stored by MarketAuthProvider)
+ */
+const getMarketAccessToken = (): string | undefined => {
+ const settings = settingsSelectors.currentSettings(useUserStore.getState());
+ return settings.market?.accessToken;
+};
+
+class CodeInterpreterService {
+ /**
+ * Call a cloud code interpreter tool
+ * @param toolName - The name of the tool to call (e.g., 'runCommand', 'writeLocalFile')
+ * @param params - The parameters for the tool
+ * @param context - Session context containing userId and topicId for isolation
+ */
+ async callTool(
+ toolName: string,
+ params: Record<string, any>,
+ context: { topicId: string; userId: string },
+ ): Promise<CallToolResult> {
+ const marketAccessToken = getMarketAccessToken();
+
+ const input: CallToolInput = {
+ marketAccessToken,
+ params,
+ toolName,
+ topicId: context.topicId,
+ userId: context.userId,
+ };
+
+ return toolsClient.codeInterpreter.callTool.mutate(input);
+ }
+
+ /**
+ * Get a pre-signed upload URL for exporting a file from the sandbox
+ * @param filename - The name of the file to export
+ * @param topicId - The topic ID for organizing files
+ */
+ async getExportFileUploadUrl(
+ filename: string,
+ topicId: string,
+ ): Promise<GetExportFileUploadUrlResult> {
+ const input: GetExportFileUploadUrlInput = {
+ filename,
+ topicId,
+ };
+
+ return toolsClient.codeInterpreter.getExportFileUploadUrl.mutate(input);
+ }
+
+ /**
+ * Save exported file content to documents table
+ * This creates a document record linked to the file for content retrieval
+ * @param params - File content and metadata
+ */
+ async saveExportedFileContent(
+ params: SaveExportedFileContentInput,
+ ): Promise<SaveExportedFileContentResult> {
+ return toolsClient.codeInterpreter.saveExportedFileContent.mutate(params);
+ }
+}
+
+export const codeInterpreterService = new CodeInterpreterService();
diff --git a/src/store/urlHydration/action.ts b/src/store/urlHydration/action.ts
deleted file mode 100644
index b8666eec590..00000000000
--- a/src/store/urlHydration/action.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { StateCreator } from 'zustand/vanilla';
-
-import { useSessionStore } from '@/store/session';
-
-import type { UrlHydrationStore } from './store';
-
-export interface UrlHydrationAction {
- /**
- * Initialize store state from URL (one-time on app load)
- */
- initAgentPinnedFromUrl: () => void;
-
- /**
- * Sync agent pinned state to URL (call after state change)
- */
- syncAgentPinnedToUrl: () => void;
-}
-
-export const urlHydrationAction: StateCreator<
- UrlHydrationStore,
- [['zustand/devtools', never]],
- [],
- UrlHydrationAction
-> = (set, get) => ({
- initAgentPinnedFromUrl: () => {
- if (get().isAgentPinnedInitialized) return;
-
- if (typeof window !== 'undefined') {
- const params = new URLSearchParams(window.location.search);
- const pinnedParam = params.get('pinned');
-
- console.log('pinnedParam', pinnedParam);
-
- if (pinnedParam === 'true') {
- useSessionStore.setState({ isAgentPinned: true });
- }
-
- set({ isAgentPinnedInitialized: true });
- }
- },
-
- syncAgentPinnedToUrl: () => {
- if (typeof window === 'undefined') return;
-
- const isAgentPinned = useSessionStore.getState().isAgentPinned;
- const url = new URL(window.location.href);
-
- if (isAgentPinned) {
- url.searchParams.set('pinned', 'true');
- } else {
- url.searchParams.delete('pinned');
- }
-
- window.history.replaceState(null, '', `${url.pathname}${url.search}`);
- },
-});
diff --git a/src/store/urlHydration/index.ts b/src/store/urlHydration/index.ts
deleted file mode 100644
index ce0462fb3d1..00000000000
--- a/src/store/urlHydration/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { type UrlHydrationStore,useUrlHydrationStore } from './store';
diff --git a/src/store/urlHydration/initialState.ts b/src/store/urlHydration/initialState.ts
deleted file mode 100644
index 41f7d5fca06..00000000000
--- a/src/store/urlHydration/initialState.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * URL Hydration Store State
- *
- * Tracks initialization status to ensure one-time URL reading.
- */
-export interface UrlHydrationState {
- isAgentPinnedInitialized: boolean;
-}
-
-export const initialState: UrlHydrationState = {
- isAgentPinnedInitialized: false,
-};
diff --git a/src/store/urlHydration/store.ts b/src/store/urlHydration/store.ts
deleted file mode 100644
index 4a77be38ce6..00000000000
--- a/src/store/urlHydration/store.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { subscribeWithSelector } from 'zustand/middleware';
-import { shallow } from 'zustand/shallow';
-import { createWithEqualityFn } from 'zustand/traditional';
-import { StateCreator } from 'zustand/vanilla';
-
-import { createDevtools } from '../middleware/createDevtools';
-import { type UrlHydrationAction, urlHydrationAction } from './action';
-import { type UrlHydrationState, initialState } from './initialState';
-
-// =============== 聚合 createStoreFn ============ //
-
-export interface UrlHydrationStore extends UrlHydrationState, UrlHydrationAction {}
-
-const createStore: StateCreator<UrlHydrationStore, [['zustand/devtools', never]]> = (
- ...parameters
-) => ({
- ...initialState,
- ...urlHydrationAction(...parameters),
-});
-
-// =============== 实装 useStore ============ //
-
-const devtools = createDevtools('urlHydration');
-
-export const useUrlHydrationStore = createWithEqualityFn<UrlHydrationStore>()(
- subscribeWithSelector(devtools(createStore)),
- shallow,
-);
diff --git a/src/tools/code-interpreter/Render/components/ResultFileGallery.tsx b/src/tools/code-interpreter-draft/Render/components/ResultFileGallery.tsx
similarity index 100%
rename from src/tools/code-interpreter/Render/components/ResultFileGallery.tsx
rename to src/tools/code-interpreter-draft/Render/components/ResultFileGallery.tsx
diff --git a/src/tools/code-interpreter/Render/components/ResultFileItem.tsx b/src/tools/code-interpreter-draft/Render/components/ResultFileItem.tsx
similarity index 100%
rename from src/tools/code-interpreter/Render/components/ResultFileItem.tsx
rename to src/tools/code-interpreter-draft/Render/components/ResultFileItem.tsx
diff --git a/src/tools/code-interpreter/Render/index.tsx b/src/tools/code-interpreter-draft/Render/index.tsx
similarity index 100%
rename from src/tools/code-interpreter/Render/index.tsx
rename to src/tools/code-interpreter-draft/Render/index.tsx
diff --git a/src/tools/code-interpreter-draft/index.ts b/src/tools/code-interpreter-draft/index.ts
new file mode 100644
index 00000000000..c99480949be
--- /dev/null
+++ b/src/tools/code-interpreter-draft/index.ts
@@ -0,0 +1,67 @@
+import { BuiltinToolManifest } from '@lobechat/types';
+
+export const CodeInterpreterIdentifier = 'lobe-code-interpreter';
+
+export const CodeInterpreterManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description: 'A Python interpreter. Use this tool to run Python code. ',
+ name: 'python',
+ parameters: {
+ properties: {
+ code: {
+ description: 'The Python code to run.',
+ type: 'string',
+ },
+ packages: {
+ description: 'The packages to install before running the code.',
+ items: {
+ type: 'string',
+ },
+ type: 'array',
+ },
+ },
+ required: ['packages', 'code'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: CodeInterpreterIdentifier,
+ meta: {
+ avatar:
+ 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IS0tIFVwbG9hZGVkIHRvOiBTVkcgUmVwbywgd3d3LnN2Z3JlcG8uY29tLCBHZW5lcmF0b3I6IFNWRyBSZXBvIE1peGVyIFRvb2xzIC0tPgo8c3ZnIHdpZHRoPSI4MDBweCIgaGVpZ2h0PSI4MDBweCIgdmlld0JveD0iMCAwIDMyIDMyIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPg0KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMy4wMTY0IDJDMTAuODE5MyAyIDkuMDM4MjUgMy43MjQ1MyA5LjAzODI1IDUuODUxODVWOC41MTg1MkgxNS45MjM1VjkuMjU5MjZINS45NzgxNEMzLjc4MTA3IDkuMjU5MjYgMiAxMC45ODM4IDIgMTMuMTExMUwyIDE4Ljg4ODlDMiAyMS4wMTYyIDMuNzgxMDcgMjIuNzQwNyA1Ljk3ODE0IDIyLjc0MDdIOC4yNzMyMlYxOS40ODE1QzguMjczMjIgMTcuMzU0MiAxMC4wNTQzIDE1LjYyOTYgMTIuMjUxNCAxNS42Mjk2SDE5LjU5NTZDMjEuNDU0NyAxNS42Mjk2IDIyLjk2MTcgMTQuMTcwNCAyMi45NjE3IDEyLjM3MDRWNS44NTE4NUMyMi45NjE3IDMuNzI0NTMgMjEuMTgwNyAyIDE4Ljk4MzYgMkgxMy4wMTY0Wk0xMi4wOTg0IDYuNzQwNzRDMTIuODU4OSA2Ljc0MDc0IDEzLjQ3NTQgNi4xNDM3OCAxMy40NzU0IDUuNDA3NDFDMTMuNDc1NCA0LjY3MTAzIDEyLjg1ODkgNC4wNzQwNyAxMi4wOTg0IDQuMDc0MDdDMTEuMzM3OCA0LjA3NDA3IDEwLjcyMTMgNC42NzEwMyAxMC43MjEzIDUuNDA3NDFDMTAuNzIxMyA2LjE0Mzc4IDExLjMzNzggNi43NDA3NCAxMi4wOTg0IDYuNzQwNzRaIiBmaWxsPSJ1cmwoI3BhaW50MF9saW5lYXJfODdfODIwNCkiLz4NCjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMTguOTgzNCAzMEMyMS4xODA1IDMwIDIyLjk2MTYgMjguMjc1NSAyMi45NjE2IDI2LjE0ODJWMjMuNDgxNUwxNi4wNzYzIDIzLjQ4MTVMMTYuMDc2MyAyMi43NDA4TDI2LjAyMTcgMjIuNzQwOEMyOC4yMTg4IDIyLjc0MDggMjkuOTk5OCAyMS4wMTYyIDI5Ljk5OTggMTguODg4OVYxMy4xMTExQzI5Ljk5OTggMTAuOTgzOCAyOC4yMTg4IDkuMjU5MjggMjYuMDIxNyA5LjI1OTI4TDIzLjcyNjYgOS4yNTkyOFYxMi41MTg1QzIzLjcyNjYgMTQuNjQ1OSAyMS45NDU1IDE2LjM3MDQgMTkuNzQ4NSAxNi4zNzA0TDEyLjQwNDIgMTYuMzcwNEMxMC41NDUxIDE2LjM3MDQgOS4wMzgwOSAxNy44Mjk2IDkuMDM4MDkgMTkuNjI5Nkw5LjAzODA5IDI2LjE0ODJDOS4wMzgwOSAyOC4yNzU1IDEwLjgxOTIgMzAgMTMuMDE2MiAzMEgxOC45ODM0Wk0xOS45MDE1IDI1LjI1OTNDMTkuMTQwOSAyNS4yNTkzIDE4LjUyNDQgMjUuODU2MiAxOC41MjQ0IDI2LjU5MjZDMTguNTI0NCAyNy4zMjkgMTkuMTQwOSAyNy45MjU5IDE5LjkwMTUgMjcuOTI1OUMyMC42NjIgMjcuOTI1OSAyMS4yNzg1IDI3LjMyOSAyMS4yNzg1IDI2LjU5MjZDMjEuMjc4NSAyNS44NTYyIDIwLjY2MiAyNS4yNTkzIDE5LjkwMTUgMjUuMjU5M1oiIGZpbGw9InVybCgjcGFpbnQxX2xpbmVhcl84N184MjA0KSIvPg0KPGRlZnM+DQo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfODdfODIwNCIgeDE9IjEyLjQ4MDkiIHkxPSIyIiB4Mj0iMTIuNDgwOSIgeTI9IjIyLjc0MDciIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4NCjxzdG9wIHN0b3AtY29sb3I9IiMzMjdFQkQiLz4NCjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzE1NjVBNyIvPg0KPC9saW5lYXJHcmFkaWVudD4NCjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQxX2xpbmVhcl84N184MjA0IiB4MT0iMTkuNTE5IiB5MT0iOS4yNTkyOCIgeDI9IjE5LjUxOSIgeTI9IjMwIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+DQo8c3RvcCBzdG9wLWNvbG9yPSIjRkZEQTRCIi8+DQo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNGOUM2MDAiLz4NCjwvbGluZWFyR3JhZGllbnQ+DQo8L2RlZnM+DQo8L3N2Zz4=',
+ title: 'Code Interpreter',
+ },
+ systemRole: `When you send a message containing Python code to python, it will be executed in a temporary pyodide python environment in browser.
+python will respond with the output of the execution or time out after 60.0 seconds.
+The drive at '/mnt/data' can be used to save and persist user files.
+
+If you are using matplotlib:
+- never use seaborn
+- give each chart its own distinct plot (no subplots)
+- never set any specific colors – unless explicitly asked to by the user
+
+If you are accessing the internet, You MUST use pyfetch from pyodide.http package. Any other methods of accessing the internet will fail.
+pyfetch is a wrapper of js fetch API, it is a async function that returns a pyodide.http.FetchResponse object.
+Here are some useful methods of FetchResponse:
+ - async bytes(): returns a bytes object
+ - async text(): returns a string
+ - async json(): returns a json object
+
+If you are generating files:
+- You MUST use the instructed library for each supported file format. (Do not assume any other libraries are available):
+ - pdf --> reportlab
+ - docx --> python-docx
+ - xlsx --> openpyxl
+ - pptx --> python-pptx
+ - csv --> pandas
+ - ods --> odfpy
+ - odt --> odfpy
+ - odp --> odfpy
+- None of the above packages are installed by default. You MUST include them in the packages parameter to install them EVERY TIME.
+- If you are generating a pdf
+ - You MUST prioritize generating text content using reportlab.platypus rather than canvas
+ - If you are generating text in Chinese, you MUST use STSong. To use the font, you must call pdfmetrics.registerFont(TTFont('STSong', 'STSong.ttf')) and apply the style to all text elements
+ `,
+ type: 'builtin',
+};
diff --git a/src/tools/code-interpreter/ExecutionRuntime/index.ts b/src/tools/code-interpreter/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..ce011b0d8de
--- /dev/null
+++ b/src/tools/code-interpreter/ExecutionRuntime/index.ts
@@ -0,0 +1,520 @@
+import { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import { codeInterpreterService } from '@/services/codeInterpreter';
+
+import {
+ EditLocalFileState,
+ ExecuteCodeState,
+ ExportFileState,
+ GetCommandOutputState,
+ GlobFilesState,
+ GrepContentState,
+ KillCommandState,
+ ListLocalFilesState,
+ MoveLocalFilesState,
+ ReadLocalFileState,
+ RenameLocalFileState,
+ RunCommandState,
+ SearchLocalFilesState,
+ WriteLocalFileState,
+} from '../type';
+
+/**
+ * Cloud Code Interpreter Execution Runtime
+ *
+ * This runtime executes tools via the LobeHub Market SDK's runBuildInTool API,
+ * which connects to AWS Bedrock AgentCore Code Interpreter sandbox.
+ *
+ * Session Management:
+ * - Sessions are automatically created per userId + topicId combination
+ * - Sessions are recreated automatically if expired
+ * - The sessionExpiredAndRecreated flag indicates if recreation occurred
+ */
+
+interface ExecutionContext {
+ topicId: string;
+ userId: string;
+}
+
+// Types for tool parameters matching market-sdk
+interface ListLocalFilesParams {
+ directoryPath: string;
+}
+
+interface ReadLocalFileParams {
+ endLine?: number;
+ path: string;
+ startLine?: number;
+}
+
+interface WriteLocalFileParams {
+ content: string;
+ createDirectories?: boolean;
+ path: string;
+}
+
+interface EditLocalFileParams {
+ all?: boolean;
+ path: string;
+ replace: string;
+ search: string;
+}
+
+interface SearchLocalFilesParams {
+ directory: string;
+ fileType?: string;
+ keyword?: string;
+ modifiedAfter?: string;
+ modifiedBefore?: string;
+}
+
+interface MoveLocalFilesParams {
+ operations: Array<{
+ destination: string;
+ source: string;
+ }>;
+}
+
+interface RenameLocalFileParams {
+ newName: string;
+ oldPath: string;
+}
+
+interface RunCommandParams {
+ background?: boolean;
+ command: string;
+ timeout?: number;
+}
+
+interface GetCommandOutputParams {
+ commandId: string;
+}
+
+interface KillCommandParams {
+ commandId: string;
+}
+
+interface GrepContentParams {
+ directory: string;
+ filePattern?: string;
+ pattern: string;
+ recursive?: boolean;
+}
+
+interface GlobLocalFilesParams {
+ directory?: string;
+ pattern: string;
+}
+
+interface ExportFileParams {
+ path: string;
+}
+
+interface ExecuteCodeParams {
+ code: string;
+ language?: 'javascript' | 'python' | 'typescript';
+}
+
+export class CodeInterpreterExecutionRuntime {
+ private context: ExecutionContext;
+
+ constructor(context: ExecutionContext) {
+ this.context = context;
+ }
+
+ // ==================== File Operations ====================
+
+ async listLocalFiles(args: ListLocalFilesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('listLocalFiles', args);
+
+ const state: ListLocalFilesState = {
+ files: result.result?.files || [],
+ };
+
+ return {
+ content: JSON.stringify(result.result),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ async readLocalFile(args: ReadLocalFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('readLocalFile', args);
+
+ const state: ReadLocalFileState = {
+ content: result.result?.content || '',
+ endLine: args.endLine,
+ path: args.path,
+ startLine: args.startLine,
+ totalLines: result.result?.totalLines,
+ };
+
+ return {
+ content: JSON.stringify(result.result),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ async writeLocalFile(args: WriteLocalFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('writeLocalFile', args);
+
+ const state: WriteLocalFileState = {
+ bytesWritten: result.result?.bytesWritten,
+ path: args.path,
+ success: result.success,
+ };
+
+ return {
+ content: JSON.stringify({
+ message: `Successfully wrote to ${args.path}`,
+ success: true,
+ }),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ async editLocalFile(args: EditLocalFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('editLocalFile', args);
+
+ const state: EditLocalFileState = {
+ diffText: result.result?.diffText,
+ linesAdded: result.result?.linesAdded,
+ linesDeleted: result.result?.linesDeleted,
+ path: args.path,
+ replacements: result.result?.replacements || 0,
+ };
+
+ const statsText =
+ state.linesAdded || state.linesDeleted
+ ? ` (+${state.linesAdded || 0} -${state.linesDeleted || 0})`
+ : '';
+
+ return {
+ content: `Successfully replaced ${state.replacements} occurrence(s) in ${args.path}${statsText}`,
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ async searchLocalFiles(args: SearchLocalFilesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('searchLocalFiles', args);
+
+ const state: SearchLocalFilesState = {
+ results: result.result?.results || [],
+ totalCount: result.result?.totalCount || 0,
+ };
+
+ return {
+ content: JSON.stringify(result.result),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ async moveLocalFiles(args: MoveLocalFilesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('moveLocalFiles', args);
+
+ const state: MoveLocalFilesState = {
+ results: result.result?.results || [],
+ successCount: result.result?.successCount || 0,
+ totalCount: args.operations.length,
+ };
+
+ return {
+ content: JSON.stringify({
+ message: `Moved ${state.successCount}/${state.totalCount} items`,
+ results: state.results,
+ }),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ async renameLocalFile(args: RenameLocalFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('renameLocalFile', args);
+
+ const state: RenameLocalFileState = {
+ error: result.result?.error,
+ newPath: result.result?.newPath || '',
+ oldPath: args.oldPath,
+ success: result.success,
+ };
+
+ return {
+ content: JSON.stringify({
+ message: `Successfully renamed ${args.oldPath} to ${args.newName}`,
+ success: true,
+ }),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ // ==================== Code Execution ====================
+
+ async executeCode(args: ExecuteCodeParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const language = args.language || 'python';
+ const result = await this.callTool('executeCode', {
+ code: args.code,
+ language,
+ });
+
+ const state: ExecuteCodeState = {
+ error: result.result?.error,
+ exitCode: result.result?.exitCode,
+ language,
+ output: result.result?.output,
+ stderr: result.result?.stderr,
+ success: result.success,
+ };
+
+ return {
+ content: JSON.stringify(result.result),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ // ==================== Shell Commands ====================
+
+ async runCommand(args: RunCommandParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('runCommand', args);
+
+ const state: RunCommandState = {
+ commandId: result.result?.commandId,
+ error: result.result?.error,
+ exitCode: result.result?.exitCode,
+ isBackground: args.background || false,
+ output: result.result?.output,
+ stderr: result.result?.stderr,
+ success: result.success,
+ };
+
+ return {
+ content: JSON.stringify(result.result),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ async getCommandOutput(args: GetCommandOutputParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('getCommandOutput', args);
+
+ const state: GetCommandOutputState = {
+ error: result.result?.error,
+ newOutput: result.result?.newOutput,
+ running: result.result?.running ?? false,
+ success: result.success,
+ };
+
+ return {
+ content: JSON.stringify(result.result),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ async killCommand(args: KillCommandParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('killCommand', args);
+
+ const state: KillCommandState = {
+ commandId: args.commandId,
+ error: result.result?.error,
+ success: result.success,
+ };
+
+ return {
+ content: JSON.stringify({
+ message: `Successfully killed command: ${args.commandId}`,
+ success: true,
+ }),
+ state,
+ success: result.success,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ // ==================== Search & Find ====================
+
+ async grepContent(args: GrepContentParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('grepContent', args);
+
+ const state: GrepContentState = {
+ matches: result.result?.matches || [],
+ pattern: args.pattern,
+ totalMatches: result.result?.totalMatches || 0,
+ };
+
+ return {
+ content: JSON.stringify(result.result),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ async globLocalFiles(args: GlobLocalFilesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callTool('globLocalFiles', args);
+
+ const state: GlobFilesState = {
+ files: result.result?.files || [],
+ pattern: args.pattern,
+ totalCount: result.result?.totalCount || 0,
+ };
+
+ return {
+ content: JSON.stringify(result.result),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ // ==================== Export Operations ====================
+
+ /**
+ * Export a file from the sandbox to cloud storage
+ * 1. Get a pre-signed upload URL from our server
+ * 2. Call the sandbox to upload the file to that URL
+ * 3. Return the download URL to the user
+ */
+ async exportFile(args: ExportFileParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ // Extract filename from path
+ const filename = args.path.split('/').pop() || 'exported_file';
+
+ // Step 1: Get pre-signed upload URL from our server
+ const uploadUrlResult = await codeInterpreterService.getExportFileUploadUrl(
+ filename,
+ this.context.topicId,
+ );
+
+ if (!uploadUrlResult.success) {
+ throw new Error(uploadUrlResult.error?.message || 'Failed to get upload URL');
+ }
+
+ // Step 2: Call the sandbox's exportFile tool with the upload URL
+ // The sandbox will read the file and upload it to the pre-signed URL
+ const result = await this.callTool('exportFile', {
+ path: args.path,
+ uploadUrl: uploadUrlResult.uploadUrl,
+ });
+
+ // Check if the sandbox upload was successful
+ const uploadSuccess = result.success && result.result?.success !== false;
+ const fileSize = result.result?.size;
+ const mimeType = result.result?.mimeType;
+ const fileContent = result.result?.content;
+
+ const state: ExportFileState = {
+ content: fileContent,
+ downloadUrl: uploadSuccess ? uploadUrlResult.downloadUrl : '',
+ filename,
+ mimeType,
+ path: args.path,
+ size: fileSize,
+ success: uploadSuccess,
+ };
+ if (!uploadSuccess) {
+ return {
+ content: JSON.stringify({
+ error: result.result?.error || 'Failed to upload file from sandbox',
+ filename,
+ success: false,
+ }),
+ state,
+ success: false,
+ };
+ }
+
+ return {
+ content: `File exported successfully.\n\nFilename: ${filename}\nDownload URL: ${uploadUrlResult.downloadUrl}`,
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ // ==================== Helper Methods ====================
+
+ /**
+ * Call a tool via the market SDK through tRPC
+ * Routes through: ExecutionRuntime -> codeInterpreterService -> tRPC -> codeInterpreterRouter -> MarketSDK
+ */
+ private async callTool(
+ toolName: string,
+ params: Record<string, any>,
+ ): Promise<{ result: any; sessionExpiredAndRecreated?: boolean; success: boolean }> {
+ const result = await codeInterpreterService.callTool(toolName, params, this.context);
+
+ if (!result.success) {
+ throw new Error(
+ (result as any).error?.message || `Cloud Code Interpreter tool ${toolName} failed`,
+ );
+ }
+
+ return result;
+ }
+
+ private handleError(error: unknown): BuiltinServerRuntimeOutput {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ return {
+ content: errorMessage,
+ error,
+ success: false,
+ };
+ }
+}
diff --git a/src/tools/code-interpreter/Intervention/EditLocalFile/index.tsx b/src/tools/code-interpreter/Intervention/EditLocalFile/index.tsx
new file mode 100644
index 00000000000..b8c473ca8e3
--- /dev/null
+++ b/src/tools/code-interpreter/Intervention/EditLocalFile/index.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Highlighter, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface EditLocalFileParams {
+ all?: boolean;
+ path: string;
+ replace: string;
+ search: string;
+}
+
+const EditLocalFile = memo<BuiltinInterventionProps<EditLocalFileParams>>(({ args }) => {
+ const { path, search, replace, all } = args;
+
+ return (
+ <Flexbox gap={8}>
+ <Text>Edit file: {path} {all && '(replace all)'}</Text>
+ <Flexbox gap={4}>
+ <Text style={{ fontSize: 12 }} type={'secondary'}>Search:</Text>
+ <Highlighter language={'text'} showLanguage={false} style={{ padding: '4px 8px' }} variant={'outlined'} wrap>
+ {search}
+ </Highlighter>
+ </Flexbox>
+ <Flexbox gap={4}>
+ <Text style={{ fontSize: 12 }} type={'secondary'}>Replace with:</Text>
+ <Highlighter language={'text'} showLanguage={false} style={{ padding: '4px 8px' }} variant={'outlined'} wrap>
+ {replace}
+ </Highlighter>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default EditLocalFile;
diff --git a/src/tools/code-interpreter/Intervention/ExecuteCode/index.tsx b/src/tools/code-interpreter/Intervention/ExecuteCode/index.tsx
new file mode 100644
index 00000000000..295581c5ab4
--- /dev/null
+++ b/src/tools/code-interpreter/Intervention/ExecuteCode/index.tsx
@@ -0,0 +1,46 @@
+'use client';
+
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Highlighter, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface ExecuteCodeParams {
+ code: string;
+ language?: 'javascript' | 'python' | 'typescript';
+}
+
+const languageDisplayNames: Record<string, string> = {
+ javascript: 'JavaScript',
+ python: 'Python',
+ typescript: 'TypeScript',
+};
+
+const ExecuteCode = memo<BuiltinInterventionProps<ExecuteCodeParams>>(({ args }) => {
+ const { code, language = 'python' } = args;
+ const displayLanguage = languageDisplayNames[language] || language;
+
+ return (
+ <Flexbox gap={8}>
+ <Flexbox horizontal justify={'space-between'}>
+ <Text>Execute code in cloud sandbox</Text>
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ {displayLanguage}
+ </Text>
+ </Flexbox>
+ {code && (
+ <Highlighter
+ language={language}
+ showLanguage={false}
+ style={{ padding: '4px 8px' }}
+ variant={'outlined'}
+ wrap
+ >
+ {code}
+ </Highlighter>
+ )}
+ </Flexbox>
+ );
+});
+
+export default ExecuteCode;
diff --git a/src/tools/code-interpreter/Intervention/MoveLocalFiles/index.tsx b/src/tools/code-interpreter/Intervention/MoveLocalFiles/index.tsx
new file mode 100644
index 00000000000..2fcf077dc99
--- /dev/null
+++ b/src/tools/code-interpreter/Intervention/MoveLocalFiles/index.tsx
@@ -0,0 +1,41 @@
+'use client';
+
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { ArrowRight } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+const useStyles = createStyles(({ css, token }) => ({
+ path: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+}));
+
+interface MoveLocalFilesParams {
+ operations: Array<{ destination: string; source: string }>;
+}
+
+const MoveLocalFiles = memo<BuiltinInterventionProps<MoveLocalFilesParams>>(({ args }) => {
+ const { styles } = useStyles();
+ const { operations } = args;
+
+ return (
+ <Flexbox gap={8}>
+ <Text>Move {operations.length} item(s):</Text>
+ <Flexbox gap={4}>
+ {operations.map((op, i) => (
+ <Flexbox align={'center'} gap={8} horizontal key={i}>
+ <Text className={styles.path} ellipsis style={{ maxWidth: 200 }}>{op.source}</Text>
+ <ArrowRight size={12} />
+ <Text className={styles.path} ellipsis style={{ maxWidth: 200 }}>{op.destination}</Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default MoveLocalFiles;
diff --git a/src/tools/code-interpreter/Intervention/RunCommand/index.tsx b/src/tools/code-interpreter/Intervention/RunCommand/index.tsx
new file mode 100644
index 00000000000..a6e96ab1def
--- /dev/null
+++ b/src/tools/code-interpreter/Intervention/RunCommand/index.tsx
@@ -0,0 +1,50 @@
+'use client';
+
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Highlighter, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface RunCommandParams {
+ background?: boolean;
+ command: string;
+ timeout?: number;
+}
+
+const formatTimeout = (ms?: number) => {
+ if (!ms) return null;
+ const seconds = ms / 1000;
+ if (seconds >= 60) return `${(seconds / 60).toFixed(1)}min`;
+ if (seconds >= 1) return `${seconds.toFixed(1)}s`;
+ return `${ms}ms`;
+};
+
+const RunCommand = memo<BuiltinInterventionProps<RunCommandParams>>(({ args }) => {
+ const { command, timeout, background } = args;
+ return (
+ <Flexbox gap={8}>
+ <Flexbox horizontal justify={'space-between'}>
+ <Text>Execute command in cloud sandbox</Text>
+ <Flexbox gap={8} horizontal>
+ {background && (
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ background
+ </Text>
+ )}
+ {timeout && (
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ timeout: {formatTimeout(timeout)}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ {command && (
+ <Highlighter language={'sh'} showLanguage={false} style={{ padding: '4px 8px' }} variant={'outlined'} wrap>
+ {command}
+ </Highlighter>
+ )}
+ </Flexbox>
+ );
+});
+
+export default RunCommand;
diff --git a/src/tools/code-interpreter/Intervention/WriteFile/index.tsx b/src/tools/code-interpreter/Intervention/WriteFile/index.tsx
new file mode 100644
index 00000000000..7df6924e012
--- /dev/null
+++ b/src/tools/code-interpreter/Intervention/WriteFile/index.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Highlighter, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface WriteLocalFileParams {
+ content: string;
+ createDirectories?: boolean;
+ path: string;
+}
+
+const WriteFile = memo<BuiltinInterventionProps<WriteLocalFileParams>>(({ args }) => {
+ const { path, content } = args;
+ const preview = content.length > 500 ? content.slice(0, 500) + '\n...(truncated)' : content;
+
+ return (
+ <Flexbox gap={8}>
+ <Text>Write to file: {path}</Text>
+ <Highlighter language={'text'} showLanguage={false} style={{ maxHeight: 200, overflow: 'auto', padding: '4px 8px' }} variant={'outlined'} wrap>
+ {preview}
+ </Highlighter>
+ </Flexbox>
+ );
+});
+
+export default WriteFile;
diff --git a/src/tools/code-interpreter/Intervention/index.ts b/src/tools/code-interpreter/Intervention/index.ts
new file mode 100644
index 00000000000..f630e890712
--- /dev/null
+++ b/src/tools/code-interpreter/Intervention/index.ts
@@ -0,0 +1,17 @@
+import { CodeInterpreterApiName } from '../index';
+import EditLocalFile from './EditLocalFile';
+import ExecuteCode from './ExecuteCode';
+import MoveLocalFiles from './MoveLocalFiles';
+import RunCommand from './RunCommand';
+import WriteFile from './WriteFile';
+
+/**
+ * Cloud Code Interpreter Intervention Components Registry
+ */
+export const CodeInterpreterInterventions = {
+ [CodeInterpreterApiName.editLocalFile]: EditLocalFile,
+ [CodeInterpreterApiName.executeCode]: ExecuteCode,
+ [CodeInterpreterApiName.moveLocalFiles]: MoveLocalFiles,
+ [CodeInterpreterApiName.runCommand]: RunCommand,
+ [CodeInterpreterApiName.writeLocalFile]: WriteFile,
+};
diff --git a/src/tools/code-interpreter/Render/EditLocalFile/index.tsx b/src/tools/code-interpreter/Render/EditLocalFile/index.tsx
new file mode 100644
index 00000000000..0d8669bac4d
--- /dev/null
+++ b/src/tools/code-interpreter/Render/EditLocalFile/index.tsx
@@ -0,0 +1,116 @@
+'use client';
+
+import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
+import { BuiltinRenderProps } from '@lobechat/types';
+import { ActionIcon, Block, Highlighter, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { ChevronDown, ChevronUp } from 'lucide-react';
+import { memo, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { EditLocalFileState } from '../../type';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ header: css`
+ .action-icon {
+ opacity: 0;
+ transition: opacity 0.2s ease;
+ }
+
+ &:hover {
+ .action-icon {
+ opacity: 1;
+ }
+ }
+ `,
+ path: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ stats: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 11px;
+ `,
+ statusIcon: css`
+ font-size: 12px;
+ `,
+}));
+
+interface EditLocalFileParams {
+ all?: boolean;
+ path: string;
+ replace: string;
+ search: string;
+}
+
+const EditLocalFile = memo<BuiltinRenderProps<EditLocalFileParams, EditLocalFileState>>(
+ ({ args, pluginState }) => {
+ const { styles, theme } = useStyles();
+ const [expanded, setExpanded] = useState(false);
+ const isSuccess = pluginState && pluginState.replacements > 0;
+
+ const statsText =
+ pluginState?.linesAdded || pluginState?.linesDeleted
+ ? `+${pluginState.linesAdded || 0} -${pluginState.linesDeleted || 0}`
+ : '';
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {/* Header */}
+ <Flexbox align={'center'} className={styles.header} horizontal justify={'space-between'}>
+ <Flexbox align={'center'} gap={8} horizontal>
+ {pluginState === undefined ? null : isSuccess ? (
+ <CheckCircleFilled
+ className={styles.statusIcon}
+ style={{ color: theme.colorSuccess }}
+ />
+ ) : (
+ <CloseCircleFilled className={styles.statusIcon} style={{ color: theme.colorError }} />
+ )}
+ <Text className={styles.path}>
+ {pluginState?.replacements || 0} replacement(s) in {args.path}
+ </Text>
+ {statsText && (
+ <Text className={styles.stats} type={'secondary'}>
+ ({statsText})
+ </Text>
+ )}
+ </Flexbox>
+ {pluginState?.diffText && (
+ <ActionIcon
+ className={`action-icon`}
+ icon={expanded ? ChevronUp : ChevronDown}
+ onClick={() => setExpanded(!expanded)}
+ size={'small'}
+ style={{ opacity: expanded ? 1 : undefined }}
+ title={expanded ? 'Hide diff' : 'Show diff'}
+ />
+ )}
+ </Flexbox>
+
+ {/* Diff view */}
+ {expanded && pluginState?.diffText && (
+ <Block padding={0} variant={'outlined'}>
+ <Highlighter
+ language={'diff'}
+ showLanguage={false}
+ style={{ maxHeight: 300, overflow: 'auto' }}
+ variant={'borderless'}
+ wrap
+ >
+ {pluginState.diffText}
+ </Highlighter>
+ </Block>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+EditLocalFile.displayName = 'EditLocalFile';
+
+export default EditLocalFile;
diff --git a/src/tools/code-interpreter/Render/ExecuteCode/index.tsx b/src/tools/code-interpreter/Render/ExecuteCode/index.tsx
new file mode 100644
index 00000000000..a0df0cfc5de
--- /dev/null
+++ b/src/tools/code-interpreter/Render/ExecuteCode/index.tsx
@@ -0,0 +1,129 @@
+'use client';
+
+import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
+import { BuiltinRenderProps } from '@lobechat/types';
+import { ActionIcon, Block, Highlighter, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { ChevronDown, ChevronUp } from 'lucide-react';
+import { memo, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ExecuteCodeState } from '../../type';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ head: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ header: css`
+ .action-icon {
+ opacity: 0;
+ transition: opacity 0.2s ease;
+ }
+
+ &:hover {
+ .action-icon {
+ opacity: 1;
+ }
+ }
+ `,
+ statusIcon: css`
+ font-size: 12px;
+ `,
+}));
+
+interface ExecuteCodeParams {
+ code: string;
+ language?: 'javascript' | 'python' | 'typescript';
+}
+
+const languageDisplayNames: Record<string, string> = {
+ javascript: 'JavaScript',
+ python: 'Python',
+ typescript: 'TypeScript',
+};
+
+const ExecuteCode = memo<BuiltinRenderProps<ExecuteCodeParams, ExecuteCodeState>>(
+ ({ args, pluginState }) => {
+ const { styles, theme } = useStyles();
+ const isSuccess = pluginState?.success;
+ const [expanded, setExpanded] = useState(false);
+
+ const language = args.language || 'python';
+ const displayLanguage = languageDisplayNames[language] || language;
+
+ const statusMessage = pluginState?.success
+ ? 'Execution completed'
+ : pluginState?.error || 'Execution failed';
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {/* Header: Language + Status */}
+ <Flexbox align={'center'} className={styles.header} horizontal justify={'space-between'}>
+ <Flexbox gap={8} horizontal>
+ <Flexbox gap={4} horizontal>
+ {pluginState === undefined ? null : isSuccess ? (
+ <CheckCircleFilled
+ className={styles.statusIcon}
+ style={{ color: theme.colorSuccess }}
+ />
+ ) : (
+ <CloseCircleFilled
+ className={styles.statusIcon}
+ style={{ color: theme.colorError }}
+ />
+ )}
+ <Text className={styles.head}>{displayLanguage}</Text>
+ </Flexbox>
+ <Text className={styles.head} type={'secondary'}>
+ {statusMessage}
+ </Text>
+ </Flexbox>
+ <Flexbox align={'center'} gap={8} horizontal>
+ <ActionIcon
+ className={`action-icon`}
+ icon={expanded ? ChevronUp : ChevronDown}
+ onClick={() => setExpanded(!expanded)}
+ size={'small'}
+ style={{ opacity: expanded ? 1 : undefined }}
+ title={expanded ? 'Collapse' : 'Expand'}
+ />
+ </Flexbox>
+ </Flexbox>
+
+ {/* Code & Output */}
+ {expanded && (
+ <Block gap={8} padding={8} variant={'outlined'}>
+ <Highlighter
+ language={language}
+ showLanguage={false}
+ style={{ paddingInline: 8 }}
+ variant={'borderless'}
+ wrap
+ >
+ {args.code}
+ </Highlighter>
+ {pluginState?.output && (
+ <Highlighter language={'text'} showLanguage={false} variant={'filled'} wrap>
+ {pluginState.output}
+ </Highlighter>
+ )}
+ {pluginState?.stderr && (
+ <Highlighter language={'text'} showLanguage={false} variant={'filled'} wrap>
+ {pluginState.stderr}
+ </Highlighter>
+ )}
+ </Block>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+ExecuteCode.displayName = 'ExecuteCode';
+
+export default ExecuteCode;
diff --git a/src/tools/code-interpreter/Render/ExportFile/index.tsx b/src/tools/code-interpreter/Render/ExportFile/index.tsx
new file mode 100644
index 00000000000..431856bba7e
--- /dev/null
+++ b/src/tools/code-interpreter/Render/ExportFile/index.tsx
@@ -0,0 +1,92 @@
+'use client';
+
+import { CheckCircleFilled, CloseCircleFilled, DownloadOutlined } from '@ant-design/icons';
+import { BuiltinRenderProps } from '@lobechat/types';
+import { ActionIcon, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo, useCallback } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ExportFileState } from '../../type';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ filename: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ statusIcon: css`
+ font-size: 12px;
+ `,
+}));
+
+interface ExportFileParams {
+ path: string;
+}
+
+const ExportFile = memo<BuiltinRenderProps<ExportFileParams, ExportFileState>>(
+ ({ args, pluginState }) => {
+ const { styles, theme } = useStyles();
+ const isSuccess = pluginState?.success;
+
+ const handleDownload = useCallback(async () => {
+ if (!pluginState?.downloadUrl || !pluginState?.filename) return;
+
+ try {
+ // Fetch the file content to bypass cross-origin download restrictions
+ const response = await fetch(pluginState.downloadUrl);
+ const blob = await response.blob();
+
+ // Create a blob URL and trigger download
+ const blobUrl = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = blobUrl;
+ link.download = pluginState.filename;
+ document.body.append(link);
+ link.click();
+ link.remove();
+
+ // Clean up the blob URL
+ URL.revokeObjectURL(blobUrl);
+ } catch {
+ // Fallback: open in new tab if fetch fails
+ window.open(pluginState.downloadUrl, '_blank');
+ }
+ }, [pluginState?.downloadUrl, pluginState?.filename]);
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ <Flexbox align={'center'} gap={8} horizontal>
+ {pluginState === undefined ? null : isSuccess ? (
+ <CheckCircleFilled
+ className={styles.statusIcon}
+ style={{ color: theme.colorSuccess }}
+ />
+ ) : (
+ <CloseCircleFilled className={styles.statusIcon} style={{ color: theme.colorError }} />
+ )}
+ <Text className={styles.filename}>
+ {isSuccess
+ ? `Exported: ${pluginState?.filename || args.path}`
+ : `Failed to export ${args.path}`}
+ </Text>
+ {isSuccess && pluginState?.downloadUrl && (
+ <ActionIcon
+ icon={DownloadOutlined}
+ onClick={handleDownload}
+ size={'small'}
+ title="Download"
+ />
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+ExportFile.displayName = 'ExportFile';
+
+export default ExportFile;
diff --git a/src/tools/code-interpreter/Render/ListFiles/index.tsx b/src/tools/code-interpreter/Render/ListFiles/index.tsx
new file mode 100644
index 00000000000..b87350c7aab
--- /dev/null
+++ b/src/tools/code-interpreter/Render/ListFiles/index.tsx
@@ -0,0 +1,123 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Block, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { File, Folder } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ListLocalFilesState } from '../../type';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ fileIcon: css`
+ color: ${token.colorTextSecondary};
+ `,
+ fileItem: css`
+ cursor: default;
+ padding-block: 4px;
+ padding-inline: 8px;
+ border-radius: 4px;
+
+ &:hover {
+ background: ${token.colorFillTertiary};
+ }
+ `,
+ fileName: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ folderIcon: css`
+ color: ${token.colorWarning};
+ `,
+ path: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ size: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 11px;
+ color: ${token.colorTextTertiary};
+ `,
+}));
+
+interface ListLocalFilesParams {
+ directoryPath: string;
+}
+
+/**
+ * Format file size to human readable string
+ */
+const formatSize = (bytes?: number): string => {
+ if (bytes === undefined) return '';
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
+};
+
+const ListFiles = memo<BuiltinRenderProps<ListLocalFilesParams, ListLocalFilesState>>(
+ ({ args, pluginState }) => {
+ const { styles } = useStyles();
+
+ if (!pluginState?.files) {
+ return null;
+ }
+
+ // Sort: directories first, then files, both alphabetically
+ const sortedFiles = [...pluginState.files].sort((a, b) => {
+ if (a.isDirectory && !b.isDirectory) return -1;
+ if (!a.isDirectory && b.isDirectory) return 1;
+ return a.name.localeCompare(b.name);
+ });
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {/* Directory path */}
+ <Flexbox align={'center'} horizontal justify={'space-between'}>
+ <Text className={styles.path} ellipsis>
+ 📁 {args.directoryPath}
+ </Text>
+ <Text className={styles.size} type={'secondary'}>
+ {pluginState.files.length} items
+ </Text>
+ </Flexbox>
+
+ {/* File list */}
+ <Block padding={8} style={{ maxHeight: 300, overflow: 'auto' }} variant={'outlined'}>
+ <Flexbox gap={2}>
+ {sortedFiles.map((file, index) => (
+ <Flexbox
+ align={'center'}
+ className={styles.fileItem}
+ horizontal
+ justify={'space-between'}
+ key={index}
+ >
+ <Flexbox align={'center'} gap={8} horizontal>
+ {file.isDirectory ? (
+ <Folder className={styles.folderIcon} size={14} />
+ ) : (
+ <File className={styles.fileIcon} size={14} />
+ )}
+ <Text className={styles.fileName}>{file.name}</Text>
+ </Flexbox>
+ {!file.isDirectory && file.size !== undefined && (
+ <Text className={styles.size}>{formatSize(file.size)}</Text>
+ )}
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Block>
+ </Flexbox>
+ );
+ },
+);
+
+ListFiles.displayName = 'ListFiles';
+
+export default ListFiles;
diff --git a/src/tools/code-interpreter/Render/MoveLocalFiles/index.tsx b/src/tools/code-interpreter/Render/MoveLocalFiles/index.tsx
new file mode 100644
index 00000000000..25ca31b6df3
--- /dev/null
+++ b/src/tools/code-interpreter/Render/MoveLocalFiles/index.tsx
@@ -0,0 +1,114 @@
+'use client';
+
+import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Block, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { ArrowRight } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { MoveLocalFilesState } from '../../type';
+
+const useStyles = createStyles(({ css, token }) => ({
+ arrow: css`
+ color: ${token.colorTextSecondary};
+ `,
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ header: css`
+ font-size: 12px;
+ `,
+ moveItem: css`
+ padding-block: 4px;
+ padding-inline: 8px;
+ border-radius: 4px;
+ `,
+ path: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 11px;
+ `,
+ statusIcon: css`
+ font-size: 12px;
+ `,
+}));
+
+interface MoveLocalFilesParams {
+ operations: Array<{
+ destination: string;
+ source: string;
+ }>;
+}
+
+const MoveLocalFiles = memo<BuiltinRenderProps<MoveLocalFilesParams, MoveLocalFilesState>>(
+ ({ pluginState }) => {
+ const { styles, theme } = useStyles();
+
+ if (!pluginState?.results) {
+ return null;
+ }
+
+ const allSuccess = pluginState.successCount === pluginState.totalCount;
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {/* Header */}
+ <Flexbox align={'center'} gap={8} horizontal>
+ {allSuccess ? (
+ <CheckCircleFilled
+ className={styles.statusIcon}
+ style={{ color: theme.colorSuccess }}
+ />
+ ) : (
+ <CloseCircleFilled className={styles.statusIcon} style={{ color: theme.colorError }} />
+ )}
+ <Text className={styles.header}>
+ Moved {pluginState.successCount}/{pluginState.totalCount} items
+ </Text>
+ </Flexbox>
+
+ {/* Move operations list */}
+ <Block padding={8} style={{ maxHeight: 300, overflow: 'auto' }} variant={'outlined'}>
+ <Flexbox gap={4}>
+ {pluginState.results.map((result, index) => (
+ <Flexbox
+ align={'center'}
+ className={styles.moveItem}
+ gap={8}
+ horizontal
+ key={index}
+ style={{
+ background: result.success ? theme.colorSuccessBg : theme.colorErrorBg,
+ }}
+ >
+ {result.success ? (
+ <CheckCircleFilled style={{ color: theme.colorSuccess, fontSize: 12 }} />
+ ) : (
+ <CloseCircleFilled style={{ color: theme.colorError, fontSize: 12 }} />
+ )}
+ <Text className={styles.path} ellipsis style={{ maxWidth: 200 }}>
+ {result.source}
+ </Text>
+ <ArrowRight className={styles.arrow} size={12} />
+ <Text className={styles.path} ellipsis style={{ maxWidth: 200 }}>
+ {result.destination}
+ </Text>
+ {result.error && (
+ <Text className={styles.path} type={'danger'}>
+ ({result.error})
+ </Text>
+ )}
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Block>
+ </Flexbox>
+ );
+ },
+);
+
+MoveLocalFiles.displayName = 'MoveLocalFiles';
+
+export default MoveLocalFiles;
diff --git a/src/tools/code-interpreter/Render/ReadLocalFile/index.tsx b/src/tools/code-interpreter/Render/ReadLocalFile/index.tsx
new file mode 100644
index 00000000000..144a6acabac
--- /dev/null
+++ b/src/tools/code-interpreter/Render/ReadLocalFile/index.tsx
@@ -0,0 +1,119 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Block, Highlighter, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ReadLocalFileState } from '../../type';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ fileInfo: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ color: ${token.colorTextSecondary};
+ `,
+ path: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+}));
+
+interface ReadLocalFileParams {
+ endLine?: number;
+ path: string;
+ startLine?: number;
+}
+
+/**
+ * Get file extension from path
+ */
+const getFileExtension = (path: string): string => {
+ const parts = path.split('.');
+ return parts.length > 1 ? parts.pop()?.toLowerCase() || 'text' : 'text';
+};
+
+/**
+ * Map file extension to Highlighter language
+ */
+const getLanguageFromExtension = (ext: string): string => {
+ const languageMap: Record<string, string> = {
+ css: 'css',
+ go: 'go',
+ html: 'html',
+ java: 'java',
+ js: 'javascript',
+ json: 'json',
+ jsx: 'jsx',
+ md: 'markdown',
+ py: 'python',
+ rs: 'rust',
+ scss: 'scss',
+ sh: 'bash',
+ sql: 'sql',
+ ts: 'typescript',
+ tsx: 'tsx',
+ xml: 'xml',
+ yaml: 'yaml',
+ yml: 'yaml',
+ };
+ return languageMap[ext] || 'text';
+};
+
+const ReadLocalFile = memo<BuiltinRenderProps<ReadLocalFileParams, ReadLocalFileState>>(
+ ({ args, pluginState }) => {
+ const { styles } = useStyles();
+
+ if (!pluginState?.content) {
+ return null;
+ }
+
+ const ext = getFileExtension(args.path);
+ const language = getLanguageFromExtension(ext);
+
+ const lineInfo =
+ pluginState.startLine || pluginState.endLine
+ ? `Lines ${pluginState.startLine || 1}-${pluginState.endLine || pluginState.totalLines || '?'}`
+ : pluginState.totalLines
+ ? `${pluginState.totalLines} lines`
+ : '';
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {/* File path and info */}
+ <Flexbox align={'center'} horizontal justify={'space-between'}>
+ <Text className={styles.path} ellipsis>
+ 📄 {args.path}
+ </Text>
+ {lineInfo && (
+ <Text className={styles.fileInfo} type={'secondary'}>
+ {lineInfo}
+ </Text>
+ )}
+ </Flexbox>
+
+ {/* File content */}
+ <Block padding={0} variant={'outlined'}>
+ <Highlighter
+ language={language}
+ showLanguage
+ style={{ maxHeight: 400, overflow: 'auto' }}
+ variant={'borderless'}
+ wrap
+ >
+ {pluginState.content}
+ </Highlighter>
+ </Block>
+ </Flexbox>
+ );
+ },
+);
+
+ReadLocalFile.displayName = 'ReadLocalFile';
+
+export default ReadLocalFile;
diff --git a/src/tools/code-interpreter/Render/RunCommand/index.tsx b/src/tools/code-interpreter/Render/RunCommand/index.tsx
new file mode 100644
index 00000000000..310f9af5411
--- /dev/null
+++ b/src/tools/code-interpreter/Render/RunCommand/index.tsx
@@ -0,0 +1,125 @@
+'use client';
+
+import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
+import { BuiltinRenderProps } from '@lobechat/types';
+import { ActionIcon, Block, Highlighter, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { ChevronDown, ChevronUp } from 'lucide-react';
+import { memo, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { RunCommandState } from '../../type';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ head: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ header: css`
+ .action-icon {
+ opacity: 0;
+ transition: opacity 0.2s ease;
+ }
+
+ &:hover {
+ .action-icon {
+ opacity: 1;
+ }
+ }
+ `,
+ statusIcon: css`
+ font-size: 12px;
+ `,
+}));
+
+interface RunCommandParams {
+ background?: boolean;
+ command: string;
+ timeout?: number;
+}
+
+const RunCommand = memo<BuiltinRenderProps<RunCommandParams, RunCommandState>>(
+ ({ args, pluginState }) => {
+ const { styles, theme } = useStyles();
+ const isSuccess = pluginState?.success;
+ const [expanded, setExpanded] = useState(false);
+
+ const statusMessage = pluginState?.isBackground
+ ? `Background command started (ID: ${pluginState.commandId})`
+ : pluginState?.success
+ ? 'Command completed'
+ : pluginState?.error || 'Command failed';
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {/* Header: Command + Status */}
+ <Flexbox align={'center'} className={styles.header} horizontal justify={'space-between'}>
+ <Flexbox gap={8} horizontal>
+ <Flexbox gap={4} horizontal>
+ {pluginState === undefined ? null : isSuccess ? (
+ <CheckCircleFilled
+ className={styles.statusIcon}
+ style={{ color: theme.colorSuccess }}
+ />
+ ) : (
+ <CloseCircleFilled
+ className={styles.statusIcon}
+ style={{ color: theme.colorError }}
+ />
+ )}
+ <Text className={styles.head} ellipsis style={{ maxWidth: 300 }}>
+ {args.command}
+ </Text>
+ </Flexbox>
+ <Text className={styles.head} type={'secondary'}>
+ {statusMessage}
+ </Text>
+ </Flexbox>
+ <Flexbox align={'center'} gap={8} horizontal>
+ <ActionIcon
+ className={`action-icon`}
+ icon={expanded ? ChevronUp : ChevronDown}
+ onClick={() => setExpanded(!expanded)}
+ size={'small'}
+ style={{ opacity: expanded ? 1 : undefined }}
+ title={expanded ? 'Collapse' : 'Expand'}
+ />
+ </Flexbox>
+ </Flexbox>
+
+ {/* Command & Output */}
+ {expanded && (
+ <Block gap={8} padding={8} variant={'outlined'}>
+ <Highlighter
+ language={'sh'}
+ showLanguage={false}
+ style={{ paddingInline: 8 }}
+ variant={'borderless'}
+ wrap
+ >
+ {args.command}
+ </Highlighter>
+ {pluginState?.output && (
+ <Highlighter language={'text'} showLanguage={false} variant={'filled'} wrap>
+ {pluginState.output}
+ </Highlighter>
+ )}
+ {pluginState?.stderr && (
+ <Highlighter language={'text'} showLanguage={false} variant={'filled'} wrap>
+ {pluginState.stderr}
+ </Highlighter>
+ )}
+ </Block>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+RunCommand.displayName = 'RunCommand';
+
+export default RunCommand;
diff --git a/src/tools/code-interpreter/Render/SearchFiles/index.tsx b/src/tools/code-interpreter/Render/SearchFiles/index.tsx
new file mode 100644
index 00000000000..4b687c93b74
--- /dev/null
+++ b/src/tools/code-interpreter/Render/SearchFiles/index.tsx
@@ -0,0 +1,109 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Block, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { File, Folder } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { SearchLocalFilesState } from '../../type';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ fileIcon: css`
+ color: ${token.colorTextSecondary};
+ `,
+ fileItem: css`
+ cursor: default;
+ padding-block: 4px;
+ padding-inline: 8px;
+ border-radius: 4px;
+
+ &:hover {
+ background: ${token.colorFillTertiary};
+ }
+ `,
+ fileName: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ folderIcon: css`
+ color: ${token.colorWarning};
+ `,
+ header: css`
+ font-size: 12px;
+ `,
+ path: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 11px;
+ color: ${token.colorTextTertiary};
+ `,
+}));
+
+interface SearchLocalFilesParams {
+ directory: string;
+ fileType?: string;
+ keyword?: string;
+ modifiedAfter?: string;
+ modifiedBefore?: string;
+}
+
+const SearchFiles = memo<BuiltinRenderProps<SearchLocalFilesParams, SearchLocalFilesState>>(
+ ({ args, pluginState }) => {
+ const { styles } = useStyles();
+
+ if (!pluginState?.results) {
+ return null;
+ }
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {/* Header */}
+ <Flexbox align={'center'} horizontal justify={'space-between'}>
+ <Text className={styles.header}>
+ 🔍 Search in {args.directory}
+ {args.keyword && ` for "${args.keyword}"`}
+ </Text>
+ <Text className={styles.path}>{pluginState.totalCount} results</Text>
+ </Flexbox>
+
+ {/* Results list */}
+ {pluginState.results.length > 0 && (
+ <Block padding={8} style={{ maxHeight: 300, overflow: 'auto' }} variant={'outlined'}>
+ <Flexbox gap={2}>
+ {pluginState.results.map((file, index) => (
+ <Flexbox
+ align={'center'}
+ className={styles.fileItem}
+ horizontal
+ justify={'space-between'}
+ key={index}
+ >
+ <Flexbox align={'center'} gap={8} horizontal>
+ {file.isDirectory ? (
+ <Folder className={styles.folderIcon} size={14} />
+ ) : (
+ <File className={styles.fileIcon} size={14} />
+ )}
+ <Flexbox gap={2}>
+ <Text className={styles.fileName}>{file.name}</Text>
+ <Text className={styles.path}>{file.path}</Text>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Block>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+SearchFiles.displayName = 'SearchFiles';
+
+export default SearchFiles;
diff --git a/src/tools/code-interpreter/Render/WriteFile/index.tsx b/src/tools/code-interpreter/Render/WriteFile/index.tsx
new file mode 100644
index 00000000000..98fe4edbb70
--- /dev/null
+++ b/src/tools/code-interpreter/Render/WriteFile/index.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { WriteLocalFileState } from '../../type';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ path: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ statusIcon: css`
+ font-size: 12px;
+ `,
+}));
+
+interface WriteLocalFileParams {
+ content: string;
+ createDirectories?: boolean;
+ path: string;
+}
+
+const WriteFile = memo<BuiltinRenderProps<WriteLocalFileParams, WriteLocalFileState>>(
+ ({ args, pluginState }) => {
+ const { styles, theme } = useStyles();
+ const isSuccess = pluginState?.success;
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ <Flexbox align={'center'} gap={8} horizontal>
+ {pluginState === undefined ? null : isSuccess ? (
+ <CheckCircleFilled className={styles.statusIcon} style={{ color: theme.colorSuccess }} />
+ ) : (
+ <CloseCircleFilled className={styles.statusIcon} style={{ color: theme.colorError }} />
+ )}
+ <Text className={styles.path}>
+ {isSuccess ? `✅ Written to ${args.path}` : `❌ Failed to write ${args.path}`}
+ </Text>
+ {pluginState?.bytesWritten !== undefined && (
+ <Text className={styles.path} type={'secondary'}>
+ ({pluginState.bytesWritten} bytes)
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+WriteFile.displayName = 'WriteFile';
+
+export default WriteFile;
diff --git a/src/tools/code-interpreter/Render/index.ts b/src/tools/code-interpreter/Render/index.ts
new file mode 100644
index 00000000000..370f3138d3f
--- /dev/null
+++ b/src/tools/code-interpreter/Render/index.ts
@@ -0,0 +1,29 @@
+import { CodeInterpreterApiName } from '../index';
+import EditLocalFile from './EditLocalFile';
+import ExecuteCode from './ExecuteCode';
+import ExportFile from './ExportFile';
+import ListFiles from './ListFiles';
+import MoveLocalFiles from './MoveLocalFiles';
+import ReadLocalFile from './ReadLocalFile';
+import RunCommand from './RunCommand';
+import SearchFiles from './SearchFiles';
+import WriteFile from './WriteFile';
+
+/**
+ * Cloud Code Interpreter Render Components Registry
+ */
+export const CodeInterpreterRenders = {
+ [CodeInterpreterApiName.editLocalFile]: EditLocalFile,
+ [CodeInterpreterApiName.executeCode]: ExecuteCode,
+ [CodeInterpreterApiName.exportFile]: ExportFile,
+ [CodeInterpreterApiName.listLocalFiles]: ListFiles,
+ [CodeInterpreterApiName.moveLocalFiles]: MoveLocalFiles,
+ [CodeInterpreterApiName.readLocalFile]: ReadLocalFile,
+ [CodeInterpreterApiName.runCommand]: RunCommand,
+ [CodeInterpreterApiName.searchLocalFiles]: SearchFiles,
+ [CodeInterpreterApiName.writeLocalFile]: WriteFile,
+};
+
+// Export API names for use in other modules
+
+export { CodeInterpreterApiName } from '../index';
diff --git a/src/tools/code-interpreter/index.ts b/src/tools/code-interpreter/index.ts
index c99480949be..4f699c54d14 100644
--- a/src/tools/code-interpreter/index.ts
+++ b/src/tools/code-interpreter/index.ts
@@ -1,27 +1,330 @@
import { BuiltinToolManifest } from '@lobechat/types';
-export const CodeInterpreterIdentifier = 'lobe-code-interpreter';
+import { systemPrompt } from './systemRole';
+
+export const CodeInterpreterApiName = {
+ editLocalFile: 'editLocalFile',
+ executeCode: 'executeCode',
+ exportFile: 'exportFile',
+ getCommandOutput: 'getCommandOutput',
+ globLocalFiles: 'globLocalFiles',
+ grepContent: 'grepContent',
+ killCommand: 'killCommand',
+ listLocalFiles: 'listLocalFiles',
+ moveLocalFiles: 'moveLocalFiles',
+ readLocalFile: 'readLocalFile',
+ renameLocalFile: 'renameLocalFile',
+ runCommand: 'runCommand',
+ searchLocalFiles: 'searchLocalFiles',
+ writeLocalFile: 'writeLocalFile',
+};
+
+export const CodeInterpreterIdentifier = 'lobe-cloud-code-interpreter';
export const CodeInterpreterManifest: BuiltinToolManifest = {
api: [
{
- description: 'A Python interpreter. Use this tool to run Python code. ',
- name: 'python',
+ description:
+ 'Execute code directly in the sandbox environment. Supports Python, JavaScript, and TypeScript. Returns execution output, errors, and exit code.',
+ humanIntervention: 'required',
+ name: CodeInterpreterApiName.executeCode,
parameters: {
properties: {
code: {
- description: 'The Python code to run.',
+ description: 'The code to execute',
+ type: 'string',
+ },
+ language: {
+ description: 'Programming language: python (default), javascript, or typescript',
+ enum: ['python', 'javascript', 'typescript'],
+ type: 'string',
+ },
+ },
+ required: ['code'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'List files and folders in a specified directory. Input should be a path. Output is a JSON array of file/folder names.',
+ name: CodeInterpreterApiName.listLocalFiles,
+ parameters: {
+ properties: {
+ directoryPath: {
+ description: 'The directory path to list',
+ type: 'string',
+ },
+ },
+ required: ['directoryPath'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Read the content of a specific file. Input should be the file path. Output is the file content as a string.',
+ name: CodeInterpreterApiName.readLocalFile,
+ parameters: {
+ properties: {
+ endLine: {
+ description: 'End line number (1-based, inclusive)',
+ type: 'number',
+ },
+ path: {
+ description: 'The file path to read',
+ type: 'string',
+ },
+ startLine: {
+ description: 'Start line number (1-based)',
+ type: 'number',
+ },
+ },
+ required: ['path'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Search for files within the sandbox based on keywords and filter options.',
+ name: CodeInterpreterApiName.searchLocalFiles,
+ parameters: {
+ properties: {
+ directory: {
+ description: 'Directory to search in',
+ type: 'string',
+ },
+ fileType: {
+ description: 'File type/extension filter',
+ type: 'string',
+ },
+ keyword: {
+ description: 'Filename keyword filter',
type: 'string',
},
- packages: {
- description: 'The packages to install before running the code.',
+ modifiedAfter: {
+ description: 'Modified time lower bound (ISO date string)',
+ type: 'string',
+ },
+ modifiedBefore: {
+ description: 'Modified time upper bound (ISO date string)',
+ type: 'string',
+ },
+ },
+ required: ['directory'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Moves or renames multiple files/directories. Input is an array of operations with source and destination paths.',
+ humanIntervention: 'required',
+ name: CodeInterpreterApiName.moveLocalFiles,
+ parameters: {
+ properties: {
+ operations: {
+ description: 'A list of move operations to perform.',
items: {
- type: 'string',
+ properties: {
+ destination: {
+ description: 'The target path for the file/directory.',
+ type: 'string',
+ },
+ source: {
+ description: 'The current path of the file/directory to move.',
+ type: 'string',
+ },
+ },
+ required: ['source', 'destination'],
+ type: 'object',
},
type: 'array',
},
},
- required: ['packages', 'code'],
+ required: ['operations'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Rename a file or folder in its current location. Input should be the current full path and the new name.',
+ name: CodeInterpreterApiName.renameLocalFile,
+ parameters: {
+ properties: {
+ newName: {
+ description: 'The new name for the file or folder (filename only, not full path)',
+ type: 'string',
+ },
+ oldPath: {
+ description: 'The current full path of the file or folder to rename',
+ type: 'string',
+ },
+ },
+ required: ['oldPath', 'newName'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Write content to a specific file. Input should be the file path and content. Overwrites existing file or creates a new one.',
+ humanIntervention: 'required',
+ name: CodeInterpreterApiName.writeLocalFile,
+ parameters: {
+ properties: {
+ content: {
+ description: 'The content to write',
+ type: 'string',
+ },
+ createDirectories: {
+ description: 'Whether to create parent directories if they do not exist',
+ type: 'boolean',
+ },
+ path: {
+ description: 'The file path to write to',
+ type: 'string',
+ },
+ },
+ required: ['path', 'content'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Perform exact string replacements in files. Must read the file first before editing.',
+ humanIntervention: 'required',
+ name: CodeInterpreterApiName.editLocalFile,
+ parameters: {
+ properties: {
+ all: {
+ description: 'Replace all occurrences (default: false)',
+ type: 'boolean',
+ },
+ path: {
+ description: 'The absolute path to the file to modify',
+ type: 'string',
+ },
+ replace: {
+ description: 'The text to replace with (must differ from search)',
+ type: 'string',
+ },
+ search: {
+ description: 'The exact text to search for',
+ type: 'string',
+ },
+ },
+ required: ['path', 'search', 'replace'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Execute a shell command and return its output. Supports both synchronous and background execution with timeout control.',
+ humanIntervention: 'required',
+ name: CodeInterpreterApiName.runCommand,
+ parameters: {
+ properties: {
+ background: {
+ description: 'Set to true to run command in background and return commandId',
+ type: 'boolean',
+ },
+ command: {
+ description: 'The shell command to execute',
+ type: 'string',
+ },
+ timeout: {
+ description: 'Timeout in milliseconds (default: 120000ms)',
+ type: 'number',
+ },
+ },
+ required: ['command'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Retrieve output from a running or completed background shell command. Returns only new output since the last check.',
+ name: CodeInterpreterApiName.getCommandOutput,
+ parameters: {
+ properties: {
+ commandId: {
+ description: 'The ID of the background command to retrieve output from',
+ type: 'string',
+ },
+ },
+ required: ['commandId'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Kill a running background shell command by its ID.',
+ name: CodeInterpreterApiName.killCommand,
+ parameters: {
+ properties: {
+ commandId: {
+ description: 'The ID of the background command to kill',
+ type: 'string',
+ },
+ },
+ required: ['commandId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Search for content within files using regex patterns. Supports various output modes and filtering options.',
+ name: CodeInterpreterApiName.grepContent,
+ parameters: {
+ properties: {
+ directory: {
+ description: 'Directory to search in',
+ type: 'string',
+ },
+ filePattern: {
+ description: 'File name pattern filter (e.g., "*.ts")',
+ type: 'string',
+ },
+ pattern: {
+ description: 'The regex pattern to search for',
+ type: 'string',
+ },
+ recursive: {
+ description: 'Whether to search recursively (default: true)',
+ type: 'boolean',
+ },
+ },
+ required: ['pattern', 'directory'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Find files matching glob patterns. Supports standard glob syntax like "**/*.js" or "src/**/*.ts".',
+ name: CodeInterpreterApiName.globLocalFiles,
+ parameters: {
+ properties: {
+ directory: {
+ description: 'The base directory to search in (defaults to current working directory)',
+ type: 'string',
+ },
+ pattern: {
+ description: 'The glob pattern to match files against (e.g. "**/*.js", "*.{ts,tsx}")',
+ type: 'string',
+ },
+ },
+ required: ['pattern'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Export a file from the sandbox to cloud storage. The file will be uploaded to a pre-signed URL and can be downloaded by the user.',
+ name: CodeInterpreterApiName.exportFile,
+ parameters: {
+ properties: {
+ path: {
+ description:
+ 'The path of the file in the sandbox to export (e.g., "./output/result.csv")',
+ type: 'string',
+ },
+ },
+ required: ['path'],
type: 'object',
},
},
@@ -30,38 +333,8 @@ export const CodeInterpreterManifest: BuiltinToolManifest = {
meta: {
avatar:
'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IS0tIFVwbG9hZGVkIHRvOiBTVkcgUmVwbywgd3d3LnN2Z3JlcG8uY29tLCBHZW5lcmF0b3I6IFNWRyBSZXBvIE1peGVyIFRvb2xzIC0tPgo8c3ZnIHdpZHRoPSI4MDBweCIgaGVpZ2h0PSI4MDBweCIgdmlld0JveD0iMCAwIDMyIDMyIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPg0KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMy4wMTY0IDJDMTAuODE5MyAyIDkuMDM4MjUgMy43MjQ1MyA5LjAzODI1IDUuODUxODVWOC41MTg1MkgxNS45MjM1VjkuMjU5MjZINS45NzgxNEMzLjc4MTA3IDkuMjU5MjYgMiAxMC45ODM4IDIgMTMuMTExMUwyIDE4Ljg4ODlDMiAyMS4wMTYyIDMuNzgxMDcgMjIuNzQwNyA1Ljk3ODE0IDIyLjc0MDdIOC4yNzMyMlYxOS40ODE1QzguMjczMjIgMTcuMzU0MiAxMC4wNTQzIDE1LjYyOTYgMTIuMjUxNCAxNS42Mjk2SDE5LjU5NTZDMjEuNDU0NyAxNS42Mjk2IDIyLjk2MTcgMTQuMTcwNCAyMi45NjE3IDEyLjM3MDRWNS44NTE4NUMyMi45NjE3IDMuNzI0NTMgMjEuMTgwNyAyIDE4Ljk4MzYgMkgxMy4wMTY0Wk0xMi4wOTg0IDYuNzQwNzRDMTIuODU4OSA2Ljc0MDc0IDEzLjQ3NTQgNi4xNDM3OCAxMy40NzU0IDUuNDA3NDFDMTMuNDc1NCA0LjY3MTAzIDEyLjg1ODkgNC4wNzQwNyAxMi4wOTg0IDQuMDc0MDdDMTEuMzM3OCA0LjA3NDA3IDEwLjcyMTMgNC42NzEwMyAxMC43MjEzIDUuNDA3NDFDMTAuNzIxMyA2LjE0Mzc4IDExLjMzNzggNi43NDA3NCAxMi4wOTg0IDYuNzQwNzRaIiBmaWxsPSJ1cmwoI3BhaW50MF9saW5lYXJfODdfODIwNCkiLz4NCjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMTguOTgzNCAzMEMyMS4xODA1IDMwIDIyLjk2MTYgMjguMjc1NSAyMi45NjE2IDI2LjE0ODJWMjMuNDgxNUwxNi4wNzYzIDIzLjQ4MTVMMTYuMDc2MyAyMi43NDA4TDI2LjAyMTcgMjIuNzQwOEMyOC4yMTg4IDIyLjc0MDggMjkuOTk5OCAyMS4wMTYyIDI5Ljk5OTggMTguODg4OVYxMy4xMTExQzI5Ljk5OTggMTAuOTgzOCAyOC4yMTg4IDkuMjU5MjggMjYuMDIxNyA5LjI1OTI4TDIzLjcyNjYgOS4yNTkyOFYxMi41MTg1QzIzLjcyNjYgMTQuNjQ1OSAyMS45NDU1IDE2LjM3MDQgMTkuNzQ4NSAxNi4zNzA0TDEyLjQwNDIgMTYuMzcwNEMxMC41NDUxIDE2LjM3MDQgOS4wMzgwOSAxNy44Mjk2IDkuMDM4MDkgMTkuNjI5Nkw5LjAzODA5IDI2LjE0ODJDOS4wMzgwOSAyOC4yNzU1IDEwLjgxOTIgMzAgMTMuMDE2MiAzMEgxOC45ODM0Wk0xOS45MDE1IDI1LjI1OTNDMTkuMTQwOSAyNS4yNTkzIDE4LjUyNDQgMjUuODU2MiAxOC41MjQ0IDI2LjU5MjZDMTguNTI0NCAyNy4zMjkgMTkuMTQwOSAyNy45MjU5IDE5LjkwMTUgMjcuOTI1OUMyMC42NjIgMjcuOTI1OSAyMS4yNzg1IDI3LjMyOSAyMS4yNzg1IDI2LjU5MjZDMjEuMjc4NSAyNS44NTYyIDIwLjY2MiAyNS4yNTkzIDE5LjkwMTUgMjUuMjU5M1oiIGZpbGw9InVybCgjcGFpbnQxX2xpbmVhcl84N184MjA0KSIvPg0KPGRlZnM+DQo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfODdfODIwNCIgeDE9IjEyLjQ4MDkiIHkxPSIyIiB4Mj0iMTIuNDgwOSIgeTI9IjIyLjc0MDciIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4NCjxzdG9wIHN0b3AtY29sb3I9IiMzMjdFQkQiLz4NCjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzE1NjVBNyIvPg0KPC9saW5lYXJHcmFkaWVudD4NCjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQxX2xpbmVhcl84N184MjA0IiB4MT0iMTkuNTE5IiB5MT0iOS4yNTkyOCIgeDI9IjE5LjUxOSIgeTI9IjMwIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+DQo8c3RvcCBzdG9wLWNvbG9yPSIjRkZEQTRCIi8+DQo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNGOUM2MDAiLz4NCjwvbGluZWFyR3JhZGllbnQ+DQo8L2RlZnM+DQo8L3N2Zz4=',
- title: 'Code Interpreter',
+ title: 'Cloud Code Interpreter',
},
- systemRole: `When you send a message containing Python code to python, it will be executed in a temporary pyodide python environment in browser.
-python will respond with the output of the execution or time out after 60.0 seconds.
-The drive at '/mnt/data' can be used to save and persist user files.
-
-If you are using matplotlib:
-- never use seaborn
-- give each chart its own distinct plot (no subplots)
-- never set any specific colors – unless explicitly asked to by the user
-
-If you are accessing the internet, You MUST use pyfetch from pyodide.http package. Any other methods of accessing the internet will fail.
-pyfetch is a wrapper of js fetch API, it is a async function that returns a pyodide.http.FetchResponse object.
-Here are some useful methods of FetchResponse:
- - async bytes(): returns a bytes object
- - async text(): returns a string
- - async json(): returns a json object
-
-If you are generating files:
-- You MUST use the instructed library for each supported file format. (Do not assume any other libraries are available):
- - pdf --> reportlab
- - docx --> python-docx
- - xlsx --> openpyxl
- - pptx --> python-pptx
- - csv --> pandas
- - ods --> odfpy
- - odt --> odfpy
- - odp --> odfpy
-- None of the above packages are installed by default. You MUST include them in the packages parameter to install them EVERY TIME.
-- If you are generating a pdf
- - You MUST prioritize generating text content using reportlab.platypus rather than canvas
- - If you are generating text in Chinese, you MUST use STSong. To use the font, you must call pdfmetrics.registerFont(TTFont('STSong', 'STSong.ttf')) and apply the style to all text elements
- `,
+ systemRole: systemPrompt,
type: 'builtin',
};
diff --git a/src/tools/code-interpreter/systemRole.ts b/src/tools/code-interpreter/systemRole.ts
new file mode 100644
index 00000000000..435d18b33be
--- /dev/null
+++ b/src/tools/code-interpreter/systemRole.ts
@@ -0,0 +1,168 @@
+export const systemPrompt = `You have access to a Cloud Code Interpreter tool that provides a secure, isolated sandbox environment for executing code and file operations. This sandbox runs on AWS Bedrock AgentCore and is completely separate from the user's local system.
+
+
+<sandbox_environment>
+**Important:** This is a CLOUD SANDBOX environment, NOT the user's local file system.
+- Files created here are temporary and session-specific
+- Each conversation topic has its own isolated session
+- Sessions may expire after inactivity; files will be recreated if needed
+- The sandbox has its own isolated file system starting at the root directory
+- Commands will time out after 60 seconds by default
+</sandbox_environment>
+
+
+<core_capabilities>
+You have access to the following tools for interacting with the cloud sandbox:
+
+
+**File Operations:**
+1. **listLocalFiles**: Lists files and directories in a specified path within the sandbox.
+2. **readLocalFile**: Reads the content of a specified file, optionally within a line range.
+3. **writeLocalFile**: Write content to a specific file. Creates parent directories if needed.
+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.
+7. **exportFile**: Export a file from the sandbox to allow user download.
+
+
+**Code Execution:**
+8. **executeCode**: Execute code directly in the sandbox. Supports Python (default), JavaScript, and TypeScript.
+
+**Shell Commands:**
+9. **runCommand**: Execute shell commands with timeout control. Supports background execution.
+10. **getCommandOutput**: Retrieve output from running background commands.
+11. **killCommand**: Terminate a running background shell command by its ID.
+
+
+**Search & Find:**
+12. **searchLocalFiles**: Search for files based on keywords and criteria.
+13. **grepContent**: Search for content within files using regex patterns.
+14. **globLocalFiles**: Find files matching glob patterns (e.g., "**/*.js").
+</core_capabilities>
+
+
+<workflow>
+1. Understand the user's request regarding code execution or file operations.
+2. Select the appropriate tool(s) for the task.
+3. Execute operations in the sandbox environment.
+4. Present results clearly, noting that files exist in the cloud sandbox.
+5. **Export files by default** - see export_policy below for when to export vs skip.
+</workflow>
+
+
+<export_policy>
+**CRITICAL: Default Export Behavior**
+
+**Core Principle: Export by Default**
+When code execution produces any output files (documents, images, data, etc.), you SHOULD automatically export them using \`exportFile\` unless the user explicitly indicates they don't need the file.
+
+**When to Export (DEFAULT - most cases):**
+- User asks to "create/make/generate/write/build" something
+- User asks to "export/download/save" something
+- User asks to "convert/transform" files
+- User asks to "process/analyze" data and expects output files
+- User asks to "draw/plot/visualize" something (export the chart/image)
+- User provides data and expects a result file
+- Any task that produces a meaningful output file the user would want
+
+**Trigger Phrases that REQUIRE export:**
+- English: "create", "make", "generate", "export", "download", "save", "convert", "help me [verb] a [file]", "I need/want a [file]"
+- Chinese: "创建", "生成", "制作", "导出", "下载", "保存", "转换", "帮我做/写/画", "我要/需要一个"
+
+**When NOT to Export (exceptions only):**
+- User explicitly says "just run it" / "帮我跑一下" / "run this" / "execute only"
+- User says "don't export" / "不用导出" / "just check" / "只是看看"
+- User only asks to "read", "view", "check", or "debug" without expecting output files
+- Temporary/intermediate files (cache, temp data, __pycache__, etc.)
+- Configuration files meant to stay in sandbox (.env, config.json for sandbox use)
+- User is iterating/debugging and hasn't finalized the result yet
+
+**Execution Pattern:**
+1. Execute the requested operation
+2. If output files are produced → **call exportFile immediately**
+3. Present download links prominently in the response
+4. Confirm what was created and exported
+
+**Example Response Format:**
+✅ Successfully created [filename]
+📥 Download link: [export URL]
+📄 File details: [size, format, brief description]
+
+**Export File Types (common outputs):**
+- Documents: PDF, DOCX, XLSX, PPTX, TXT, MD, CSV, ODT, ODS, ODP
+- Images: PNG, JPG, JPEG, SVG, GIF
+- Code files: PY, JS, HTML, CSS, JSON, XML, YAML
+- Archives: ZIP, TAR, GZ
+- Data files: CSV, JSON, XML, PARQUET
+</export_policy>
+
+
+<tool_usage_guidelines>
+- For listing directory contents: Use 'listLocalFiles' with the target directory path.
+- For reading a file: Use 'readLocalFile' with the file path. Optionally specify startLine/endLine for partial reads.
+- For writing files: Use 'writeLocalFile' with the file path and content. Set createDirectories: true if needed.
+- For editing files: Use 'editLocalFile'. Always read the file first to verify content before editing.
+- For executing code directly: Use 'executeCode' with the code and optional language (python/javascript/typescript). This is preferred over runCommand for simple code execution.
+- For running shell commands: Use 'runCommand' to execute shell commands like \`pip install package\` or complex shell operations.
+- For background tasks: Set background: true in runCommand, then use getCommandOutput to check progress.
+- For searching files: Use 'searchLocalFiles' for filename search, 'grepContent' for content search, 'globLocalFiles' for pattern matching.
+- For exporting files: Use 'exportFile' with the file path to generate a download URL for the user. **Export by default when any output files are produced - only skip when user explicitly asks to just run/check something.**
+</tool_usage_guidelines>
+
+
+<python_guidelines>
+When executing Python code:
+
+
+**Visualization with Matplotlib:**
+- Never use seaborn library
+- Give each chart its own distinct plot (no subplots)
+- Never set specific colors unless explicitly asked by the user
+- Save plots to files using \`plt.savefig('output.png')\` then **automatically export for user download**
+
+
+**Generating Document Files:**
+You MUST use the following libraries for each supported file format:
+- **PDF**: Use \`reportlab\` - prioritize \`reportlab.platypus\` over canvas for text content
+- **DOCX**: Use \`python-docx\`
+- **XLSX**: Use \`openpyxl\`
+- **PPTX**: Use \`python-pptx\`
+- **CSV**: Use \`pandas\`
+- **ODS/ODT/ODP**: Use \`odfpy\`
+
+Install required packages first: \`pip install <package-name>\`
+**After successful generation, automatically export the document file.**
+
+
+**Chinese Text in PDFs:**
+When generating PDFs with Chinese text, you MUST:
+1. Register the Chinese font: \`pdfmetrics.registerFont(TTFont('STSong', 'STSong.ttf'))\`
+2. Apply the 'STSong' font style to all text elements containing Chinese characters
+</python_guidelines>
+
+
+<session_behavior>
+- Your sandbox session is automatically managed per conversation topic
+- If a session expires, it will be automatically recreated
+- Files from previous sessions may not persist; recreate them as needed
+- The sessionExpiredAndRecreated flag in responses indicates if this occurred
+</session_behavior>
+
+
+<security_considerations>
+- This sandbox is isolated from the user's local system for security
+- Confirm with the user before performing destructive operations
+- Be cautious with shell commands that have significant side effects
+- The sandbox has resource limits (CPU, memory, execution time)
+</security_considerations>
+
+
+<response_format>
+- When showing file paths, clarify they are in the cloud sandbox
+- When displaying file contents, format code appropriately with syntax highlighting
+- When showing command output, preserve formatting and line breaks
+- Always indicate success/failure status clearly
+- **When files are auto-exported per the rules, prominently display download links with clear labels**
+- Use visual indicators (✅ 📥 📄) to make exported files stand out
+</response_format>
+`;
diff --git a/src/tools/code-interpreter/type.ts b/src/tools/code-interpreter/type.ts
new file mode 100644
index 00000000000..3d7f7f40f77
--- /dev/null
+++ b/src/tools/code-interpreter/type.ts
@@ -0,0 +1,148 @@
+/**
+ * Types for Cloud Code Interpreter tool states
+ * These types represent the state returned by each tool after execution
+ */
+
+// ==================== File Operations ====================
+
+export interface ListLocalFilesState {
+ files: Array<{
+ isDirectory: boolean;
+ name: string;
+ path: string;
+ size?: number;
+ }>;
+}
+
+export interface ReadLocalFileState {
+ content: string;
+ endLine?: number;
+ path: string;
+ startLine?: number;
+ totalLines?: number;
+}
+
+export interface WriteLocalFileState {
+ bytesWritten?: number;
+ path: string;
+ success: boolean;
+}
+
+export interface EditLocalFileState {
+ diffText?: string;
+ linesAdded?: number;
+ linesDeleted?: number;
+ path: string;
+ replacements: number;
+}
+
+export interface SearchLocalFilesState {
+ results: Array<{
+ isDirectory: boolean;
+ modifiedAt?: string;
+ name: string;
+ path: string;
+ size?: number;
+ }>;
+ totalCount: number;
+}
+
+export interface MoveLocalFilesState {
+ results: Array<{
+ destination: string;
+ error?: string;
+ source: string;
+ success: boolean;
+ }>;
+ successCount: number;
+ totalCount: number;
+}
+
+export interface RenameLocalFileState {
+ error?: string;
+ newPath: string;
+ oldPath: string;
+ success: boolean;
+}
+
+export interface GlobFilesState {
+ files: string[];
+ pattern: string;
+ totalCount: number;
+}
+
+export interface ExportFileState {
+ /** File content for text files (only when mimeType is text-like and size <= 1MB) */
+ content?: string;
+ /** The download URL for the exported file */
+ downloadUrl: string;
+ /** The exported file name */
+ filename: string;
+ /** The MIME type of the file */
+ mimeType?: string;
+ /** The original path in sandbox */
+ path: string;
+ /** The file size in bytes */
+ size?: number;
+ /** Whether the export was successful */
+ success: boolean;
+}
+
+export interface GrepContentState {
+ matches: Array<{
+ content?: string;
+ lineNumber?: number;
+ path: string;
+ }>;
+ pattern: string;
+ totalMatches: number;
+}
+
+// ==================== Code Execution ====================
+
+export interface ExecuteCodeState {
+ /** Error message if execution failed */
+ error?: string;
+ /** Exit code of the execution */
+ exitCode?: number;
+ /** The programming language used */
+ language: 'javascript' | 'python' | 'typescript';
+ /** Standard output from execution */
+ output?: string;
+ /** Standard error from execution */
+ stderr?: string;
+ /** Whether the execution was successful */
+ success: boolean;
+}
+
+// ==================== Shell Commands ====================
+
+export interface RunCommandState {
+ commandId?: string;
+ error?: string;
+ exitCode?: number;
+ isBackground: boolean;
+ output?: string;
+ stderr?: string;
+ success: boolean;
+}
+
+export interface GetCommandOutputState {
+ error?: string;
+ newOutput?: string;
+ running: boolean;
+ success: boolean;
+}
+
+export interface KillCommandState {
+ commandId: string;
+ error?: string;
+ success: boolean;
+}
+
+// ==================== Session Info ====================
+
+export interface SessionInfo {
+ sessionExpiredAndRecreated: boolean;
+ sessionId: string;
+}
diff --git a/src/utils/router.tsx b/src/utils/router.tsx
new file mode 100644
index 00000000000..4e9d3e2c1e2
--- /dev/null
+++ b/src/utils/router.tsx
@@ -0,0 +1,176 @@
+'use client';
+
+import {
+ ComponentType,
+ ReactElement,
+ Suspense,
+ createElement,
+ lazy,
+ memo,
+ useCallback,
+ useEffect,
+} from 'react';
+import { Navigate, Route, useNavigate, useRouteError } from 'react-router-dom';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import { useGlobalStore } from '@/store/global';
+
+/**
+ * Helper function to create a dynamic page element directly for router configuration
+ * This eliminates the need to define const for each component
+ *
+ * @example
+ * // Instead of:
+ * // const ChatPage = dynamicPage(() => import('./chat'));
+ * // element: <ChatPage />
+ *
+ * // You can now use:
+ * // element: dynamicElement(() => import('./chat'))
+ */
+export function dynamicElement<P = NonNullable<unknown>>(
+ importFn: () => Promise<{ default: ComponentType<P> } | ComponentType<P>>,
+ debugId?: string,
+): ReactElement {
+ const LazyComponent = lazy(async () => {
+ // eslint-disable-next-line @next/next/no-assign-module-variable
+ const module = await importFn();
+ if (typeof module === 'function') {
+ return { default: module };
+ }
+ if ('default' in module) {
+ return module as { default: ComponentType<P> };
+ }
+ return { default: module as unknown as ComponentType<P> };
+ });
+
+ // @ts-ignore
+ return (
+ <Suspense fallback={<Loading debugId={debugId || 'dynamicElement'} />}>
+ {/* @ts-ignore */}
+ <LazyComponent {...({} as P)} />
+ </Suspense>
+ );
+}
+
+/**
+ * Error boundary component for React Router
+ * Displays an error page and provides a reset function to navigate to a specific path
+ *
+ * @example
+ * import { ErrorBoundary } from '@/utils/dynamicPage';
+ *
+ * // In router config:
+ * {
+ * path: 'chat',
+ * errorElement: <ErrorBoundary resetPath="/chat" />
+ * }
+ */
+export interface ErrorBoundaryProps {
+ resetPath: string;
+}
+
+export const ErrorBoundary = ({ resetPath }: ErrorBoundaryProps) => {
+ const ErrorCapture = require('@/components/Error').default;
+
+ const error = useRouteError() as Error;
+ const navigate = useNavigate();
+
+ const reset = useCallback(() => {
+ navigate(resetPath);
+ }, [navigate, resetPath]);
+
+ return createElement(ErrorCapture, { error, reset });
+};
+
+/**
+ * Component to register navigate function in global store
+ * This allows navigation to be triggered from anywhere in the app, including stores
+ *
+ * @example
+ * import { NavigatorRegistrar } from '@/utils/dynamicPage';
+ *
+ * // In router root layout:
+ * const RootLayout = () => (
+ * <>
+ * <NavigatorRegistrar />
+ * <YourMainLayout />
+ * </>
+ * );
+ */
+export const NavigatorRegistrar = memo(() => {
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ useGlobalStore.setState({ navigate });
+ return () => {
+ useGlobalStore.setState({ navigate: undefined });
+ };
+ }, [navigate]);
+
+ return null;
+});
+
+/**
+ * Route configuration object type (compatible with createBrowserRouter format)
+ */
+export interface RouteConfig {
+ // HydrateFallback is ignored in declarative mode
+ HydrateFallback?: ComponentType;
+ children?: RouteConfig[];
+ element?: ReactElement;
+ errorElement?: ReactElement;
+ index?: boolean;
+ loader?: (args: { params: Record<string, string | undefined> }) => unknown;
+ path?: string;
+}
+
+/**
+ * Convert route config objects to declarative Route elements
+ * This allows using createBrowserRouter-style config with BrowserRouter
+ *
+ * @example
+ * const routes: RouteConfig[] = [
+ * {
+ * path: '/',
+ * element: <Layout />,
+ * children: [
+ * { path: 'chat', element: <Chat /> }
+ * ]
+ * }
+ * ];
+ *
+ * <BrowserRouter>
+ * <Routes>{renderRoutes(routes)}</Routes>
+ * </BrowserRouter>
+ */
+export function renderRoutes(routes: RouteConfig[]): ReactElement[] {
+ return routes.map((route, index) => {
+ const { path, element, children, index: isIndex, loader } = route;
+
+ // Handle redirect loaders (convert to Navigate element)
+ if (loader && !element && isIndex) {
+ // Check if loader is a redirect by inspecting it
+ // For now, we'll handle this case in the config itself
+ }
+
+ const childRoutes = children ? renderRoutes(children) : undefined;
+
+ if (isIndex) {
+ return <Route element={element} index key={`index-${index}`} />;
+ }
+
+ return (
+ <Route element={element} key={path || index} path={path}>
+ {childRoutes}
+ </Route>
+ );
+ });
+}
+
+/**
+ * Create a redirect element for use in route config
+ * Replaces loader: () => redirect('/path') in declarative mode
+ */
+export function redirectElement(to: string): ReactElement {
+ return <Navigate replace to={to} />;
+}