♻️ refactor: move code-interpreter to single packages

This commit is contained in:
arvinxx
2025-12-30 17:03:15 +08:00
parent 784bb5806a
commit 1fa4357963
36 changed files with 160 additions and 112 deletions
+1
View File
@@ -168,6 +168,7 @@
"@lobechat/agent-runtime": "workspace:*",
"@lobechat/builtin-agents": "workspace:*",
"@lobechat/builtin-tool-agent-builder": "workspace:*",
"@lobechat/builtin-tool-code-interpreter": "workspace:*",
"@lobechat/builtin-tool-group-agent-builder": "workspace:*",
"@lobechat/builtin-tool-group-management": "workspace:*",
"@lobechat/builtin-tool-gtd": "workspace:*",
@@ -0,0 +1,22 @@
{
"name": "@lobechat/builtin-tool-code-interpreter",
"version": "1.0.0",
"private": true,
"exports": {
".": "./src/index.ts",
"./client": "./src/client/index.ts",
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
"devDependencies": {
"@lobechat/types": "workspace:*"
},
"peerDependencies": {
"@lobehub/ui": "^4",
"antd": "^6",
"antd-style": "*",
"lucide-react": "*",
"react": "*",
"react-i18next": "*"
}
}
@@ -17,7 +17,7 @@ import {
type RunCommandState,
type SearchLocalFilesState,
type WriteLocalFileState,
} from '../type';
} from '../types';
/**
* Cloud Code Interpreter Execution Runtime
@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';
import { highlightTextStyles, shinyTextStyles } from '@/styles';
import { type ExecuteCodeState } from '../../type';
import { type ExecuteCodeState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
root: css`
@@ -1,4 +1,4 @@
import { CodeInterpreterApiName } from '../index';
import { CodeInterpreterApiName } from '../../types';
import { ExecuteCodeInspector } from './ExecuteCode';
/**
@@ -1,4 +1,4 @@
import { CodeInterpreterApiName } from '../index';
import { CodeInterpreterApiName } from '../../types';
import EditLocalFile from './EditLocalFile';
import ExecuteCode from './ExecuteCode';
import MoveLocalFiles from './MoveLocalFiles';
@@ -7,7 +7,7 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { memo, useState } from 'react';
import { type EditLocalFileState } from '../../type';
import { type EditLocalFileState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -5,7 +5,7 @@ import { Block, Flexbox, Highlighter } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
import { type ExecuteCodeState } from '../../type';
import { type ExecuteCodeState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -6,7 +6,7 @@ import { ActionIcon, Flexbox, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { memo, useCallback } from 'react';
import { type ExportFileState } from '../../type';
import { type ExportFileState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -6,7 +6,7 @@ import { createStaticStyles } from 'antd-style';
import { File, Folder } from 'lucide-react';
import { memo } from 'react';
import { type ListLocalFilesState } from '../../type';
import { type ListLocalFilesState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -7,7 +7,7 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ArrowRight } from 'lucide-react';
import { memo } from 'react';
import { type MoveLocalFilesState } from '../../type';
import { type MoveLocalFilesState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
arrow: css`
@@ -5,7 +5,7 @@ import { Block, Flexbox, Highlighter, Text } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
import { type ReadLocalFileState } from '../../type';
import { type ReadLocalFileState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -7,7 +7,7 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { memo, useState } from 'react';
import { type RunCommandState } from '../../type';
import { type RunCommandState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -6,7 +6,7 @@ import { createStaticStyles } from 'antd-style';
import { File, Folder } from 'lucide-react';
import { memo } from 'react';
import { type SearchLocalFilesState } from '../../type';
import { type SearchLocalFilesState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -6,7 +6,7 @@ import { Flexbox, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { memo } from 'react';
import { type WriteLocalFileState } from '../../type';
import { type WriteLocalFileState } from '../../../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -1,4 +1,4 @@
import { CodeInterpreterApiName } from '../index';
import { CodeInterpreterApiName } from '../../types';
import EditLocalFile from './EditLocalFile';
import ExecuteCode from './ExecuteCode';
import ExportFile from './ExportFile';
@@ -26,4 +26,4 @@ export const CodeInterpreterRenders = {
// Export API names for use in other modules
export { CodeInterpreterApiName } from '../index';
export { CodeInterpreterApiName } from '../../types';
@@ -1,4 +1,4 @@
import { CodeInterpreterApiName } from '../index';
import { CodeInterpreterApiName } from '../../types';
import { ExecuteCodeStreaming } from './ExecuteCode';
/**
@@ -0,0 +1,15 @@
// Inspector components (customized tool call headers)
export { CodeInterpreterInspectors } from './Inspector';
// Render components (read-only snapshots)
export { CodeInterpreterRenders } from './Render';
// Intervention components (approval dialogs)
export { CodeInterpreterInterventions } from './Intervention';
// Streaming components
export { CodeInterpreterStreamings } from './Streaming';
// Re-export types and manifest for convenience
export { CodeInterpreterIdentifier, CodeInterpreterManifest } from '../manifest';
export * from '../types';
@@ -0,0 +1,3 @@
export * from './manifest';
export * from './systemRole';
export * from './types';
@@ -1,23 +1,7 @@
import { type BuiltinToolManifest } from '@lobechat/types';
import type { BuiltinToolManifest } from '@lobechat/types';
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',
};
import { CodeInterpreterApiName } from './types';
export const CodeInterpreterIdentifier = 'lobe-cloud-code-interpreter';
@@ -344,3 +328,5 @@ export const CodeInterpreterManifest: BuiltinToolManifest = {
systemRole: systemPrompt,
type: 'builtin',
};
export { CodeInterpreterApiName } from './types';
@@ -1,28 +1,28 @@
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.
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>
<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:
<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.
**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:**
@@ -31,14 +31,14 @@ You have access to the following tools for interacting with the cloud sandbox:
**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.
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>
14. **globLocalFiles**: Find files matching glob patterns (e.g., "**/*.js").
</core_capabilities>
<workflow>
@@ -107,61 +107,61 @@ When code execution produces any output files (documents, images, data, etc.), y
- 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>
</tool_usage_guidelines>
<python_guidelines>
When executing Python code:
<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
**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\`
**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>\`
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>
**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>
<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>
<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
<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>
@@ -1,7 +1,25 @@
/**
* Types for Cloud Code Interpreter tool states
* These types represent the state returned by each tool after execution
* API names for Cloud Code Interpreter tool
*/
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',
} as const;
export type CodeInterpreterApiNameType =
(typeof CodeInterpreterApiName)[keyof typeof CodeInterpreterApiName];
// ==================== File Operations ====================
@@ -1,3 +1,4 @@
import { CodeInterpreterIdentifier } from '@lobechat/builtin-tool-code-interpreter';
import {
type CodeInterpreterFileItem,
type CodeInterpreterParams,
@@ -15,7 +16,6 @@ import { pythonService } from '@/services/python';
import { dbMessageSelectors } from '@/store/chat/selectors';
import { type ChatStore } from '@/store/chat/store';
import { useFileStore } from '@/store/file';
import { CodeInterpreterIdentifier } from '@/tools/code-interpreter';
import { setNamespace } from '@/utils/storeDebug';
const n = setNamespace('codeInterpreter');
@@ -1,4 +1,5 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
import { CodeInterpreterIdentifier, type ExportFileState } from '@lobechat/builtin-tool-code-interpreter';
import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
import { type ChatToolPayload, type RuntimeStepContext } from '@lobechat/types';
import { PluginErrorType } from '@lobehub/chat-plugin-sdk';
@@ -16,8 +17,6 @@ import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation';
import { type ChatStore } from '@/store/chat/store';
import { useToolStore } from '@/store/tool';
import { hasExecutor } from '@/store/tool/slices/builtin/executors';
import { CodeInterpreterIdentifier } from '@/tools/code-interpreter';
import { type ExportFileState } from '@/tools/code-interpreter/type';
import { safeParseJSON } from '@/utils/safeParseJSON';
import { dbMessageSelectors } from '../../message/selectors';
@@ -289,7 +288,7 @@ export const pluginTypes: StateCreator<
try {
// Import ExecutionRuntime dynamically to avoid circular dependencies
const { CodeInterpreterExecutionRuntime } =
await import('@/tools/code-interpreter/ExecutionRuntime');
await import('@lobechat/builtin-tool-code-interpreter/executionRuntime');
// Create runtime with context
const runtime = new CodeInterpreterExecutionRuntime({
+1 -1
View File
@@ -1,4 +1,5 @@
import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';
import { CodeInterpreterManifest } from '@lobechat/builtin-tool-code-interpreter';
import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';
import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
import { GTDManifest } from '@lobechat/builtin-tool-gtd';
@@ -9,7 +10,6 @@ import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { ArtifactsManifest } from './artifacts';
import { CodeInterpreterManifest } from './code-interpreter';
import { KnowledgeBaseManifest } from './knowledge-base';
export const builtinToolIdentifiers: string[] = [
+1 -1
View File
@@ -1,4 +1,5 @@
import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';
import { CodeInterpreterManifest } from '@lobechat/builtin-tool-code-interpreter';
import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';
import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
import { GTDManifest } from '@lobechat/builtin-tool-gtd';
@@ -11,7 +12,6 @@ import { isDesktop } from '@lobechat/const';
import { type LobeBuiltinTool } from '@lobechat/types';
import { ArtifactsManifest } from './artifacts';
import { CodeInterpreterManifest } from './code-interpreter';
import { KnowledgeBaseManifest } from './knowledge-base';
export const builtinTools: LobeBuiltinTool[] = [
+4 -2
View File
@@ -1,3 +1,7 @@
import {
CodeInterpreterIdentifier,
CodeInterpreterInspectors,
} from '@lobechat/builtin-tool-code-interpreter/client';
import {
GroupManagementInspectors,
GroupManagementManifest,
@@ -11,8 +15,6 @@ import {
} from '@lobechat/builtin-tool-web-browsing/client';
import { type BuiltinInspector } from '@lobechat/types';
import { CodeInterpreterInspectors } from './code-interpreter/Inspector';
import { CodeInterpreterIdentifier } from './code-interpreter/index';
import { LocalSystemInspectors } from './local-system/Inspector';
/**
+3 -3
View File
@@ -2,6 +2,8 @@ import {
AgentBuilderInterventions,
AgentBuilderManifest,
} from '@lobechat/builtin-tool-agent-builder/client';
import { CodeInterpreterManifest } from '@lobechat/builtin-tool-code-interpreter';
import { CodeInterpreterInterventions } from '@lobechat/builtin-tool-code-interpreter/client';
import {
GroupManagementInterventions,
GroupManagementManifest,
@@ -12,8 +14,6 @@ import { NotebookManifest } from '@lobechat/builtin-tool-notebook';
import { NotebookInterventions } from '@lobechat/builtin-tool-notebook/client';
import { type BuiltinIntervention } from '@lobechat/types';
import { CodeInterpreterManifest as CloudCodeInterpreterManifest } from './code-interpreter';
import { CodeInterpreterInterventions } from './code-interpreter/Intervention';
import { LocalSystemInterventions } from './local-system/Intervention';
/**
@@ -23,7 +23,7 @@ import { LocalSystemInterventions } from './local-system/Intervention';
*/
export const BuiltinToolInterventions: Record<string, Record<string, any>> = {
[AgentBuilderManifest.identifier]: AgentBuilderInterventions,
[CloudCodeInterpreterManifest.identifier]: CodeInterpreterInterventions,
[CodeInterpreterManifest.identifier]: CodeInterpreterInterventions,
[GroupManagementManifest.identifier]: GroupManagementInterventions,
[GTDManifest.identifier]: GTDInterventions,
[LocalSystemManifest.identifier]: LocalSystemInterventions,
+3 -3
View File
@@ -1,6 +1,9 @@
// agent-builder
import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';
import { AgentBuilderRenders } from '@lobechat/builtin-tool-agent-builder/client';
// code-interpreter
import { CodeInterpreterManifest } from '@lobechat/builtin-tool-code-interpreter';
import { CodeInterpreterRenders } from '@lobechat/builtin-tool-code-interpreter/client';
// group-management
import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
import { GroupManagementRenders } from '@lobechat/builtin-tool-group-management/client';
@@ -16,9 +19,6 @@ import {
} from '@lobechat/builtin-tool-web-browsing/client';
import { type BuiltinRender } from '@lobechat/types';
// code-interpreter
import { CodeInterpreterManifest } from './code-interpreter';
import { CodeInterpreterRenders } from './code-interpreter/Render';
// knowledge-base
import { KnowledgeBaseManifest } from './knowledge-base';
import { KnowledgeBaseRenders } from './knowledge-base/Render';
+4 -2
View File
@@ -1,3 +1,7 @@
import {
CodeInterpreterIdentifier,
CodeInterpreterStreamings,
} from '@lobechat/builtin-tool-code-interpreter/client';
import {
GroupManagementManifest,
GroupManagementStreamings,
@@ -6,8 +10,6 @@ import { GTDManifest, GTDStreamings } from '@lobechat/builtin-tool-gtd/client';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { type BuiltinStreaming } from '@lobechat/types';
import { CodeInterpreterIdentifier } from './code-interpreter';
import { CodeInterpreterStreamings } from './code-interpreter/Streaming';
import { LocalSystemStreamings } from './local-system/Streaming';
/**