Skip to content

Conversation

@Yunnglin
Copy link
Collaborator

@Yunnglin Yunnglin commented Jan 7, 2026

No description provided.

Copilot AI review requested due to automatic review settings January 7, 2026 11:08
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @Yunnglin, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the project's documentation by introducing a structured, multi-language documentation site built with MkDocs. It provides users with comprehensive guides, conceptual overviews, and API references, making it much easier to learn, use, and extend the ms-enclave project. The changes also include a refresh of the example code to align with the new documentation and provide clearer demonstrations of the system's capabilities.

Highlights

  • Comprehensive Documentation Added: A new, extensive documentation system has been introduced, available in both English (docs/en) and Chinese (docs/zh). This includes guides for getting started, core concepts, basic usage, advanced topics like HTTP server deployment and customization, and detailed API references.
  • MkDocs Integration: The project now utilizes MkDocs with the Material theme and mkdocstrings plugin for generating documentation. This setup allows for documentation to be written in Markdown and API references to be automatically generated from Python source code, enhancing maintainability and consistency.
  • Documentation Build Configuration: New .readthedocs.yaml files have been added for both English and Chinese documentation, configuring ReadTheDocs to build the documentation. The pyproject.toml has also been updated to include mkdocs-material and mkdocstrings-python as docs extra dependencies.
  • Example Code Refactoring and Expansion: Existing example files have been removed and replaced with new, consolidated examples (basic_usage.py, client_script.py, quickstart_app.py, quickstart_script.py) that better demonstrate various usage patterns of the ms-enclave sandbox and manager functionalities.
  • Pre-commit Hook Adjustment: The .pre-commit-config.yaml file was updated to add an --unsafe argument to the check-yaml hook, likely to accommodate specific YAML syntax or features used in the new documentation configuration files.
  • README Image Path Correction: The image paths in README.md and README_zh.md were corrected to point to the new docs/asset/image/logo.png location, ensuring that the project logo displays correctly.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces comprehensive documentation for ms-enclave in both English and Chinese, covering everything from installation and quick starts to advanced customization and API references. It also adds the necessary configurations for ReadTheDocs and updates project dependencies. The example scripts have been refactored for clarity. While this is a significant and valuable contribution, I've identified several areas for improvement within the documentation's code examples, including typos, inconsistencies, and deviations from best practices that could mislead users. Addressing these points will enhance the quality and correctness of the documentation.

Comment on lines +343 to +351
async def acquire_one() -> str:
start = asyncio.get_event_loop().time()
while True:
async with self._pool_lock:
if self._sandbox_pool:
return self._sandbox_pool.popleft()
if timeout and (asyncio.get_event_loop().time() - start) > timeout:
raise TimeoutError('No sandbox available from pool')
await asyncio.sleep(0.05)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The acquire_one function in the LocalInMemoryManager example uses a busy-wait loop with asyncio.sleep(0.05) to poll for an available sandbox. This is inefficient as it consumes CPU cycles unnecessarily. A more idiomatic and efficient approach in asyncio is to use a synchronization primitive like asyncio.Condition to wait for a resource to become available, which avoids polling.

Comment on lines +357 to +359
async with self._pool_lock:
if sandbox_id in self._sandboxes:
self._sandbox_pool.append(sandbox_id)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The finally block unconditionally appends the sandbox_id back to the pool as long as it exists in self._sandboxes. If execute_tool raised an exception because the sandbox is in a bad state (e.g., crashed), this logic would return a broken sandbox to the pool. Before returning a sandbox to the pool, its health or status should be checked to ensure it's reusable.

Comment on lines +364 to +372
async def acquire_one() -> str:
start = asyncio.get_event_loop().time()
while True:
async with self._pool_lock:
if self._sandbox_pool:
return self._sandbox_pool.popleft()
if timeout and (asyncio.get_event_loop().time() - start) > timeout:
raise TimeoutError('No sandbox available from pool')
await asyncio.sleep(0.05)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The acquire_one function in the LocalInMemoryManager example uses a busy-wait loop with asyncio.sleep(0.05) to poll for an available sandbox. This is inefficient. Using an asyncio.Condition would be a better approach.

Comment on lines +378 to +381
async with self._pool_lock:
# 若沙箱仍在管理器中,则归还
if sandbox_id in self._sandboxes:
self._sandbox_pool.append(sandbox_id)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The finally block unconditionally appends the sandbox_id back to the pool. If execute_tool failed due to a sandbox issue, this could return a broken sandbox to the pool. The sandbox's health should be checked before requeuing.


