Files
doubao-clone/android/kernel/store.py
l fd72ad06a1 feat(agent-v1.1): 智能体系统第一阶段 —— 数据层 + 7 个工具 + 选择界面
按《智能体系统需求文档 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 端跟上。
2026-10-16 12:36:55 +08:00

1209 lines
46 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
持久化:设置 / 会话 / 智能体。
对应 Node 版的 config.mjs(设置)+ store.mjs(会话)+ agents.mjs(智能体),
文件名也保持一致(settings.json / conversations.json / agents.json),
这样安卓内核和桌面内核可以共用同一个数据目录。
为什么用 JSON 文件而不是 SQLite:
* 数据量极小(几条会话、几个智能体),前端还要能直接看到/改这些文件;
* 安卓上 Chaquopy 自带 sqlite3,但跨端"人肉可读"更重要;
* 写盘走"临时文件 + 原子替换",避免安卓被杀进程时留下半个 JSON。
"""
import json
import os
import re
import shutil
import sys
import threading
import uuid
from datetime import datetime, timezone
import paths
import agentdb
from defaults import DEFAULT_AGENTS, DEFAULT_SETTINGS, PROVIDER_PRESETS
_lock = threading.RLock()
_conv_state = None # 会话状态在内存里缓存(和 Node 版 store.mjs 一样只 load 一次)
# --------------------------------------------------------------------------- #
# 通用小工具
# --------------------------------------------------------------------------- #
def now_iso() -> str:
"""
和 JS 的 new Date().toISOString() 完全一致的格式:
2025-01-01T12:00:00.000Z(毫秒精度 + Z 后缀)。
前端会把这些字符串直接排序/展示,格式不一致会出现"时间跳来跳去"。
"""
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
def _read_json(file_path: str):
"""读 JSON;文件不存在或坏掉都返回 None(调用方决定怎么兜底)。"""
if not os.path.isfile(file_path):
return None
try:
with open(file_path, 'r', encoding='utf-8') as fh:
return json.load(fh)
except (OSError, ValueError) as exc:
print(f'[store] {os.path.basename(file_path)} 解析失败:{exc}', file=sys.stderr)
return None
def _write_json(file_path: str, payload) -> None:
"""原子写:先写 .tmp 再 os.replace,避免掉电/被杀时留下半个文件。"""
os.makedirs(os.path.dirname(file_path), exist_ok=True)
tmp = f'{file_path}.tmp'
with open(tmp, 'w', encoding='utf-8') as fh:
json.dump(payload, fh, ensure_ascii=False, indent=2)
os.replace(tmp, file_path)
def _as_text(value) -> str:
"""JS 的 String(x):None 会变成空串而不是 'None'。"""
if value is None:
return ''
if isinstance(value, str):
return value
return str(value)
# --------------------------------------------------------------------------- #
# 设置
# --------------------------------------------------------------------------- #
_dotenv_loaded = False
def _load_dotenv() -> None:
"""
极简 .env 解析。Node 版读 server/.env;Python 版读数据目录和内核目录下的 .env,
这样安卓上把 key 放在数据目录里就能用,不需要动源码目录。
"""
global _dotenv_loaded
if _dotenv_loaded:
return
_dotenv_loaded = True
p = paths.get()
for folder in (p.data_dir, os.path.dirname(os.path.abspath(__file__))):
env_file = os.path.join(folder, '.env')
if not os.path.isfile(env_file):
continue
try:
with open(env_file, 'r', encoding='utf-8') as fh:
lines = fh.read().splitlines()
except OSError:
continue
for raw in lines:
line = raw.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, _, value = line.partition('=')
key = key.strip()
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
value = value[1:-1]
if key and key not in os.environ:
os.environ[key] = value
def mask_settings(settings: dict) -> dict:
"""脱敏:apiKey / 语音 Token 只回掩码 + has* 标志(前端据此显示"已配置")。"""
out = dict(settings)
out['apiKey'] = '••••••••' if settings.get('apiKey') else ''
out['hasApiKey'] = bool(settings.get('apiKey'))
speech = dict(out.get('speech') or {})
speech['volcToken'] = '••••••••' if speech.get('volcToken') else ''
speech['volcApiKey'] = '••••••••' if speech.get('volcApiKey') else ''
speech['openaiApiKey'] = '••••••••' if speech.get('openaiApiKey') else ''
out['speech'] = speech
return out
def read_settings() -> dict:
"""读设置:默认值 + 文件 + 环境变量兜底(字段与 Node 版一致)。"""
_load_dotenv()
stored = _read_json(paths.get().settings_file) or {}
if not isinstance(stored, dict):
stored = {}
settings = dict(DEFAULT_SETTINGS)
settings.update(stored)
# 子对象要深合并,否则用户只改 security.allow 会把 security.mode 冲掉。
# ★ 而且必须防住"子对象被非字典值覆盖":曾经前端把嵌套 Map 序列化成了字符串
# ({"speech":"{autoRead=true}"}),存进去之后**每一次**读配置都会抛
# TypeError,/api/state 从此一直 500 —— 一个坏字段把整个 App 弄成空白。
# 所以:读的时候发现不是字典就回落默认值(自愈),写的时候也不让非字典覆盖。
#
# ★ timeouts **刻意不在这个列表里**:它的默认值是空 dict(真正的默认值在
# timeouts.py 里),深合并会让"改回默认 = 删掉这一项"永远删不掉 ——
# 旧值残留在设置文件里,用户会看到"我明明恢复默认了怎么还是 30 秒"。
# 所以它走**整体替换**:写进来的就是全部,没写到的等于用默认值。
for key in ('tools', 'security', 'speech'):
defaults = DEFAULT_SETTINGS.get(key) or {}
raw = stored.get(key)
if not isinstance(raw, dict):
if raw is not None:
print(f'[config] settings.json 里的 {key} 不是对象,已回落默认值', file=sys.stderr, flush=True)
raw = {}
settings[key] = {**defaults, **raw}
if not isinstance(settings['security'].get('allow'), list):
settings['security']['allow'] = []
settings.pop('hasApiKey', None)
# 环境变量兜底:没填 key 时用 .env / 系统环境变量里的
preset = _preset_of(settings)
if not settings.get('apiKey') and preset.get('apiKeyEnv'):
settings['apiKey'] = os.environ.get(preset['apiKeyEnv'], '')
return settings
def _preset_of(settings: dict) -> dict:
from defaults import PROVIDER_PRESETS # 局部导入,避免循环依赖
return PROVIDER_PRESETS.get(settings.get('provider')) or PROVIDER_PRESETS['ark']
def write_settings(patch: dict) -> dict:
"""写设置:浅合并 + 子对象深合并 + 掩码值表示"不修改"。"""
if not isinstance(patch, dict):
patch = {}
# ★★ 显式的"清除"通路:值传 None 就是"我要把它清掉"。
#
# 为什么需要它:下面那段"空串一律当没填"的保险是对的(它防的是
# "前端草稿没初始化好,一次保存清空整份配置"),但代价是
# **用户永远清不掉自定义 Base URL / 模型名** ——
# 他删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
# (这是我在测 AI 界面回流时踩到的:想把内核从假模型服务指回默认,
# 传空串怎么也改不掉。)
#
# 所以给一条**显式**的路:传 null。空串仍然= "没填、别动",
# null = "确实要清掉"。两者语义不同,前端可以按需选。
explicit_clear = {k for k, v in patch.items() if v is None}
for key in explicit_clear:
patch.pop(key, None)
# ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。
# 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好),
# 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。
# systemPrompt / toolsDir 故意不在此列:它们"留空"是合理需求。
for key in ('baseUrl', 'model', 'apiKey', 'nickname', 'provider', 'thinkingLevel'):
if key in patch and isinstance(patch[key], str) and not patch[key].strip():
patch.pop(key)
current = read_settings()
nxt = {**current, **patch}
# 显式清除的落到默认值上(不是留着旧值,也不是变成空 —— 空会让
# "用哪个 provider 的默认 baseUrl"这套逻辑失效)
for key in explicit_clear:
nxt[key] = DEFAULT_SETTINGS.get(key, '')
# 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。
# ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 JSON 序列化踩坑),
# 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。
for key in ('tools', 'security', 'speech'):
if key not in patch:
continue
if isinstance(patch[key], dict):
nxt[key] = {**(current.get(key) or {}), **patch[key]}
else:
nxt[key] = current.get(key) or {}
print(f'[config] 补丁里的 {key} 不是对象({type(patch[key]).__name__}),已忽略', file=sys.stderr, flush=True)
# ★ timeouts 是**整体替换**,不深合并 —— 默认值在 timeouts.py 里,
# 深合并会让"改回默认 = 从设置里删掉这一项"永远删不掉。
# 调用方(/api/timeouts)传进来的就是**完整的非默认集合**。
if 'timeouts' in patch:
raw_t = patch['timeouts']
if isinstance(raw_t, dict):
nxt['timeouts'] = raw_t
else:
nxt['timeouts'] = current.get('timeouts') or {}
print(f'[config] 补丁里的 timeouts 不是对象({type(raw_t).__name__}),已忽略', file=sys.stderr, flush=True)
if patch.get('apiKey') == '••••••••':
nxt['apiKey'] = current.get('apiKey', '')
# ★ 掩码回写保护:界面读到的是 '••••••••',用户不改语音设置直接保存时,
# 这个掩码会跟着 patch 回来。不处理的话真 Token 就被这八个点覆盖了,
# 下次朗读直接报"缺 Token" —— 这类"看一眼就坏"的 bug 最难查。
speech_next = nxt.get('speech')
if isinstance(speech_next, dict):
speech_cur = current.get('speech') or {}
for secret in ('volcToken', 'volcApiKey', 'openaiApiKey'):
if speech_next.get(secret) == '••••••••':
speech_next[secret] = speech_cur.get(secret, '')
# ★ 语音里"空字符串就等于坏掉"的字段,同样不许被空值覆盖。
# 引擎名一空,界面上一张卡片都不会高亮(看起来就是"设置被清空了");
# 模型名一空,朗读/识别会直接调不通。
# 注意 ttsVoice / volcAppId / sttLanguage 不在此列 —— 它们留空是合理需求
# (留空 = 用引擎默认音色 / 还没填)。
for key in ('ttsEngine', 'sttEngine', 'sttModel', 'ttsModel', 'volcCluster', 'volcEncoding'):
if key in speech_next and isinstance(speech_next[key], str) and not speech_next[key].strip():
speech_next[key] = speech_cur.get(key) or DEFAULT_SETTINGS['speech'].get(key, '')
nxt['speech'] = speech_next
nxt.pop('hasApiKey', None)
_write_json(paths.get().settings_file, nxt)
return nxt
def provider_info(settings: dict, agent: dict = None) -> dict:
"""
当前提供商的完整信息(预设 + 生效的 baseUrl/model)。
★ agent 不为空时,智能体自己的 provider/model/baseUrl **优先**,留空则继承全局。
这样"某个智能体用 DeepSeek、其它还用方舟"是改一个智能体的事,
不用来回切全局设置 —— 而全局设置仍然是没配过的智能体的默认值。
"""
agent = agent or {}
provider_key = (agent.get('provider') or '').strip() or settings.get('provider')
preset = PROVIDER_PRESETS.get(provider_key) or _preset_of(settings)
return {
**preset,
'provider': provider_key,
# baseUrl 也是三层:智能体 > 全局 > 预设
'baseUrl': (agent.get('baseUrl') or '').strip() or settings.get('baseUrl') or preset.get('baseUrl', ''),
'model': (agent.get('model') or '').strip() or settings.get('model') or preset.get('defaultModel', ''),
}
def agent_or_empty(agent_id: str) -> dict:
"""按 id 找智能体;找不到返回空 dict(调用方按"没指定"处理)。
包一层是因为 get_agent 返回 None,而调用方(会议引擎、朗读路由)基本都是
"有就用、没有就继承全局"的语义,到处写 `or {}` 太啰嗦。
"""
return get_agent(agent_id) or {}
# --------------------------------------------------------------------------- #
# 会话
# --------------------------------------------------------------------------- #
def _rid_conv() -> str:
# 和 Node 的 `c_${Date.now().toString(36)}_${random}` 同风格;不必逐字符相同
return f'c_{_ts36()}_{_rand36(5)}'
def _ts36() -> str:
return _base36(int(datetime.now(timezone.utc).timestamp() * 1000))
def _base36(num: int) -> str:
digits = '0123456789abcdefghijklmnopqrstuvwxyz'
if num == 0:
return '0'
out = ''
while num:
num, rem = divmod(num, 36)
out = digits[rem] + out
return out
def _rand36(length: int) -> str:
import random
return ''.join(random.choice('0123456789abcdefghijklmnopqrstuvwxyz') for _ in range(length))
def _fresh_state() -> dict:
stamp = now_iso()
return {
'conversations': [
{
'id': 'c_main',
'title': '主对话',
'agentId': 'a_doubao',
'pinned': True,
'createdAt': stamp,
'updatedAt': stamp,
'messages': [],
}
]
}
def _load_conversations() -> dict:
global _conv_state
with _lock:
if _conv_state is None:
state = _read_json(paths.get().conversations_file)
if state is None:
state = _fresh_state()
if not isinstance(state.get('conversations'), list) or not state['conversations']:
state = _fresh_state()
_conv_state = state
return _conv_state
def _persist_conversations() -> None:
_write_json(paths.get().conversations_file, _load_conversations())
def _preview_of(messages: list) -> str:
"""列表预览:取最后一条有内容的消息,用户消息加"我:"前缀。"""
for msg in reversed(messages or []):
content = msg.get('content')
if not content:
continue
text = re.sub(r'\s+', ' ', _as_text(content)).strip()
if not text:
continue
tag = '我:' if msg.get('role') == 'user' else ''
return f'{tag}{text[:30]}…' if len(text) > 30 else f'{tag}{text}'
return ''
def list_conversations() -> list:
"""列表:带最后一条消息预览,置顶优先 + 更新时间倒序。"""
items = list(_load_conversations()['conversations'])
items.sort(
key=lambda c: (1 if c.get('pinned') else 0, _as_text(c.get('updatedAt'))),
reverse=True,
)
out = []
for conv in items:
messages = conv.get('messages') or []
meta = {k: v for k, v in conv.items() if k != 'messages'}
meta['messageCount'] = len(messages)
meta['preview'] = _preview_of(messages)
out.append(meta)
return out
# --------------------------------------------------------------------------- #
# AI 弹过的界面(HTML)
# --------------------------------------------------------------------------- #
#
# 用户要求:"AI 写的界面可以再点开" —— 关掉之后(甚至重启 App 之后)
# 还能把它调出来。所以每次 show_ui 都存一份。
#
# 存法:
# <data>/screens/<id>.html 正文
# <data>/screens/index.json 索引(列表页只读这个,不用把 HTML 全读一遍)
#
# ★ 为什么落盘而不是只留内存:
# 用户关掉界面、过一会儿想起来"刚才那个再看一眼",内存里那份早没了。
# 重启 App 更是全没了。
#
# ★ 为什么单独存文件而不是塞进 conversations.json:
# 一个界面的 HTML 可能几十 KB,塞进会话文件会让那个文件越来越大、
# 每次读写整个会话列表都变慢。分开存,列表页只读个小索引。
SCREEN_INDEX = 'index.json'
# 一个会话最多留多少个界面(多了列表没法看,磁盘也白占)
SCREEN_KEEP_PER_CONV = 30
def _screens_dir() -> str:
d = paths.get().screens_dir
os.makedirs(d, exist_ok=True)
return d
def _screen_index_path() -> str:
return os.path.join(_screens_dir(), SCREEN_INDEX)
def _load_screen_index() -> list:
try:
with open(_screen_index_path(), encoding='utf-8') as fh:
data = json.load(fh)
return data if isinstance(data, list) else []
except Exception: # noqa: BLE001 - 没有/坏了都当空
return []
def _save_screen_index(items: list) -> None:
try:
with open(_screen_index_path(), 'w', encoding='utf-8') as fh:
json.dump(items, fh, ensure_ascii=False, indent=2)
except Exception as exc: # noqa: BLE001
print(f'[screens] 写索引失败:{exc}', file=sys.stderr, flush=True)
def _screen_preview(html: str) -> str:
"""从 HTML 里抠一小段纯文字做预览(去掉标签/脚本/样式)"""
text = re.sub(r'<(script|style)[^>]*>.*?</\1>', ' ', html, flags=re.DOTALL | re.IGNORECASE)
text = re.sub(r'<[^>]+>', ' ', text)
text = re.sub(r'\s+', ' ', text).strip()
return text[:120]
def save_screen(conv_id: str, html: str, title: str, full_html: bool) -> dict:
"""存一个 AI 弹出来的界面,返回它的索引项。"""
sid = 's_' + uuid.uuid4().hex[:12]
try:
with open(os.path.join(_screens_dir(), f'{sid}.html'), 'w', encoding='utf-8') as fh:
fh.write(html)
except Exception as exc: # noqa: BLE001
print(f'[screens] 写 {sid}.html 失败:{exc}', file=sys.stderr, flush=True)
return {}
item = {
'id': sid,
'conversationId': conv_id or '',
'title': (title or '').strip() or 'AI 界面',
'fullHtml': bool(full_html),
'bytes': len(html),
# 列表页拿它做一行预览 —— 不用把 HTML 读出来也能看出这是哪个界面
'preview': _screen_preview(html),
'at': now_iso(),
}
with _lock:
items = _load_screen_index()
items.insert(0, item)
# 每个会话只留最近 N 个
kept, per_conv = [], {}
for it in items:
cid = it.get('conversationId') or ''
per_conv[cid] = per_conv.get(cid, 0) + 1
if per_conv[cid] <= SCREEN_KEEP_PER_CONV:
kept.append(it)
else:
# 超出的把正文删掉,别让磁盘一直涨
try:
os.remove(os.path.join(_screens_dir(), f"{it.get('id')}.html"))
except Exception: # noqa: BLE001
pass
_save_screen_index(kept)
return item
def list_screens(conv_id: str = '') -> list:
"""列出界面(按时间倒序)。传 conv_id 就只看那个会话的。"""
items = _load_screen_index()
if conv_id:
items = [it for it in items if (it.get('conversationId') or '') == conv_id]
# 正文被清掉的(超上限)就别列出来了
out = []
for it in items:
if os.path.isfile(os.path.join(_screens_dir(), f"{it.get('id')}.html")):
out.append(it)
return out
def read_screen(screen_id: str):
"""读一个界面的正文;不存在返回 None"""
if not screen_id or '/' in screen_id or '\\' in screen_id or '..' in screen_id:
return None
try:
with open(os.path.join(_screens_dir(), f'{screen_id}.html'), encoding='utf-8') as fh:
return fh.read()
except Exception: # noqa: BLE001
return None
def delete_screen(screen_id: str) -> bool:
if not screen_id:
return False
with _lock:
items = _load_screen_index()
kept = [it for it in items if it.get('id') != screen_id]
if len(kept) == len(items):
return False
_save_screen_index(kept)
try:
os.remove(os.path.join(_screens_dir(), f'{screen_id}.html'))
except Exception: # noqa: BLE001
pass
return True
# --------------------------------------------------------------------------- #
# AI 主动往会话里发消息(send_message 工具)
# --------------------------------------------------------------------------- #
#
# ★★★ 这个功能最危险的地方是**死循环**:
# 模型发一条消息 → 内核顺手跑一轮回复 → 那一轮里模型又调 send_message
# → 再跑一轮 → 无限套娃。一个下午能把 API 额度烧光,
# 而且用户看到满屏自己没发过的消息。
#
# 所以除了工具侧和桥侧的深度检查,这里再做一道**每会话条数上限**:
# 即使深度检查因为某个环节没传到而失效,条数上限也能兜住。
#
# ★ 计数**从会话历史里数**,不用内存计数器(第一版就是内存计数,两个毛病):
# 1. 重启 App 就清零 —— 上限形同虚设,"每次重启又能发 20 条"
# 2. 写失败时可能多计 —— 拒绝信息里的数字和实际条数对不上
# 数历史没有这两个问题:它自洽、跨重启、和用户看到的东西一致。
#
# 靠消息上的 `aiSent` 标记区分"AI 主动发的"和"用户打的"。
# 这个标记界面上不显示,也不给模型看,纯粹是内部记账。
SESSION_MSG_MAX = 20
def session_message_count(conv_id: str) -> int:
conv = get_conversation(conv_id) or {}
return sum(1 for m in (conv.get('messages') or []) if m.get('aiSent'))
def append_message(conv_id: str, role: str, content: str) -> dict:
"""
往会话里追加一条消息(AI 主动发的)。
★ 走 `update_conversation` 而不是自己写文件:会话的落盘、时间戳、
标题自动生成那些逻辑都在那儿,这里再写一份就会不一致
(这个仓库里"同一段逻辑两份、加功能只改一份"的坑踩过好几次)。
"""
item = get_conversation(conv_id)
if not item:
raise KeyError(f'会话不存在:{conv_id}')
msgs = list(item.get('messages') or [])
msg = {
'role': role if role in ('user', 'assistant') else 'user',
'content': content,
'at': now_iso(),
# ★ 内部标记:这条是 AI 主动发的。
# 用来算"这个会话还能主动发几条",界面上不显示、也不给模型看。
'aiSent': True,
}
msgs.append(msg)
update_conversation(conv_id, {'messages': msgs})
return msg
# --------------------------------------------------------------------------- #
# 笔记(notes 工具写的,用户要能查看)
# --------------------------------------------------------------------------- #
#
# ★ 用户的原话:"notes 用户要能查看"。
# 以前笔记只有 AI 能读写(走 notes 工具),用户在界面上看不到。
#
# ★ 目录是 `<数据目录>/notes`(`paths.get().notes_dir`)——
# 以前 notes.py 自己算 `工具文件/../data/notes`,在安卓上落到
# **App 外部私有目录**(用户翻不到、卸载还会被清掉)。
# 那些老文件由 notes.py 里的 `_migrate_once` 自动搬过来。
#
# ★ 文件名格式:`20261015-151925-标题.md`。时间戳前缀让排序天然按时间倒序。
NOTE_SUFFIX = '.md'
def _notes_dir() -> str:
d = paths.get().notes_dir
os.makedirs(d, exist_ok=True)
# ★ 顺手把老位置的笔记搬过来。
#
# 以前迁移只在 `notes` 工具被调用时才跑(notes.py 的 ensure_dir)。
# 问题是:用户装了新版之后**先打开「笔记」页面**(而不是先让 AI 写笔记),
# 那时迁移还没跑,他看到的是**空列表** —— 以为笔记全丢了。
# 放在这里,任何一次读笔记都会先保证迁移过。
_migrate_legacy_notes(d)
return d
# 老位置:工具文件旁边的 `../data/notes`。
# 在安卓上那会落到 App 的**外部**私有目录
# (`/storage/emulated/0/Android/data/<包名>/files/data/notes`)——
# 用户用文件管理器翻不到(Android 11+ 直接隐藏),卸载还会一起删掉。
def _legacy_notes_dirs() -> list:
dirs = []
try:
# 工具目录的上一级 + /data/notes
tools_dir = paths.get().tools_dir
if tools_dir:
dirs.append(os.path.join(os.path.dirname(tools_dir), 'data', 'notes'))
except Exception: # noqa: BLE001
pass
return [d for d in dirs if d and os.path.abspath(d) != os.path.abspath(paths.get().notes_dir)]
def _migrate_legacy_notes(target: str) -> None:
"""
把老位置的笔记搬到新位置(只做一次)。
★ 为什么必须搬:用户在老版本里记的笔记是**真实数据** ——
换了目录之后文件还在老地方躺着,但 list/read 都看不到,
表现就是"我记的笔记全没了"。这类"改路径把用户数据弄丢"的事最不该发生。
"""
marker = os.path.join(target, '.migrated')
if os.path.exists(marker):
return
moved = 0
for legacy in _legacy_notes_dirs():
if not os.path.isdir(legacy):
continue
try:
names = os.listdir(legacy)
except Exception: # noqa: BLE001
continue
for name in names:
if not name.endswith(NOTE_SUFFIX):
continue
dst = os.path.join(target, name)
if os.path.exists(dst):
continue # 不覆盖同名的(新位置已有)
src = os.path.join(legacy, name)
try:
shutil.move(src, dst)
moved += 1
except Exception: # noqa: BLE001
# 跨设备 move 可能失败,退回复制
try:
shutil.copy2(src, dst)
os.remove(src)
moved += 1
except Exception: # noqa: BLE001
pass
try:
with open(marker, 'w', encoding='utf-8') as fh:
fh.write('ok\n')
except Exception: # noqa: BLE001
pass
if moved:
print(f'[notes] 已把 {moved} 条老笔记搬到新目录', file=sys.stderr, flush=True)
def _note_path(name: str):
"""把文件名解析成绝对路径;不合法(穿越/非 .md)返回 None"""
if not name or not name.endswith(NOTE_SUFFIX):
return None
# ★ 防目录穿越:文件名必须是纯文件名,不能带路径分隔符
if '/' in name or '\\' in name or '..' in name:
return None
return os.path.join(_notes_dir(), name)
def _note_title(path: str, fallback: str) -> str:
"""标题取正文第一行的 `# 标题`;读不到就用文件名兜底"""
try:
with open(path, encoding='utf-8') as fh:
first = fh.readline().strip().lstrip('#').strip()
return first or fallback
except Exception: # noqa: BLE001
return fallback
def _note_time(name: str) -> str:
"""
从文件名前缀 `20261015-151925` 解析出时间,转成 `2026-10-15T15:19:25`。
★ 解析不出来就返回空串(界面上不显示时间),**不要瞎猜** ——
用户手改过文件名的情况是有的。
"""
m = re.match(r'^(\d{8})-(\d{6})-', name)
if not m:
return ''
d, t = m.group(1), m.group(2)
return f'{d[0:4]}-{d[4:6]}-{d[6:8]}T{t[0:2]}:{t[2:4]}:{t[4:6]}'
def list_notes() -> list:
"""列出所有笔记(按文件名倒序 = 按时间倒序)"""
d = _notes_dir()
try:
names = sorted(os.listdir(d), reverse=True)
except Exception: # noqa: BLE001
return []
out = []
for name in names:
if not name.endswith(NOTE_SUFFIX):
continue
full = os.path.join(d, name)
try:
size = os.path.getsize(full)
except Exception: # noqa: BLE001
continue
# 预览 = 去掉标题行之后的头一段
preview = ''
try:
with open(full, encoding='utf-8') as fh:
body = fh.read()
lines = [ln.strip() for ln in body.splitlines()]
body_lines = [ln for ln in lines[1:] if ln]
preview = ' '.join(body_lines)[:100]
except Exception: # noqa: BLE001
pass
out.append({
'file': name,
'title': _note_title(full, name),
'bytes': size,
'at': _note_time(name),
'preview': preview,
})
return out
def read_note(name: str):
"""读一条笔记;不存在返回 None"""
path = _note_path(name)
if not path or not os.path.isfile(path):
return None
try:
with open(path, encoding='utf-8') as fh:
text = fh.read()
except Exception: # noqa: BLE001
return None
return {
'file': name,
'title': _note_title(path, name),
'at': _note_time(name),
'content': text,
'bytes': len(text.encode('utf-8')),
}
def delete_note(name: str) -> bool:
path = _note_path(name)
if not path or not os.path.isfile(path):
return False
try:
os.remove(path)
return True
except Exception: # noqa: BLE001
return False
def get_conversation(conv_id: str):
for conv in _load_conversations()['conversations']:
if conv.get('id') == conv_id:
return conv
return None
# --------------------------------------------------------------------------- #
# AI 界面的数据回流
# --------------------------------------------------------------------------- #
#
# AI 用 show_ui 弹的 HTML 界面里可以调 `Doubao.sendToAi(值)`,
# 那个值先落到这里排队,下一轮对话开始时被取走、当作上下文交给模型。
#
# ★ 为什么单独存一份、而不是直接写进会话的消息列表:
# 写进消息列表的话它会**变成一条 user 消息** —— 用户会看到一条
# 自己没打过的消息,而且它会被当成"用户说的话"进历史。
# 语义上它更像**附件/上下文**,不是用户的一句话。
# 所以单独排队,由 agent_loop 拼进这一轮的上下文里。
#
# ★ 为什么不落盘:这是**一次性的上下文**,跨重启没有意义
# (用户重启 App 之后那个界面早就关了,界面的选择也就失效了)。
# 放内存里,进程重启自然清空,正合适。
_pending_ui: dict = {}
_pending_ui_lock = threading.Lock()
# 每个会话最多排多少条 —— 用户在界面上乱点不能把内存堆满
PENDING_UI_MAX = 20
# 单条最长多少字符 —— 界面可能回传一大段文本
PENDING_UI_ITEM_MAX = 4000
def add_pending_ui(conv_id: str, value: str) -> int:
"""把界面上回传的一个值排进队。返回队里现在有几条。"""
text = (value or '').strip()[:PENDING_UI_ITEM_MAX]
if not conv_id or not text:
return len(_pending_ui.get(conv_id) or [])
with _pending_ui_lock:
box = _pending_ui.setdefault(conv_id, [])
box.append(text)
# 超了就丢**最旧的**:用户最新点的那次最相关
while len(box) > PENDING_UI_MAX:
box.pop(0)
return len(box)
def peek_pending_ui(conv_id: str) -> list:
"""看一眼(不取走)—— 给调试用的 GET 接口"""
with _pending_ui_lock:
return list(_pending_ui.get(conv_id) or [])
def take_pending_ui(conv_id: str) -> list:
"""
取走并清空。
★ 必须"取走":不取走的话每轮对话都会把同一条又带上,
用户会看到模型反复提同一件事。
"""
with _pending_ui_lock:
return list(_pending_ui.pop(conv_id, []) or [])
def clear_pending_ui(conv_id: str) -> None:
with _pending_ui_lock:
_pending_ui.pop(conv_id, None)
# --------------------------------------------------------------------------- #
# 「建议整理记忆」的待处理队列
# --------------------------------------------------------------------------- #
#
# AI 用 memory_suggest_summary 提的建议 —— **只提示不执行**(需求 3.2)。
# 界面读到之后给用户一个「整理记忆」按钮,用户点了才真的跑总结。
#
# ★ 为什么放内存而不是落库:它是一次性的提示,用户处理完就该消失。
# 落库的话重启一次 App 会看到三天前那条建议,莫名其妙。
# ★ 按智能体存(不是按会话):建议是"你的记忆该整理了",跟哪个会话无关。
_pending_summary: dict = {}
def add_pending_summary_suggestion(agent_id: str, reason: str) -> None:
"""同一个人后来的建议**覆盖**前面的 —— 说两遍没有意义"""
if not agent_id:
return
with _lock:
_pending_summary[agent_id] = (reason or '').strip()
def peek_summary_suggestion(agent_id: str) -> str:
with _lock:
return _pending_summary.get(agent_id or '', '')
def take_summary_suggestion(agent_id: str) -> str:
"""取走(取完就没了)"""
with _lock:
return _pending_summary.pop(agent_id or '', '')
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
item = {
'id': _rid_conv(),
'title': title,
'agentId': agent_id or '',
'pinned': False,
'createdAt': now_iso(),
'updatedAt': now_iso(),
'messages': [],
}
with _lock:
_load_conversations()['conversations'].insert(0, item)
_persist_conversations()
return item
def update_conversation(conv_id: str, patch: dict):
item = get_conversation(conv_id)
if not item:
return None
with _lock:
if isinstance(patch, dict):
item.update(patch)
item['updatedAt'] = now_iso()
_persist_conversations()
return item
def delete_conversation(conv_id: str) -> bool:
with _lock:
state = _load_conversations()
index = next((i for i, c in enumerate(state['conversations']) if c.get('id') == conv_id), -1)
if index < 0:
return False
state['conversations'].pop(index)
# 删光了就把"主对话"补回来,界面上不能出现空列表
if not state['conversations']:
state['conversations'].extend(_fresh_state()['conversations'])
_persist_conversations()
return True
def append_messages(conv_id: str, messages: list):
item = get_conversation(conv_id)
if not item:
return None
with _lock:
item.setdefault('messages', []).extend(messages)
item['updatedAt'] = now_iso()
_persist_conversations()
return item
def auto_title(conv_id: str, text: str) -> None:
"""用首条用户消息自动起标题(只改还没起过名的会话)。"""
item = get_conversation(conv_id)
if not item or item.get('title') not in ('新对话', '主对话'):
return
title = re.sub(r'\s+', ' ', _as_text(text)).strip()[:18]
if title:
update_conversation(conv_id, {'title': title})
def store_file_path() -> str:
return paths.get().conversations_file
# --------------------------------------------------------------------------- #
# 智能体
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
# 智能体
# --------------------------------------------------------------------------- #
#
# 智能体可以独立指定的字段。**留空一律表示"继承全局设置"** ——
# 这样"代码搭子走 DeepSeek、文案师用另一个音色"只改那一个智能体,
# 而全局设置仍然是没配过的智能体的默认值。
#
# 提成常量是为了 create / update 两边不会漂移:
# 之前这两个函数各写一份硬编码白名单,加字段时漏改一处,
# 表现就是"界面上填了、保存后再打开又变空了"。
#
# ★ v1.1 新增(《智能体系统需求文档》),字段按类型分开,见下面的 _apply_agent_patch:
# description 选择界面上展示的介绍文案(2.1)
# image 外观四件套 front / back / border-main / border-info(2.5)
# modelId 引用全局模型列表里的一个(3.3 多模型)
# worldviewId 绑定的世界观(3.6)
# emotionEnabled 情绪感知开关(3.5)
# tokenLimit Token 限额,0 = 无限制(3.1)
# skillIds 绑定的自定义 Skill(3.7;真正的绑定关系在 agent.db)
AGENT_TEXT_FIELDS = (
'name', 'avatar', 'tagline', 'description', 'systemPrompt',
'provider', # 走哪家(留空 = 全局)
'model', # 用哪个模型
'baseUrl', # 自定义网关地址
'ttsEngine', # 朗读引擎:system / volcv3 / volc / openai
'ttsVoice', # 音色 —— 多人会议里靠它区分谁在说话
'modelId', # ← 全局模型列表里的 id
'worldviewId', # ← 绑定的世界观 id
)
AGENT_NUM_FIELDS = (
'ttsSpeed', # 语速
'tokenLimit', # 0 = 无限制(不是"限额为 0")
)
AGENT_BOOL_FIELDS = ('emotionEnabled',)
AGENT_LIST_FIELDS = ('skillIds',)
AGENT_DICT_FIELDS = ('image',)
#: 能被 patch 改的全部字段(界面上"这个智能体有哪些可配"就看它)
AGENT_FIELDS = (
AGENT_TEXT_FIELDS + AGENT_NUM_FIELDS + AGENT_BOOL_FIELDS
+ AGENT_LIST_FIELDS + AGENT_DICT_FIELDS
)
def _apply_agent_patch(agent: dict, patch: dict) -> dict:
"""
把 patch 里的字段规整进 agent。
★ **create 和 update 共用这一份** —— 它们以前各写一份白名单,
加字段漏改一处就是"界面上填了、保存后再打开又变空了"这种查半天的 bug。
★ 类型规整也在这里:从 HTTP 来的东西可能是字符串(`"true"`、`"3"`),
直接存进去会让界面读到时类型不对(勾选框永远是空的)。
"""
patch = patch or {}
for key in AGENT_TEXT_FIELDS:
if patch.get(key) is not None:
agent[key] = _as_text(patch[key])
for key in AGENT_NUM_FIELDS:
if patch.get(key) is not None:
try:
agent[key] = float(patch[key])
except (TypeError, ValueError):
pass
for key in AGENT_BOOL_FIELDS:
if patch.get(key) is not None:
agent[key] = bool(patch[key])
for key in AGENT_LIST_FIELDS:
if patch.get(key) is not None:
raw = patch[key]
agent[key] = [str(x) for x in raw] if isinstance(raw, list) else []
for key in AGENT_DICT_FIELDS:
if patch.get(key) is not None:
raw = patch[key]
agent[key] = (
{str(k): _as_text(v) for k, v in raw.items()}
if isinstance(raw, dict) else {}
)
return agent
def list_agents() -> list:
file_path = paths.get().agents_file
if not os.path.isfile(file_path):
_write_json(file_path, {'agents': DEFAULT_AGENTS})
return [dict(a) for a in DEFAULT_AGENTS]
data = _read_json(file_path)
if not isinstance(data, dict) or not isinstance(data.get('agents'), list) or not data['agents']:
print('[store] agents.json 损坏,重建内置智能体', file=sys.stderr)
_write_json(file_path, {'agents': DEFAULT_AGENTS})
return [dict(a) for a in DEFAULT_AGENTS]
return data['agents']
def get_agent(agent_id: str | None):
if not agent_id:
return None
for agent in list_agents():
if agent.get('id') == agent_id:
return agent
return None
def create_agent(payload: dict) -> dict:
payload = payload or {}
state = {'agents': list_agents()}
# ★ id 一律 UUID(需求附录 A):`name` 只是显示名,允许重复、允许随便改,
# 所有关联(记忆作者、Token 统计、Skill 绑定)都挂在这个 id 上。
# 老数据里的 `a_doubao` 这种短 id **保留不动** —— 会话语料引用着它们。
agent = {
'id': agentdb.new_id(),
'name': _as_text(payload.get('name') or '新智能体')[:24],
'avatar': _as_text(payload.get('avatar') or 'custom'),
'tagline': _as_text(payload.get('tagline'))[:40],
'systemPrompt': _as_text(payload.get('systemPrompt')),
'builtin': False,
'createdAt': now_iso(),
}
_apply_agent_patch(agent, payload)
state['agents'].append(agent)
_write_json(paths.get().agents_file, state)
return agent
def update_agent(agent_id: str, patch: dict):
state = {'agents': list_agents()}
agent = next((a for a in state['agents'] if a.get('id') == agent_id), None)
if not agent:
return None
_apply_agent_patch(agent, patch)
_write_json(paths.get().agents_file, state)
return agent
def delete_agent(agent_id: str) -> bool:
state = {'agents': list_agents()}
index = next((i for i, a in enumerate(state['agents']) if a.get('id') == agent_id), -1)
if index < 0:
return False
state['agents'].pop(index)
_write_json(paths.get().agents_file, state)
# 清掉它在数据库里的绑定关系和情绪;**记忆不删** —— 那是用户的数据,
# 删智能体顺手把他攒了几个月的记忆抹掉,他会心疼(而且没法恢复)
try:
agentdb.unbind_agent(agent_id)
except Exception as exc: # noqa: BLE001 - 清理失败不该让删除失败
print(f'[store] 清理 {agent_id} 的绑定关系失败:{exc}', file=sys.stderr)
return True
# --------------------------------------------------------------------------- #
# 通用资源表:世界观 / 全局模型 / Skill
# --------------------------------------------------------------------------- #
#
# ★ 三者的 CRUD 完全一样(列表 + 增 + 改 + 删 + UUID 主键),所以**只写一份** ——
# 区别只是"有哪些字段",那部分在 RESOURCES 里声明。
#
# ★ 为什么不放 agent.db(SQLite):它们的量级和 agents.json 一样是"几个到几十个"
# (用户自己会去数),而且要人肉可读。分界线见 agentdb.py 的文件头。
RESOURCES = {
# 世界观(需求 3.6):名字 + 设定文本 + 外观四件套
'worldviews': {
'file': lambda: paths.get().worldviews_file,
'key': 'worldviews',
'text': ('name', 'setting'),
'dict': ('image',),
'label': '世界观',
},
# 全局模型列表(需求 3.3):名称 + API 端点 + Key + 模型标识 + 单价
'models': {
'file': lambda: paths.get().models_file,
'key': 'models',
'text': ('name', 'apiBase', 'apiKey', 'model', 'provider'),
'num': ('pricePerK',), # 元/千 Token,0 = 不显示费用估算
'label': '模型',
},
# Skill(需求 3.7):纯文本的"工具使用手册"
'skills': {
'file': lambda: paths.get().skills_file,
'key': 'skills',
'text': ('name', 'content'),
'bool': ('builtin',),
'label': 'Skill',
},
}
def _res(name: str) -> dict:
cfg = RESOURCES.get(name)
if not cfg:
raise KeyError(f'没有这种资源:{name}')
return cfg
def list_resource(name: str) -> list:
cfg = _res(name)
file_path = cfg['file']()
data = _read_json(file_path)
if not isinstance(data, dict) or not isinstance(data.get(cfg['key']), list):
return []
return data[cfg['key']]
def _write_resource(name: str, items: list) -> None:
cfg = _res(name)
_write_json(cfg['file'](), {cfg['key']: items})
def get_resource(name: str, rid: str):
if not rid:
return None
for item in list_resource(name):
if item.get('id') == rid:
return item
return None
def _apply_resource_patch(name: str, item: dict, patch: dict) -> dict:
cfg = _res(name)
patch = patch or {}
for key in cfg.get('text', ()):
if patch.get(key) is not None:
item[key] = _as_text(patch[key])
for key in cfg.get('num', ()):
if patch.get(key) is not None:
try:
item[key] = float(patch[key])
except (TypeError, ValueError):
pass
for key in cfg.get('bool', ()):
if patch.get(key) is not None:
item[key] = bool(patch[key])
for key in cfg.get('dict', ()):
if patch.get(key) is not None:
raw = patch[key]
item[key] = (
{str(k): _as_text(v) for k, v in raw.items()}
if isinstance(raw, dict) else {}
)
return item
def create_resource(name: str, payload: dict) -> dict:
cfg = _res(name)
items = list_resource(name)
item = {
'id': agentdb.new_id(), # ★ UUID(需求附录 A)
'name': _as_text((payload or {}).get('name'))[:40],
'builtin': False,
'createdAt': now_iso(),
}
_apply_resource_patch(name, item, payload)
# 重名不拦(需求 2.5:重名由用户自己区分),但界面要能看出来,
# 所以这里不做任何"自动改名" —— 显示时加序号是界面的事
items.append(item)
_write_resource(name, items)
return item
def update_resource(name: str, rid: str, patch: dict):
items = list_resource(name)
item = next((x for x in items if x.get('id') == rid), None)
if not item:
return None
_apply_resource_patch(name, item, patch)
_write_resource(name, items)
return item
def delete_resource(name: str, rid: str) -> bool:
items = list_resource(name)
left = [x for x in items if x.get('id') != rid]
if len(left) == len(items):
return False
_write_resource(name, left)
return True
def reset_runtime_cache() -> None:
"""测试/热重载用:丢掉会话内存缓存(设置本来就不缓存)。"""
global _conv_state, _dotenv_loaded
with _lock:
_conv_state = None
_dotenv_loaded = False