按《智能体系统需求文档 v1.1》实现。这一阶段打通了"内核数据 → 接口 → 界面"整条链路。 ## 内核 - 新增 agentdb.py:智能体系统的 SQLite 层(记忆 / 情绪 / Token 统计 / Skill 绑定)。 **为什么这次用 SQLite 而别处还是 JSON**(store.py 顶上写着 JSON 的理由): 记忆是"条目无上限 + 每轮全量注入 + 要 LIKE 检索 + 要行级改删", 那三条都指向 SQLite;而设置/会话/智能体的量级仍然是"几个到几十个"、 且要人肉可读,继续留在 JSON。分界线写在 agentdb.py 的文件头。 - 新增 agent_context.py:按需求附录 C 拼 system prompt (人设 → skills → worldview → emotion → memory → peer_emotions,**空段整段删掉**,每轮重拼)。 - 新增 agent_tools.py:7 个内置工具(memory_add/update/forget/search、 memory_suggest_summary、emotion_set、get_token_usage)。 走进程内实现是因为它们要读写 agent.db,而电脑端的文件工具是子进程。 共享记忆的写入限权(只能改自己写的)+ pinned 保护都在这里。 - 新增 agent_api.py:20+ 个 HTTP 接口(记忆 CRUD/导出导入/整理、情绪、 Token 用量、世界观/模型列表/Skill 的 CRUD 与包导入导出)。 app.py 的老 /api/agents 三个路由删掉,统一由它处理(顺便补上"内置不能删")。 - store.py:Agent 字段按类型分开的 _apply_agent_patch(create/update 共用)、 三种资源的通用 CRUD、create_agent 改用 **UUID**(需求附录 A)、 delete_agent 清理绑定关系但**不删记忆**。 - Token:usage 从"只留最后一轮"改成**累加**(多轮工具调用的消耗是大头, 以前全丢);落库时按轮记在消息上(会话级 = 加起来,重新生成不会虚高) + 计入智能体累计(按模型分桶、输入输出分开);超限时**发起前**拦住, 附一条带语气的告别消息并给界面明确的 token_limit 错误(需求 3.1)。 - 会议节点的 system prompt 也改用 agent_context(以前是自己拼的, 同一个智能体在会议里没有记忆/情绪/世界观)。 - doubao_entry:web_search.py 补进 BUNDLED_TOOL_FILES(对拍脚本抓出的清单不一致)。 ## 安卓 - AgentSelectScreen:智能体选择界面(需求第二章)—— 左列表 + 右侧四层叠加(背景/主体边框/角色图/介绍边框), 1.5s 四阶段切换动画(0.3 出 / 0.5 间隔 / 0.4 边框 / 0.3 入,方向按列表顺序, 连点立即打断并从当前视觉状态续走),圆形「更多」按钮,默认资源回退。 - AssetImage:本地图片显示。**不引 Coil/Glide**(项目零第三方依赖)—— PNG/JPG 走 BitmapFactory,GIF 走 ImageDecoder(API28+ 能播动图,以下退化成首帧), SVG 走 WebView(原生解不了)。 - TokenUsageScreen / MemoryScreen:用量详情(输入输出分列、按模型分行、 限额进度、配了单价才估费用)+ 记忆管理(情绪编辑、整理、导入导出、 pinned 开关、共享记忆提示)。 - Models.kt / KernelClient.kt / AppViewModel.kt:全部新字段与新接口。 - 入口:抽屉「智能体」→ 选择界面;聊天页顶栏点名字 → 选择界面 (以前点开的是「模型」面板 —— 那是"换脑子"不是"换人")。 - 需求文档给的两张默认资源图进 res/drawable(2.3MB)。 ## 验证 - 新增 scripts/probe-agent-system.py:11 节 60+ 项断言,**不装机**跑完整链路 (临时数据目录 + 假 Handler)。覆盖:UUID 主键、记忆增删改查检索、 pinned 保护、共享记忆与写入限权、system prompt 五段注入与顺序、 20 多个接口、包的导出导入边界(模型引用/世界观/限额**不进包**)、 记忆导入的合并去重、资源 CRUD。全绿。 - 装机验证:选择界面四层叠加、默认资源回退、切换动画与高亮。 ## 还没做(下一阶段) 世界观/Skill/模型列表的管理界面、对话页会话级用量显示、智能体编辑界面扩展 (介绍/外观/模型引用/世界观/限额/技能绑定)、包的导入导出界面、 幻觉调用检测、不支持 function calling 的兼容降级、Node 端跟上。
357 lines
14 KiB
Python
357 lines
14 KiB
Python
"""
|
||
内置工具:shell 与 python_run。
|
||
|
||
为什么要内置,而不是直接复用 tools/shell.py、tools/python_run.py:
|
||
* 那两个文件是"子进程 + 解释器"模型:`python tool.py --input x.json`,
|
||
安卓上根本没有独立的 python 可执行文件(唯一解释器就在 Kern 进程里),
|
||
所以必须把这两个能力做成进程内实现。
|
||
* 内置版本在工具发现阶段**优先于同名文件工具**(和"安卓端优先"的取舍一致),
|
||
用户在 tools/ 里放自己的 shell.py 也不会把内核搞挂。
|
||
|
||
安全说明:python_run 在**内核进程内** exec 用户代码,这是安卓端的必然取舍
|
||
(没有子进程可以隔离)。因此只保留超时(线程 + 放弃)和 stdout/stderr 捕获,
|
||
真正要沙箱只能靠 settings.security.mode = restricted 的白名单。
|
||
"""
|
||
|
||
import builtins
|
||
import contextlib
|
||
import importlib.util
|
||
import io
|
||
import os
|
||
import platform
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
import traceback
|
||
|
||
import paths
|
||
import timeouts
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 工具定义(与 tools/shell.py、tools/python_run.py 的 TOOL 完全一致,
|
||
# 这样模型看到的 description / parameters 在两端一模一样)
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
SHELL_TOOL = {
|
||
'name': 'shell',
|
||
'description': (
|
||
'在用户电脑/手机的终端里执行一条 shell 命令,返回退出码、标准输出和标准错误。'
|
||
'适合查看文件、跑脚本、装依赖、查系统信息。危险命令会被拦截。'
|
||
),
|
||
'parameters': {
|
||
'type': 'object',
|
||
'properties': {
|
||
'command': {'type': 'string', 'description': '要执行的命令,例如 ls -la 或 python --version'},
|
||
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||
'timeout': {
|
||
'type': 'number',
|
||
'description': '超时秒数。不传就用设置里「超时 → shell 命令」那个值',
|
||
},
|
||
},
|
||
'required': ['command'],
|
||
},
|
||
}
|
||
|
||
PYTHON_RUN_TOOL = {
|
||
'name': 'python_run',
|
||
'description': (
|
||
'运行一段 Python 代码或指定 .py 文件,返回标准输出/错误。'
|
||
'适合做计算、数据处理、调用网络接口(requests/httpx/urllib 可用)。'
|
||
'action=libs 可以查看当前环境装了哪些库。'
|
||
),
|
||
'parameters': {
|
||
'type': 'object',
|
||
'properties': {
|
||
'action': {
|
||
'type': 'string',
|
||
'enum': ['run', 'libs'],
|
||
'description': 'run=执行代码/文件(默认);libs=列出可用库',
|
||
},
|
||
'code': {'type': 'string', 'description': '要执行的 Python 代码(action=run 时二选一)'},
|
||
'file': {'type': 'string', 'description': '要执行的 .py 文件路径(action=run 时二选一)'},
|
||
'stdin': {'type': 'string', 'description': '传给脚本的标准输入,可留空'},
|
||
'timeout': {
|
||
'type': 'number',
|
||
'description': '超时秒数。不传就用设置里「超时 → 跑 Python 代码」那个值',
|
||
},
|
||
},
|
||
},
|
||
}
|
||
|
||
# 明显会搞坏机器的模式(可用 DOUBAO_SHELL_UNSAFE=1 关闭)
|
||
BLOCKED = [
|
||
'rm -rf /',
|
||
'rm -rf /*',
|
||
'mkfs',
|
||
'dd if=/dev/zero',
|
||
':(){:|:&};:',
|
||
'shutdown',
|
||
'reboot',
|
||
'format c:',
|
||
'del /f /s /q c:\\',
|
||
'rmdir /s /q c:\\',
|
||
]
|
||
|
||
# python_run action=libs 里检查的常用库
|
||
WATCHED = [
|
||
'requests', 'httpx', 'aiohttp', 'urllib3', 'bs4', 'lxml', 'pandas', 'numpy',
|
||
'PIL', 'openpyxl', 'docx', 'pptx', 'yaml', 'dotenv', 'mcp', 'flask', 'fastapi',
|
||
]
|
||
|
||
# 进程内 exec 会临时切换 cwd(Python 没有"给这段代码单独设 cwd"的机制),
|
||
# 加锁只是为了让切换尽量短,不能解决并发请求看到临时 cwd 的问题,故在此说明。
|
||
_cwd_lock = threading.Lock()
|
||
|
||
|
||
@contextlib.contextmanager
|
||
def _redirect_stdin(buffer):
|
||
"""标准库只有 redirect_stdout/redirect_stderr,没有 redirect_stdin,只能自己换。"""
|
||
saved = sys.stdin
|
||
sys.stdin = buffer
|
||
try:
|
||
yield buffer
|
||
finally:
|
||
sys.stdin = saved
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# shell
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def shell_run(args: dict) -> dict:
|
||
command = str(args.get('command') or '').strip()
|
||
if not command:
|
||
raise ValueError('command 不能为空')
|
||
if len(command) > 4000:
|
||
raise ValueError('命令过长')
|
||
|
||
if os.environ.get('DOUBAO_SHELL_UNSAFE') != '1':
|
||
lowered = command.lower()
|
||
for bad in BLOCKED:
|
||
if bad in lowered:
|
||
raise ValueError(f'命令命中黑名单({bad}),已拒绝执行。确实需要请设置 DOUBAO_SHELL_UNSAFE=1')
|
||
|
||
# 超时:模型传了就用它的,没传就用设置里的(设置 → 超时 → shell 命令)
|
||
timeout = timeouts.budget(args, 'shell')
|
||
cwd = args.get('cwd') or None
|
||
if cwd and not os.path.isdir(cwd):
|
||
raise ValueError(f'工作目录不存在:{cwd}')
|
||
|
||
if paths.IS_WINDOWS:
|
||
argv = ['cmd', '/c', command]
|
||
else:
|
||
# 安卓系统里 /bin/sh 通常存在(是 /system/bin/sh 的软链),没有就退回真实路径
|
||
shell = '/bin/sh' if os.path.exists('/bin/sh') else '/system/bin/sh'
|
||
argv = [shell, '-c', command]
|
||
|
||
try:
|
||
proc = subprocess.run(
|
||
argv,
|
||
cwd=cwd,
|
||
capture_output=True,
|
||
timeout=timeout,
|
||
text=True,
|
||
errors='replace',
|
||
)
|
||
except subprocess.TimeoutExpired:
|
||
return {'error': f'命令超时({timeout}s)', 'timeout': True}
|
||
except OSError as exc:
|
||
# 安卓上可能完全没有可执行权限/没有 shell,这里要给模型一个能读懂的原因
|
||
raise RuntimeError(f'无法启动命令({argv[0]}):{exc}') from exc
|
||
|
||
return {
|
||
'exit_code': proc.returncode,
|
||
'stdout': (proc.stdout or '')[-8000:],
|
||
'stderr': (proc.stderr or '')[-4000:],
|
||
'platform': f'{platform.system()} {platform.release()}',
|
||
}
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# python_run
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def _libs_report() -> dict:
|
||
available, missing = [], []
|
||
for name in WATCHED:
|
||
try:
|
||
found = importlib.util.find_spec(name) is not None
|
||
except (ImportError, ValueError):
|
||
found = False
|
||
(available if found else missing).append(name)
|
||
return {
|
||
'python': sys.version.split()[0],
|
||
'executable': sys.executable or '<进程内>',
|
||
'available': available,
|
||
'missing': missing,
|
||
'hint': '缺库时可以用 shell 工具执行 pip install <包名>' if missing else '常用库齐全',
|
||
}
|
||
|
||
|
||
def _exec_source(source: str, filename: str, cwd: str, stdin_text: str) -> tuple:
|
||
"""
|
||
在进程内执行 Python 源码,返回 (exit_code, stdout, stderr)。
|
||
|
||
- stdout/stderr 用 contextlib.redirect_* 捕获;
|
||
- sys.exit()/SystemExit 的 code 当作退出码;
|
||
- 其它异常打印完整 traceback 到 stderr(模型据此自我修正);
|
||
- cwd 临时切到脚本目录,跑完恢复(Python 没有更细粒度的办法)。
|
||
"""
|
||
out_buf, err_buf = io.StringIO(), io.StringIO()
|
||
namespace = {
|
||
'__name__': '__main__',
|
||
'__file__': filename,
|
||
'__builtins__': builtins,
|
||
'__doc__': None,
|
||
'__package__': None,
|
||
}
|
||
exit_code = 0
|
||
|
||
def _work():
|
||
nonlocal exit_code
|
||
try:
|
||
code_obj = compile(source, filename, 'exec')
|
||
except SyntaxError:
|
||
traceback.print_exc(file=err_buf)
|
||
exit_code = 1
|
||
return
|
||
try:
|
||
exec(code_obj, namespace) # noqa: S102 - 这就是本工具存在的意义
|
||
except SystemExit as exc:
|
||
value = exc.code
|
||
exit_code = 0 if value is None else (value if isinstance(value, int) else 1)
|
||
except BaseException: # noqa: BLE001 - 用户代码什么都能抛,包括 KeyboardInterrupt
|
||
traceback.print_exc(file=err_buf)
|
||
exit_code = 1
|
||
|
||
saved_cwd = os.getcwd()
|
||
changed = bool(cwd) and os.path.isdir(cwd) and os.path.abspath(cwd) != os.path.abspath(saved_cwd)
|
||
# 注意:redirect_stdout/stderr 和 chdir 都是"进程级"的(Python 没有线程级实现),
|
||
# 因此在同一进程里并发跑 python_run 时,另一个请求的 print 也可能被收进本次结果。
|
||
# 安卓上内核是单用户本地服务,这个代价可以接受;桌面/服务器场景请改用独立进程。
|
||
with contextlib.ExitStack() as stack:
|
||
stack.enter_context(contextlib.redirect_stdout(out_buf))
|
||
stack.enter_context(contextlib.redirect_stderr(err_buf))
|
||
# 标准库里没有 redirect_stdin(只有 stdout/stderr),只能自己换 sys.stdin:
|
||
# Node 版是靠子进程的 stdin 参数,安卓上没子进程,这里就是等价实现。
|
||
stack.enter_context(_redirect_stdin(io.StringIO(stdin_text or '')))
|
||
try:
|
||
if changed:
|
||
with _cwd_lock:
|
||
os.chdir(cwd)
|
||
_work()
|
||
finally:
|
||
if changed:
|
||
with _cwd_lock:
|
||
os.chdir(saved_cwd)
|
||
return exit_code, out_buf.getvalue(), err_buf.getvalue()
|
||
|
||
|
||
def run_with_timeout(fn, timeout_s: float):
|
||
"""
|
||
线程 + join(timeout) 实现超时。
|
||
|
||
为什么不用 signal.alarm / SIGALRM:安卓主线程之外信号不可用,
|
||
而且 CPython 根本杀不掉一个正在跑的线程。超时后我们只能"放弃等待",
|
||
被放弃的线程会继续在后台跑完(daemon 线程,不阻塞进程退出)。
|
||
这个取舍必须让用户知道,所以超时消息里写清楚。
|
||
|
||
★★ `timeout_s <= 0` = **不限时**(一直等到它跑完)。
|
||
|
||
给"停下来等用户"的那类工具用(`ask_user` / `show_ui` 的 wait 模式)——
|
||
它们的耗时**完全取决于用户什么时候点**,60 秒的上限只会造成:
|
||
弹窗还开着、用户 5 分钟后才选,而模型早就收到"工具执行超时"、
|
||
于是按自己猜的答案往下写了。
|
||
|
||
为什么默认仍然是 60 秒:这是"工具里写了死循环"的安全网
|
||
(不让整个内核跟着卡死)。会等用户的工具属于**设计上就该慢**,
|
||
由工具自己声明 `WAIT_FOR_USER = True` 来豁免,见 tools_runtime。
|
||
"""
|
||
box = {}
|
||
|
||
def worker():
|
||
try:
|
||
box['value'] = fn()
|
||
except BaseException as exc: # noqa: BLE001 - 转成错误对象回主线程
|
||
box['error'] = exc
|
||
|
||
thread = threading.Thread(target=worker, name='doubao-python-run', daemon=True)
|
||
thread.start()
|
||
if timeout_s and timeout_s > 0:
|
||
thread.join(timeout_s)
|
||
if thread.is_alive():
|
||
return None
|
||
else:
|
||
# 不限时:join() 不带参数就是一直等
|
||
thread.join()
|
||
if 'error' in box:
|
||
raise box['error']
|
||
return box.get('value')
|
||
|
||
|
||
def python_run(args: dict) -> dict:
|
||
action = str(args.get('action') or 'run').lower()
|
||
|
||
if action == 'libs':
|
||
return _libs_report()
|
||
|
||
code = args.get('code')
|
||
file_path = args.get('file')
|
||
if not code and not file_path:
|
||
raise ValueError('code 和 file 至少要给一个')
|
||
|
||
timeout = timeouts.budget(args, 'pythonRun')
|
||
stdin_text = args.get('stdin') or ''
|
||
|
||
if file_path:
|
||
target = str(file_path)
|
||
if not os.path.isfile(target):
|
||
raise ValueError(f'文件不存在:{target}')
|
||
with open(target, 'r', encoding='utf-8', errors='replace') as fh:
|
||
source = fh.read()
|
||
filename = os.path.abspath(target)
|
||
cwd = os.path.dirname(filename)
|
||
else:
|
||
source = str(code)
|
||
# 用与安卓缓存目录同级的位置当"脚本目录",避免把临时文件写进只读的 assets
|
||
filename = os.path.join(paths.get().tmp_dir, f'doubao_run_{int(time.time() * 1000)}.py')
|
||
cwd = paths.get().tmp_dir
|
||
|
||
result = run_with_timeout(
|
||
lambda: _exec_source(source, filename, cwd, stdin_text),
|
||
timeout,
|
||
)
|
||
if result is None:
|
||
return {
|
||
'error': f'执行超时({timeout}s)',
|
||
'timeout': True,
|
||
'note': '进程内执行无法强杀线程,被放弃的代码可能仍在后台运行',
|
||
}
|
||
exit_code, stdout_text, stderr_text = result
|
||
return {
|
||
'exit_code': exit_code,
|
||
'stdout': stdout_text[-12000:],
|
||
'stderr': stderr_text[-6000:],
|
||
}
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 注册表
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
BUILTIN_TOOLS = {
|
||
'shell': {'spec': SHELL_TOOL, 'run': shell_run},
|
||
'python_run': {'spec': PYTHON_RUN_TOOL, 'run': python_run},
|
||
}
|
||
|
||
# 智能体系统的工具(记忆 / 情绪 / 用量)也走**进程内**实现 —— 它们要读写
|
||
# `agent.db`,而电脑端的文件工具是子进程,根本 import 不到内核模块。
|
||
#
|
||
# ★ 合并进这一个字典而不是让 tools_runtime 从两处取:
|
||
# 发现工具、找入口、判"要不要豁免超时"全都只认 BUILTIN_TOOLS,
|
||
# 多一个来源就多一处"忘了查"的机会(加进来之后自动全部生效)。
|
||
from agent_tools import AGENT_TOOLS # noqa: E402
|
||
|
||
BUILTIN_TOOLS.update(AGENT_TOOLS)
|