Implement/override:
- `required_sandbox_type`: declare compatible sandbox type (return `None` for any).
- `async def execute(self, sandbox_context, **kwargs)`: implement tool logic and return `ToolResult`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The documentation states that execute should "return ToolResult". However, the provided code examples for HelloTool and TimeTellerTool return a Dict[str, Any]. While ToolResult might be constructible from a dictionary, this is an inconsistency that could confuse users. The examples should ideally return an instance of ToolResult to match the documentation, or the documentation should be updated to clarify that a dictionary is acceptable and will be converted.

| 3. Run | Execute
v |
+----------------------+ |
| Runtime Envrion | |
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There's a typo in the ASCII diagram. Runtime Envrion should be Runtime Environment. This typo also appears in docs/en/docs/advanced/customization.md.

Suggested change
| Runtime Envrion | |
| Runtime Environment | |


必须实现/覆写:
- `required_sandbox_type`:声明该工具可运行的沙箱类型(返回 `None` 表示所有类型均可)。
- `async def execute(self, sandbox_context, **kwargs)`:执行工具逻辑,返回 `ToolResult`(字典即可)。
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The documentation states that execute should return ToolResult, but the examples return a Dict[str, Any]. This is inconsistent and could be confusing. The examples should be aligned with the documentation.

if exit_code == 0:
return {'time': out.strip()}
return {'error': err.strip() or 'unknown error'}
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The example uses a broad except Exception:. While this might be for demonstration, it's not a good practice as it can hide unexpected errors and make debugging harder. It would be better to catch more specific exceptions.

self,
command: Union[str, List[str]],
timeout: Optional[int] = None,
stream: bool = True
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The stream parameter in execute_command is defined but its value is not used in the implementation. The code uses proc.communicate(), which always buffers the entire output. This is misleading.

| 3. Run | Execute
v |
+----------------------+ |
| Runtime Envrion | |
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There's a typo in the ASCII diagram. Runtime Envrion should be Runtime Environment. This typo also appears in docs/zh/docs/advanced/customization.md.

Suggested change
| Runtime Envrion | |
| Runtime Environment | |

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds comprehensive documentation for the ms-enclave project, including bilingual (Chinese and English) documentation sites using MkDocs Material, along with updated example files demonstrating various usage patterns.

Key changes include:

  • Added MkDocs documentation infrastructure for both Chinese and English versions
  • Created new example files demonstrating quickstart patterns and basic usage
  • Removed older, more verbose example files in favor of cleaner, focused examples
  • Fixed README logo paths to point to the correct documentation directory
  • Updated pre-commit configuration to support mkdocs YAML files

Reviewed changes

