Files
doubao-clone/android/kernel/store.py
l f056bcf45a 豆包复刻:原生安卓(Compose + 内嵌 Termux)+ Web / Windows
一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、
不需要另外装 Termux。

安卓端
- 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的
- 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹
- 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端;
  pty 不可用的 ROM 上自动降级成命令控制台
- APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上
- 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板
- 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎

AI 能力
- 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 /
  通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义
- 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发),
  认不出来的一律不发,避免给不支持的厂商发字段直接 400
- MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式

跨端
- 安卓走原生 Compose,Web / Windows 走 Lynx
- Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本

自检脚本(都不需要真 Key)
- verify-phone.mjs          设备端 24 项验收
- verify-speech.mjs         语音链路 31 项,两份内核各跑一遍
- parity-thinking.mjs       思考强度映射对拍
- probe-settings-wipe.mjs   设置防清空攻击测试
- mock-llm.mjs              假的 OpenAI + 火山语音服务

许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron)
的授权见 LICENSE。
2026-10-09 14:09:36 +08:00

461 lines
17 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
_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['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', '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) -> dict:
"""当前提供商的完整信息(预设 + 生效的 baseUrl/model)。"""
preset = _preset_of(settings)
return {**preset, 'baseUrl': settings.get('baseUrl') or preset['baseUrl'],
'model': settings.get('model') or preset['defaultModel']}
# --------------------------------------------------------------------------- #
# 会话
# --------------------------------------------------------------------------- #
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
# --------------------------------------------------------------------------- #
# 智能体
# --------------------------------------------------------------------------- #
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(),
}
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'):
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