按《智能体系统需求文档 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 端跟上。
153 lines
7.0 KiB
Python
153 lines
7.0 KiB
Python
"""
|
||
运行期路径与平台判断。
|
||
|
||
为什么单独一个模块:
|
||
* Node 版把路径写在 config.mjs 的模块级常量里(读进程环境变量),
|
||
Python 版要能在安卓(Chaquopy)里被反复以不同参数启动,所以做成可配置单例。
|
||
* 所有落盘位置都从「数据目录」派生,安卓上把数据目录指到
|
||
/data/data/<包名>/files 或外部存储即可,源码目录保持只读。
|
||
|
||
只用标准库;安卓相关判断也只用标准库(sys.platform / os.environ)。
|
||
"""
|
||
|
||
import os
|
||
import sys
|
||
|
||
# 让 `python android/kernel/main.py` 和 `python -m android.kernel` 两种启动方式
|
||
# 都能用扁平导入(import store / from app import ...)。tools/*.py 也是这个套路。
|
||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||
if _HERE not in sys.path:
|
||
sys.path.insert(0, _HERE)
|
||
|
||
# 仓库根目录:android/kernel/ -> android/ -> <repo>
|
||
REPO_ROOT = os.path.dirname(os.path.dirname(_HERE))
|
||
|
||
|
||
def _detect_android() -> bool:
|
||
"""
|
||
判断是否跑在安卓的 CPython(Chaquopy)里。
|
||
Chaquopy 会设 sys.platform == 'android'(较新版本)或提供 sys.getandroidapilevel(),
|
||
老版本两个都没有,只能退回看 ANDROID_ROOT / ANDROID_DATA 环境变量。
|
||
"""
|
||
if sys.platform.startswith('android') or sys.platform in ('linux-android', 'android'):
|
||
return True
|
||
if hasattr(sys, 'getandroidapilevel'):
|
||
return True
|
||
return bool(os.environ.get('ANDROID_ROOT') or os.environ.get('ANDROID_DATA'))
|
||
|
||
|
||
IS_ANDROID = _detect_android()
|
||
IS_WINDOWS = sys.platform.startswith('win')
|
||
|
||
|
||
class Paths:
|
||
"""一次内核进程用到的全部目录/文件位置。"""
|
||
|
||
def __init__(
|
||
self,
|
||
data_dir: str | None = None,
|
||
tools_dir: str | None = None,
|
||
web_dir: str | None = None,
|
||
dist_dir: str | None = None,
|
||
web_core_dir: str | None = None,
|
||
):
|
||
# 数据目录:安卓上由 Kotlin 侧(或 --data-dir)指定,默认放在内核目录下的 data/
|
||
self.data_dir = os.path.abspath(
|
||
data_dir or os.environ.get('DOUBAO_DATA') or os.path.join(_HERE, 'data')
|
||
)
|
||
# 内置工具目录(仓库里的 tools/;settings.toolsDir 可以在运行时覆盖它)
|
||
self.tools_dir = os.path.abspath(
|
||
tools_dir or os.environ.get('DOUBAO_TOOLS') or os.path.join(REPO_ROOT, 'tools')
|
||
)
|
||
# 静态托管:宿主页 + Lynx 产物 + web-core 运行时(安卓上一般用不上,
|
||
# 因为页面在 assets 里,但保留以便桌面/局域网调试时同一端口全包)
|
||
self.web_dir = os.path.abspath(web_dir or os.environ.get('DOUBAO_WEB') or os.path.join(REPO_ROOT, 'web'))
|
||
self.dist_dir = os.path.abspath(
|
||
dist_dir or os.environ.get('DOUBAO_DIST') or os.path.join(REPO_ROOT, 'app', 'dist')
|
||
)
|
||
self.web_core_dir = self._resolve_web_core(web_core_dir)
|
||
|
||
# 数据目录下的固定文件(文件名与 Node 版保持一致,方便两边互相读)
|
||
self.uploads_dir = os.path.join(self.data_dir, 'uploads')
|
||
self.tmp_dir = os.path.join(self.data_dir, 'tmp')
|
||
# ★ AI 弹出来的那些 HTML 界面存这儿 —— 用户关掉之后还要能再打开
|
||
# (用户明确要求:"AI 写的界面可以再点开")
|
||
self.screens_dir = os.path.join(self.data_dir, 'screens')
|
||
# ★ notes 工具的笔记存这儿("notes 用户要能查看")。
|
||
#
|
||
# 以前 notes.py 自己算路径:`工具文件/../data/notes` ——
|
||
# 在安卓上会落到 **App 的外部私有目录**
|
||
# (`/storage/emulated/0/Android/data/<包名>/files/data/notes`)。
|
||
# 那个地方用户用文件管理器根本翻不到(Android 11+ 直接隐藏),
|
||
# 而且**卸载 App 就一起删了**。
|
||
# 放到 data_dir 下和别的数据一起,持久、位置统一、也能通过接口读出来给界面看。
|
||
self.notes_dir = os.path.join(self.data_dir, 'notes')
|
||
self.settings_file = os.path.join(self.data_dir, 'settings.json')
|
||
self.conversations_file = os.path.join(self.data_dir, 'conversations.json')
|
||
self.agents_file = os.path.join(self.data_dir, 'agents.json')
|
||
self.mcp_file = os.path.join(self.data_dir, 'mcp.servers.json')
|
||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||
#
|
||
# ★ 和 agents.json 一样是 JSON、一人一个文件:它们的量级也是"几个到几十个",
|
||
# 而且要人肉可读(用户会想直接看自己建的世界观写成什么样)。
|
||
# 会**持续增长**的那些(记忆 / 情绪 / Token 统计)在 agent.db 里,
|
||
# 分界线见 agentdb.py 的文件头。
|
||
self.worldviews_file = os.path.join(self.data_dir, 'worldviews.json')
|
||
self.models_file = os.path.join(self.data_dir, 'models.json')
|
||
self.skills_file = os.path.join(self.data_dir, 'skills.json')
|
||
# 智能体系统的 SQLite(记忆 / 情绪 / Token / 绑定关系)
|
||
self.agent_db_file = os.path.join(self.data_dir, 'agent.db')
|
||
# 智能体包解出来的图片等资源(导入 zip 时落到这儿)
|
||
self.agent_assets_dir = os.path.join(self.data_dir, 'agent-assets')
|
||
|
||
@staticmethod
|
||
def _resolve_web_core(explicit: str | None) -> str:
|
||
candidates = [
|
||
explicit,
|
||
os.environ.get('DOUBAO_WEB_CORE'),
|
||
os.path.join(REPO_ROOT, 'web-core'),
|
||
os.path.join(REPO_ROOT, 'app', 'node_modules', '@lynx-js', 'web-core', 'dist', 'client_prod', 'static'),
|
||
]
|
||
for item in candidates:
|
||
if item and os.path.isdir(item):
|
||
return os.path.abspath(item)
|
||
# 都不存在时也返回最后一个候选,交给 404 分支处理(和 Node 版行为一致)
|
||
return os.path.abspath(candidates[-1])
|
||
|
||
def ensure_dirs(self) -> None:
|
||
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir,
|
||
self.notes_dir, self.agent_assets_dir):
|
||
try:
|
||
os.makedirs(folder, exist_ok=True)
|
||
except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死
|
||
print(f'[paths] 无法创建目录 {folder}:{exc}', file=sys.stderr)
|
||
|
||
def as_dict(self) -> dict:
|
||
return {
|
||
'dataDir': self.data_dir,
|
||
'toolsDir': self.tools_dir,
|
||
'webDir': self.web_dir,
|
||
'distDir': self.dist_dir,
|
||
'webCoreDir': self.web_core_dir,
|
||
'settingsFile': self.settings_file,
|
||
}
|
||
|
||
|
||
_current: Paths | None = None
|
||
|
||
|
||
def configure(**kwargs) -> Paths:
|
||
"""(重新)配置全局路径;main.py 启动时调一次,测试里可以反复调。"""
|
||
global _current
|
||
_current = Paths(**kwargs)
|
||
_current.ensure_dirs()
|
||
return _current
|
||
|
||
|
||
def get() -> Paths:
|
||
"""取当前路径配置,没配置过就用默认值(方便被安卓侧直接 import 调用)。"""
|
||
global _current
|
||
if _current is None:
|
||
_current = configure()
|
||
return _current
|