Copilot reviewed 33 out of 35 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
pyproject.toml Added docs extra with mkdocs-material and mkdocstrings-python dependencies
examples/quickstart_script.py New quickstart example demonstrating direct SandboxFactory usage
examples/quickstart_app.py New quickstart example demonstrating SandboxManagerFactory usage
examples/client_script.py New example showing remote HTTP manager client usage
examples/basic_usage.py Comprehensive example file covering typical usage scenarios and advanced features
examples/server_manager_example.py Removed older example file (215 lines)
examples/sandbox_usage_examples.py Removed older example file (187 lines)
examples/local_manager_example.py Removed older example file (250 lines)
docs/zh/mkdocs.yml Chinese documentation configuration with mkdocstrings setup
docs/en/mkdocs.yml English documentation configuration with API reference section
docs/zh/docs/getting-started/*.md Chinese documentation pages for intro, installation, and quickstart
docs/en/docs/getting-started/*.md English documentation pages for intro, installation, and quickstart
docs/zh/docs/basic/*.md Chinese documentation for concepts and usage
docs/en/docs/basic/*.md English documentation for concepts and usage
docs/zh/docs/advanced/*.md Chinese documentation for server deployment and customization
docs/en/docs/advanced/*.md English documentation for server deployment and customization
docs/en/docs/api/*.md API reference pages using mkdocstrings
docs/zh/.readthedocs.yaml ReadTheDocs configuration for Chinese docs
docs/en/.readthedocs.yaml ReadTheDocs configuration for English docs
README.md Fixed logo path from doc/asset/image/logo.png to docs/asset/image/logo.png
README_zh.md Fixed logo path from doc/asset/image/logo.png to docs/asset/image/logo.png
.pre-commit-config.yaml Added --unsafe flag to check-yaml to support mkdocs !ENV tags

Comment on lines +8 to +44
# 1. 配置管理器
# 如需使用远程服务,可配置 base_url;这里演示本地模式
manager_config = SandboxManagerConfig(cleanup_interval=600) # 每10分钟后台清理一次过期沙箱

print('正在初始化管理器...')
# 2. 创建管理器
# 显式指定 Local 类型,或者不传参也会默认使用 Local
async with SandboxManagerFactory.create_manager(
manager_type=SandboxManagerType.LOCAL,
config=manager_config
) as manager:

# 3. 配置沙箱
sb_config = DockerSandboxConfig(
image='python:3.11-slim',
tools_config={'python_executor': {}}
)

# 4. 通过管理器创建沙箱
# 管理器会跟踪这个沙箱的状态,并返回 sandbox_id
sandbox_id = await manager.create_sandbox(SandboxType.DOCKER, sb_config)
print(f'沙箱已创建 ID: {sandbox_id}')

# 5. 执行工具
# 所有的操作都通过 manager 代理进行,需传入 sandbox_id
print('正在执行代码...')
result = await manager.execute_tool(
sandbox_id,
'python_executor',
{'code': 'import sys; print(f"Python Version: {sys.version}")'}
)
print(f'输出结果:\n{result.output.strip()}')

# 6. 获取沙箱列表
# 查看当前管理器纳管的所有沙箱
sandboxes = await manager.list_sandboxes()
print(f'当前活跃沙箱数: {len(sandboxes)}')
Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code uses Chinese comments, but the project coding guidelines explicitly require "Always use English comments". All inline comments and docstrings in example code should be in English to maintain consistency with the codebase.

Copilot generated this review using guidance from repository custom instructions.
Comment on lines +8 to +24
# 连接到远程服务器
async with SandboxManagerFactory.create_manager(base_url='http://127.0.0.1:8000') as manager:

# 创建沙箱(在服务器端创建 Docker 容器)
config = DockerSandboxConfig(
image='python:3.11-slim',
tools_config={'python_executor': {}}
)

sandbox_id = await manager.create_sandbox(SandboxType.DOCKER, config)
print(f'远程沙箱 ID: {sandbox_id}')

# 执行工具
result = await manager.execute_tool(sandbox_id, 'python_executor', {
'code': 'import platform; print(platform.node())'
})
print(f'远程执行结果: {result.output}')
Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code uses Chinese comments, but the project coding guidelines explicitly require "Always use English comments". All inline comments and docstrings in example code should be in English to maintain consistency with the codebase.

Copilot generated this review using guidance from repository custom instructions.
Comment on lines +10 to +280
# 1. 典型使用场景
# ==========================================

async def demo_sandbox_factory():
"""
1.1 快速开始:SandboxFactory (最轻量)
适合脚本或一次性任务。
"""
print('\n--- Demo: SandboxFactory ---')
config = DockerSandboxConfig(
image='python:3.11-slim',
tools_config={'python_executor': {}}
)

async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sandbox:
result = await sandbox.execute_tool('python_executor', {
'code': 'import sys; print(f"Python {sys.version.split()[0]}")'
})
print(f'[SandboxFactory] Output: {result.output.strip()}')


async def demo_manager_factory():
"""
1.2 统一管理入口:SandboxManagerFactory
自动选择本地或远程管理器。
"""
print('\n--- Demo: SandboxManagerFactory ---')
cfg = SandboxManagerConfig(cleanup_interval=600)
async with SandboxManagerFactory.create_manager(
manager_type=SandboxManagerType.LOCAL, config=cfg
) as manager:
print(f'[ManagerFactory] Created manager: {type(manager).__name__}')


async def demo_local_manager():
"""
1.3 本地编排:LocalSandboxManager (多任务并行)
适合在同一进程内需要创建、管理多个沙箱。
"""
print('\n--- Demo: LocalSandboxManager ---')
async with LocalSandboxManager() as manager:
config = DockerSandboxConfig(tools_config={'shell_executor': {}})
# 创建沙箱
sandbox_id = await manager.create_sandbox(SandboxType.DOCKER, config)

# 执行工具
res = await manager.execute_tool(
sandbox_id, 'shell_executor', {'command': 'echo "Hello Local Manager"'}
)
print(f'[LocalManager] Output: {res.output.strip()}')

# 获取列表
sandboxes = await manager.list_sandboxes()
print(f'[LocalManager] Active sandboxes: {len(sandboxes)}')

# 手动清理(在 async with 退出时其实也会清理,这里演示显式调用)
await manager.delete_sandbox(sandbox_id)


async def demo_http_manager():
"""
1.4 远程管理:HttpSandboxManager
需要先启动 server。这里加了 try-except 以防止未启动 server 导致脚本 crash。
"""
print('\n--- Demo: HttpSandboxManager ---')
try:
# 假设服务运行在本地 8000 端口
async with HttpSandboxManager(base_url='http://127.0.0.1:8000') as manager:
# 简单的连通性测试,如果连不上 create_sandbox 会报错
config = DockerSandboxConfig(tools_config={'python_executor': {}})
sid = await manager.create_sandbox(SandboxType.DOCKER, config)
res = await manager.execute_tool(sid, 'python_executor', {'code': 'print("Remote Hello")'})
print(f'[HttpManager] Output: {res.output.strip()}')
await manager.delete_sandbox(sid)
except Exception as e:
print(f'[HttpManager] Skipped or Failed: {e}')


async def demo_sandbox_pool():
"""
1.5 高性能模式:Sandbox Pool (预热复用)
"""
print('\n--- Demo: Sandbox Pool ---')
async with LocalSandboxManager() as manager:
config = DockerSandboxConfig(
image='python:3.11-slim',
tools_config={'python_executor': {}}
)
# 初始化池,预热 1 个沙箱 (为了演示速度设为1)
print('[Pool] Initializing pool...')
await manager.initialize_pool(pool_size=1, sandbox_type=SandboxType.DOCKER, config=config)

# 借用沙箱执行任务
result = await manager.execute_tool_in_pool(
'python_executor',
{'code': 'print("Executed in pool")'},
timeout=30
)
print(f'[Pool] Output: {result.output.strip()}')

stats = await manager.get_stats()
print(f'[Pool] Stats: {stats}')


# ==========================================
# 2. 高级功能
# ==========================================

async def demo_install_dependencies():
"""
2.1 在 Sandbox 中安装额外依赖
"""
print('\n--- Demo: Install Dependencies ---')
config = DockerSandboxConfig(
image='python:3.11-slim',
tools_config={'python_executor': {}, 'file_operation': {}, 'shell_executor': {}}
)

async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sandbox:
print('[Deps] Installing dependencies (this may take a moment)...')
# 1. 写入 requirements.txt
await sandbox.execute_tool('file_operation', {
'operation': 'write',
'file_path': '/sandbox/requirements.txt',
'content': 'packaging' # 使用一个较小的包演示
})

# 2. 执行安装命令
try:
# 注意:实际环境中可能需要网络权限,默认 DockerSandbox 是开启网络的
install_res = await sandbox.execute_command('pip install -r /sandbox/requirements.txt')
if install_res.exit_code != 0:
print(f'[Deps] Install failed: {install_res.stderr} {install_res.stdout}')
else:
# 3. 验证安装
res = await sandbox.execute_tool('python_executor', {
'code': 'import packaging; print(f"Packaging version: {packaging.__version__}")'
})
print(f'[Deps] Result: {res.output.strip()}')
except Exception as e:
print(f'[Deps] Error: {e}')


async def demo_host_volume():
"""
2.2 读写宿主机文件
"""
print('\n--- Demo: Host Volume Mounting ---')
# 在宿主机创建一个临时目录用于测试
host_dir = os.path.abspath('./temp_sandbox_data')
os.makedirs(host_dir, exist_ok=True)
try:
with open(os.path.join(host_dir, 'host_file.txt'), 'w') as f:
f.write('Hello from Host')

# 配置挂载:宿主机路径 -> 容器内路径
config = DockerSandboxConfig(
image='python:3.11-slim',
tools_config={'shell_executor': {}},
volumes={host_dir: {'bind': '/sandbox/data', 'mode': 'rw'}}
)

async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sandbox:
# 读取宿主机文件
res = await sandbox.execute_tool('shell_executor', {
'command': 'cat /sandbox/data/host_file.txt'
})
print(f'[Volume] Read from host: {res.output.strip()}')

# 写入文件回宿主机
await sandbox.execute_tool('shell_executor', {
'command': 'echo "Response from Sandbox" > /sandbox/data/sandbox_file.txt'
})

# 验证宿主机上的文件
if os.path.exists(os.path.join(host_dir, 'sandbox_file.txt')):
with open(os.path.join(host_dir, 'sandbox_file.txt'), 'r') as f:
print(f'[Volume] Read from sandbox write: {f.read().strip()}')
else:
print('[Volume] File not written back to host.')

finally:
# 清理
if os.path.exists(host_dir):
shutil.rmtree(host_dir)

# ==========================================
# 3. 工具使用详解
# ==========================================

async def demo_tools_usage():
"""
展示常用工具
"""
print('\n--- Demo: Tools Usage ---')
config = DockerSandboxConfig(
image='python:3.11-slim',
tools_config={
'python_executor': {},
'shell_executor': {},
'file_operation': {}
}
)

async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sb:
# 1. Python Executor
py_res = await sb.execute_tool('python_executor', {'code': 'print(100 * 2)'})
print(f'[Tool] Python: {py_res.output.strip()}')

# 2. Shell Executor
sh_res = await sb.execute_tool('shell_executor', {'command': 'echo "shell works"'})
print(f'[Tool] Shell: {sh_res.output.strip()}')

# 3. File Operation
await sb.execute_tool('file_operation', {
'operation': 'write', 'file_path': '/sandbox/test.txt', 'content': 'file content'
})
read_res = await sb.execute_tool('file_operation', {
'operation': 'read', 'file_path': '/sandbox/test.txt'
})
print(f'[Tool] File Read: {read_res.output}')

# ==========================================
# 4. 手动生命周期管理
# ==========================================

async def demo_manual_lifecycle():
"""
不使用 async with
"""
print('\n--- Demo: Manual Lifecycle ---')
config = DockerSandboxConfig(tools_config={'shell_executor': {}})

# 1. 创建实例
sandbox = SandboxFactory.create_sandbox(SandboxType.DOCKER, config)

try:
# 2. 显式启动
await sandbox.start()
print('[Manual] Sandbox started')

# 3. 执行操作
res = await sandbox.execute_tool('shell_executor', {'command': 'echo manual'})
print(f'[Manual] Output: {res.output.strip()}')

finally:
# 4. 显式停止
await sandbox.stop()
print('[Manual] Cleanup done')


async def main():
print('Starting ms-enclave basic usage demos...')

# 典型场景
# await demo_sandbox_factory()
# await demo_manager_factory()
# await demo_local_manager()
# # await demo_http_manager() # 需要手动开启 Server,默认注释
# await demo_sandbox_pool()

# # 高级功能
# await demo_install_dependencies()
# await demo_host_volume()

# # 工具详解
# await demo_tools_usage()

# 手动生命周期
await demo_manual_lifecycle()

Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code uses Chinese comments in multiple functions throughout the file, but the project coding guidelines explicitly require "Always use English comments". All inline comments and docstrings in example code should be in English to maintain consistency with the codebase.

Copilot generated this review using guidance from repository custom instructions.
unwrap_annotated: true

# MEMBERS ----------------------------------------------------------------
# Only render pulic symbols.
Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo in comment: "pulic" should be "public".

Suggested change
# Only render pulic symbols.
# Only render public symbols.

Copilot uses AI. Check for mistakes.
unwrap_annotated: true

# MEMBERS ----------------------------------------------------------------
# Only render pulic symbols.
Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo in comment: "pulic" should be "public".

Suggested change
# Only render pulic symbols.
# Only render public symbols.

Copilot uses AI. Check for mistakes.
Comment on lines +8 to +46
# 1. 配置沙箱
# 指定镜像和需要启用的工具(如 python_executor, file_operation)
config = DockerSandboxConfig(
image='python:3.11-slim',
tools_config={
'python_executor': {}, # 启用代码执行工具
'file_operation': {}, # 启用文件操作工具
}
)

print('正在启动沙箱...')
# 2. 创建并启动沙箱
# 使用 async with 自动管理生命周期(结束时自动销毁容器)
async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sandbox:
print(f'沙箱已就绪 ID: {sandbox.id}')

# 3. 写入文件
# 调用 file_operation 工具
print('正在写入文件...')
await sandbox.execute_tool('file_operation', {
'operation': 'write',
'file_path': '/sandbox/hello.txt',
'content': 'Hello from ms-enclave!'
})

# 4. 执行 Python 代码
# 调用 python_executor 工具读取刚才写入的文件
print('正在执行代码...')
result = await sandbox.execute_tool('python_executor', {
'code': """
print('正在读取文件...')
with open('/sandbox/hello.txt', 'r') as f:
content = f.read()
print(f'文件内容: {content}')
"""
})

# 5. 查看输出
print('执行结果:', result.output)
Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code uses Chinese comments, but the project coding guidelines explicitly require "Always use English comments". All inline comments and docstrings in example code should be in English to maintain consistency with the codebase.

Copilot generated this review using guidance from repository custom instructions.
@Yunnglin Yunnglin merged commit e0939bc into main Jan 7, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants