用户要求"全部超时做成可调"。改造前 15 个超时散在 10 个文件里当模块级常量, 说不清一共有几个,也答不了"哪些能调"。 内核 - 新增 android/kernel/timeouts.py:**超时的唯一一份定义**(DEFAULT + SPECS), 带每项的 名字/分组/说明/默认值/上下界;get() 一律夹取,用户填什么都不炸 - 新增 GET/POST /api/timeouts(清单 + 当前值 + 保存 + 恢复默认) - 各处改现读:tools_runtime(tool)、builtin_tools(shell/pythonRun)、 doubao_entry(termux)、providers(model)、speech(tts/stt)、 mcp_client(请求/连接/调用)、meeting(meetingNode)、custom_nodes(customNode)、 app.py 的 SSE 心跳 - ask_user / show_ui 用 TIMEOUT_KEYS 声明"哪个参数该用设置里的值", 内核调用前注入(工具的默认值退化成单独跑时的兜底) - store.py:timeouts 走**整体替换**而不是深合并 —— 深合并会让"改回默认"删不掉 安卓 - data/AppTimeouts.kt:客户端缓存(OkHttp 的 readTimeout、文件选择没法现问内核) - KernelClient:readTimeout 跟着 sseRead 走,改完重建连接池;新增 timeouts 接口 - ui/TimeoutsScreen.kt:全屏界面,按分组列出、-/+ 与输入框、恢复默认 - 设置页加「超时」卡片入口;NativeBridge 的本地接口请求 / 选文件等待接上 - Settings 模型加 TimeoutItem / TimeoutsState(字段全部来自内核) Node 端(Web/exe) - 新增 server/src/timeouts.mjs(和 Python 那份逐字对应) - config.mjs 加 timeouts(同样整体替换);speech / python-tools / mcp / providers 各处改读;index.mjs 加 /api/timeouts 验证 - 新增 scripts/verify-timeouts.py:清单完整性、边界容错(文字/空串/负数/超大值/ 带单位/None)、**扫内核有没有漏网的硬编码超时**(带白名单)、 工具侧声明、以及和 Node 端逐项对拍 - 实测真机:界面显示 18 项来自内核 → 点 + 保存 → 内核 heartbeat 15→25 → 恢复默认 → 回 15;askUser 显示"不限时" 文档:README §3.13;docs/AI界面能力.md 的"不限时要三处一起改"补上可调入口。 版本 2.0.46。
988 lines
38 KiB
Python
988 lines
38 KiB
Python
"""
|
||
持久化:设置 / 会话 / 智能体。
|
||
|
||
对应 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
|
||
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)
|
||
|
||
|
||
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
|