Files
zhenxun_bot/zhenxun/services/ai/sandbox/protocols.py
T
922d092650 ♻️ refactor(core): 重构 AI 能力与定时任务调度系统 (#2148)
* ♻️ refactor(core): 重构 AI 能力与定时任务调度系统

- 【AI 能力与工具】重构 Capability 注册与管理机制,引入 CapabilityManager 统一管理
- 移除全局能力注册表,改用声明式装饰器 `@capability` 进行解耦注册
- 重构工具解析器链,使用统一的 BaseToolResolver 代替原有的多个特定解析器
- 增强工具查询过滤,支持通配符匹配、工具箱过滤和排除标签
- 【定时任务调度】重构定时任务管理器,引入 SchedulerRegistry 统一管理任务元数据
- 引入 JobConfig 聚合定时任务配置,支持用户维度的定时任务调度
- 重构执行分发器,支持并发限制、串行间隔和随机延迟打散
- 【运行上下文】引入 ScheduledDeps 以支持后台和定时任务环境下的依赖注入
- 优化 RunContext,支持从定时任务上下文快速构造,并提供 emit 辅助方法
- 【日志与监控】引入 AILoggerProxy,实现 AI 各模块的专属日志输出
- 将各模块的全局 logger 替换为对应的模块专属日志代理
- 【其他优化】修复 Pydantic V1 兼容层中 model_validator 的装饰器兼容性问题
- 在非交互式环境(如定时任务)中自动隐藏 HITL 交互工具以节省 Token

* ♻️ refactor(core): 优化内部导入路径并提升 Pydantic 兼容性

- 【重构】将 `services/ai` 模块内的绝对导入重构为相对导入,优化包结构
- 【重构】移除不必要的 `if TYPE_CHECKING` 保护,通过 `from __future__ import annotations` 直接导入类型
- 【清理】清理 `core/messages/types.py` 中未使用的 `AssistantContentUnion` 等联合类型定义
- 【优化】在 `utils/pydantic_compat.py` 中新增 `model_rebuild` 兼容函数,统一 Pydantic V1/V2 的模型重建逻辑
- 【优化】将部分函数内部的延迟导入提升至模块顶部,规范代码结构

* ♻️ refactor(imports): 优化导入路径为相对导入并清理冗余导入

- 【重构】将 AI 服务相关模块中的绝对导入路径修改为相对导入,提升模块内聚性与可移植性
- 【清理】移除多处函数内部或类方法中未使用的冗余导入,避免循环引用和资源浪费
- 【格式化】微调部分工具装饰器和返回语句的格式与尾随逗号

* 🚨 auto fix by pre-commit hooks

---------

Co-authored-by: webjoin111 <455457521@qq.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-07-10 09:14:06 +08:00

190 lines
5.2 KiB
Python

from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable
from contextlib import AbstractAsyncContextManager
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Protocol, runtime_checkable
from .models import SandboxExecutionResult
class InteractiveTerminalSession(Protocol):
@abstractmethod
async def start(self, cmd: str, env: dict[str, str] | None = None) -> None:
"""启动并挂载终端会话"""
...
@abstractmethod
async def send_input(self, text: str) -> None:
"""向终端发送标准输入"""
...
@abstractmethod
async def read_output(self, timeout: int = 5) -> str:
"""读取当前终端屏幕输出画面"""
...
@abstractmethod
async def interrupt(self) -> None:
"""发送强制中断信号(Ctrl+C)"""
...
@abstractmethod
async def close(self) -> None:
"""释放并关闭终端资源"""
...
@runtime_checkable
class SupportsCommandExecution(Protocol):
async def run_process(
self,
command: str | list[str],
cwd: str | None = None,
timeout: float | None = None,
env: dict[str, str] | None = None,
on_output: Callable[[str, bytes], Awaitable[None]] | None = None,
) -> SandboxExecutionResult:
"""在沙箱内单次执行短命令并获取结果"""
...
@runtime_checkable
class SandboxProcessStream(Protocol):
@abstractmethod
async def read(self) -> "ProcessStreamMessage | None":
"""异步读取下一块输出流数据"""
...
@abstractmethod
async def write(self, data: bytes) -> None:
"""异步写入数据到进程标准输入"""
...
@abstractmethod
async def close(self) -> None:
"""关闭并终止输入输出流"""
...
@runtime_checkable
class SupportsStreamExecution(Protocol):
@abstractmethod
def create_stream_process(
self,
command: str | list[str],
cwd: str | None = None,
env: dict[str, str] | None = None,
) -> AbstractAsyncContextManager[SandboxProcessStream]:
"""创建持久流式后台进程,供长连接通信"""
...
@runtime_checkable
class SupportsInteractivePTY(Protocol):
async def create_pty_session(self) -> InteractiveTerminalSession:
"""创建分配一个真实的伪终端(PTY)交互会话"""
...
@runtime_checkable
class SupportsFileSystem(Protocol):
async def write_raw_file(self, path: str | Path, content: str) -> bool:
"""使用字符串极速覆写文件"""
...
async def read_raw_file(self, path: str | Path) -> str:
"""直接读取文件内容为文本字符串"""
...
async def delete_raw_file(self, path: str | Path) -> bool:
"""直接删除指定物理文件"""
...
async def upload_raw_dir(
self, local_dir_path: str | Path, sandbox_target_path: str | Path
) -> bool:
"""将宿主机本地目录完整打包上传至沙箱"""
...
async def write(self, path: str | Path, data: bytes) -> bool:
"""底层二进制安全写入文件"""
...
async def read(self, path: str | Path) -> bytes:
"""底层二进制安全读取文件"""
...
async def rm(self, path: str | Path, recursive: bool = False) -> bool:
"""执行标准的 rm 删除操作"""
...
async def mkdir(self, path: str | Path, parents: bool = False) -> bool:
"""执行标准的 mkdir 创建目录操作"""
...
@runtime_checkable
class SupportsPortMapping(Protocol):
def get_meta(self, key: str, default: Any = None) -> Any:
"""获取沙箱驱动映射的底层元数据(如分配的随机端口)"""
...
class SandboxChannel(ABC):
@abstractmethod
def get_meta(self, key: str, default: Any = None) -> Any:
"""获取沙箱会话的底层元数据字典"""
...
class StatefulCodeClient(Protocol):
"""有状态代码执行客户端通信协议"""
@abstractmethod
async def execute(
self,
code: str,
timeout: int = 30,
on_output: Callable[[str, bytes], Awaitable[None]] | None = None,
) -> SandboxExecutionResult:
"""执行指定代码并获取结果"""
...
@abstractmethod
async def interrupt(self) -> None:
"""发送强制中断信号(模拟Ctrl+C)"""
...
@abstractmethod
async def close(self) -> None:
"""关闭底层网络及进程连接"""
...
class BaseEngineManager(Protocol):
"""沙箱后台引擎生命周期管理器协议"""
@abstractmethod
async def ensure_started(self, env_vars: dict[str, str] | None = None) -> None:
"""确保后台引擎主服务已在沙箱中成功启动"""
...
@abstractmethod
async def get_client(self, kernel_name: str) -> StatefulCodeClient:
"""分配并获取指定语言内核的通信客户端"""
...
@abstractmethod
async def close(self) -> None:
"""安全关闭引擎并回收所有分配的客户端资源"""
...
@dataclass
class ProcessStreamMessage:
"""统一的进程流消息载体"""
stream_type: int
data: bytes