Files
doubao-clone/android/kernel/store.py
l 24cc34d79b 智能体支持独立模型与语音(留空继承全局)
用户需求 A。规则是**智能体 > 全局**:智能体自己配了 provider / model /
baseUrl / ttsEngine / ttsVoice / ttsSpeed 就用它的,留空(空串 / null / 0)
就沿用全局设置。

这样"代码搭子走 DeepSeek、文案师换个音色"只改那一个智能体,
而全局设置仍然是没配过的智能体的默认值。

【内核】
- store.provider_info(settings, agent):provider/model/baseUrl 三层解析
  (智能体 > 全局 > 预设)
- speech.voice_for(settings, agent):音色解析,只有这一份实现 ——
  别在别处再抄一遍规则,两处不一致最难查
- agent_loop 用解析后的 provider 发请求(以前永远走全局)
- /api/tts 和 /api/tts/stream 接受 agentId;流式的"是不是系统引擎"
  判断也要用**智能体覆盖后**的那套 —— 某个智能体单独配了云端音色、
  全局是"设备自带"时,不能因为全局是 system 就把它的流式挡掉

【关键设计:多人会议靠它区分谁在说话】
四个智能体一个嗓子的话,会议模式根本没法听。所以音色必须能按智能体覆盖 ——
这是会议模式的前置依赖,先做掉。

【测试抓到的两个真 bug】
1. store.create_agent / update_agent 用的是**硬编码字段白名单**,
   ttsVoice 这些新字段直接被丢掉 —— 表现就是"界面上填了、保存后又变空"。
   两份内核都有这个问题。现在字段表提成常量(AGENT_FIELDS),
   create / update 共用,加字段不会再漏改一处。
2. Node 的 /api/tts/stream 忘了给 synthesizeStream 传 agent。

这两条都是新加的回归断言抓到的 —— 不是我看代码看出来的。

【顺带】
- store.py 少了 PROVIDER_PRESETS 的 import(一跑内核就 NameError)
- 排查时手滑把 VOLC_TTS_URL 的定义删了(node --check 查不出运行时错误,
  是导入模块才暴露的)

回归:语音验收 36 → 41 项(新增 5 条智能体音色断言:
带 agentId 用自己的、不传回落全局、智能体没配则继承全局),
两份内核各 41/41;Markdown 对拍 19/19。

【这一轮之后还剩】
- B 的界面部分:可搜索的全量音色选择器(内核数据已就位)
- A 的界面部分:智能体编辑页的模型/语音选择
- C 会议模式(节点+连线编排)—— 最大的一块,下一轮开始
2026-10-10 11:10:29 +08:00

509 lines
19 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 sys
import threading
from datetime import datetime, timezone
import paths
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 弄成空白。
# 所以:读的时候发现不是字典就回落默认值(自愈),写的时候也不让非字典覆盖。
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 = {}
# ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。
# 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好),
# 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。
# 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}
# 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。
# ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 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)
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
def get_conversation(conv_id: str):
for conv in _load_conversations()['conversations']:
if conv.get('id') == conv_id:
return conv
return None
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 两边不会漂移:
# 之前这两个函数各写一份硬编码白名单,加字段时漏改一处,
# 表现就是"界面上填了、保存后再打开又变空了"。
AGENT_FIELDS = (
'provider', # 走哪家(留空 = 全局)
'model', # 用哪个模型
'baseUrl', # 自定义网关地址
'ttsEngine', # 朗读引擎:system / volcv3 / volc / openai
'ttsVoice', # 音色 —— 多人会议里靠它区分谁在说话
'ttsSpeed', # 语速
)
def _rid_agent() -> str:
return f'a_{_ts36()}_{_rand36(4)}'
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()}
agent = {
'id': _rid_agent(),
'name': _as_text(payload.get('name') or '新智能体')[:24],
'avatar': payload.get('avatar') or 'custom',
'tagline': _as_text(payload.get('tagline'))[:40],
'systemPrompt': _as_text(payload.get('systemPrompt')),
'builtin': False,
'createdAt': now_iso(),
}
# 智能体自己的模型/语音(留空 = 继承全局)
for key in AGENT_FIELDS:
if payload.get(key) is not None:
agent[key] = _as_text(payload.get(key))
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
patch = patch or {}
for key in ('name', 'avatar', 'tagline', 'systemPrompt', *AGENT_FIELDS):
if patch.get(key) is not None:
agent[key] = patch[key]
_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)
return True
def reset_runtime_cache() -> None:
"""测试/热重载用:丢掉会话内存缓存(设置本来就不缓存)。"""
global _conv_state, _dotenv_loaded
with _lock:
_conv_state = None
_dotenv_loaded = False