""" 持久化:设置 / 会话 / 智能体。 对应 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 normalize_image(image) -> dict: """ 把 `image` 归一化成 v1.2 的形状(读的时候统一调它)。 ★★ v1.2 把 `front` 从**单个文件名**扩成了**五档立绘表**(需求 2.5): v1.1: "front": "normal.png" v1.2: "front": {"喜": "happy.png", "怒": "angry.png", "哀": "sad.png", "平常": "normal.png", "死亡": "dead.png"} 兼容规则是"**旧格式视为仅有「平常」档**"(需求原话)。 ★ 为什么在**读**的时候归一化、而不是在写的时候:老数据已经在磁盘上了 (`agents.json` 里存的就是字符串),写的时候归一化管不到它们。 读的时候归一化则一次覆盖新旧两种 —— 而且写入路径不用改, "用户手改过 agents.json" 这种情况也不会被冲掉。 归一化**不丢信息**:字典里多出来的档位原样保留(用户可能自己加了「醉」这种)。 """ img = dict(image or {}) front = img.get('front') if isinstance(front, str): # v1.1 的单文件名 → 只有「平常」档 img['front'] = {'平常': front} if front.strip() else {} elif isinstance(front, dict): img['front'] = { str(k): str(v) for k, v in front.items() if str(v or '').strip() } else: img['front'] = {} for key in ('back', 'border-main', 'border-info'): img[key] = str(img.get(key) or '') return img 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/apiKey)。 ★ agent 不为空时,智能体自己的 provider/model/baseUrl **优先**,留空则继承全局。 这样"某个智能体用 DeepSeek、其它还用方舟"是改一个智能体的事, 不用来回切全局设置 —— 而全局设置仍然是没配过的智能体的默认值。 ★★ v1.1 新增一层:智能体可以**引用全局模型列表里的一项**(`modelId`,需求 3.3)。 优先级是: 模型列表那一项(地址/Key/模型标识都从它来,**整组覆盖**) ↓ 没引用 智能体自己的 provider/model/baseUrl ↓ 留空 全局设置 ↓ 还没填 提供商预设 「整组覆盖」是刻意的:模型列表存在的意义就是"配一次到处用、 改 Key 只改一处"。如果只覆盖 model 而 Key 还用全局的, 就会出现"选了 DeepSeek 的模型、却拿方舟的 Key 去调"这种必然 401 的组合。 """ agent = agent or {} entry = None model_id = (agent.get('modelId') or '').strip() if model_id: try: entry = get_resource('models', model_id) except Exception: # noqa: BLE001 - 列表坏了不该让对话发不出去 entry = None if entry: provider_key = (entry.get('provider') or '').strip() or settings.get('provider') preset = PROVIDER_PRESETS.get(provider_key) or _preset_of(settings) return { **preset, 'provider': provider_key, 'baseUrl': (entry.get('apiBase') or '').strip() or preset.get('baseUrl', ''), 'model': (entry.get('model') or '').strip() or preset.get('defaultModel', ''), # ★ Key 也从那一项来(留空才回落全局)—— # "只覆盖 model 不覆盖 Key"必然 401,见上面的注释 'apiKey': (entry.get('apiKey') or '').strip() or settings.get('apiKey') or '', 'modelEntryId': model_id, # ★ 兼容降级(需求 3.3):这个模型不支持 tools 参数 'noTools': bool(entry.get('noTools')), } 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', ''), 'apiKey': settings.get('apiKey') or '', } 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 都存一份。 # # 存法: # /screens/.html 正文 # /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)[^>]*>.*?', ' ', 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, kind: str = 'single', participants: list | None = None) -> dict: """ 新建会话。 ★ v1.2 加了两个字段(需求 §3.9): type single(单聊)/ group(群聊)/ private(私聊记录) participants 群聊的成员 id 列表(单聊为空) 群聊/私聊是**独立实体**,出现在每个参与者的会话列表里 —— 不是"每个智能体各存一份",那样三条记录迟早会不同步。 """ item = { 'id': _rid_conv(), 'title': title, 'agentId': agent_id or '', # ★ 老会话没有这两个字段 → 读的时候当 single 处理(见 toConversation), # 所以不用写迁移:JSON 里少两个键不影响任何东西 'type': kind if kind in ('single', 'group', 'private') else 'single', 'participants': [str(p) for p in (participants or []) if str(p or '').strip()], '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 set_conversation_agent(conv_id: str, agent_id: str) -> None: """ 把会话**认领**给一个智能体(只用于没有主人的老会话)。 ★ 只认领、不"改嫁":已经在别人名下的会话不由这里动 —— 那会让历史消息和提示词对不上(用户报的"串味"就是这么来的)。 ★ 走 `_load_conversations` / `_persist_conversations` 这一对, 不要自己 `_read_json`+`_write_json`:会话有一份**内存缓存**, 绕过它写文件的话,紧接着的 `get_conversation` 读到的还是旧的缓存 (这个错误在探针里被抓到过)。 """ with _lock: data = _load_conversations() for c in data.get('conversations') or []: if c.get('id') == conv_id and not (c.get('agentId') or '').strip(): c['agentId'] = agent_id _persist_conversations() return 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 # ★ v1.2 新增: # inviteMode 拉起其他智能体:silent 直接进场 / confirm 先问用户(§6.1) # contextWindow 对话上下文窗口(§4.3,留空继承全局) # ★ 这两个字段**必须列在这儿** —— 不列的话 _apply_agent_patch 会丢掉, # 表现是"界面上配了、读出来没有"(rulePackId 那个坑一模一样) 'inviteMode', ) AGENT_NUM_FIELDS = ( 'ttsSpeed', # 语速 'tokenLimit', # 0 = 无限制(不是"限额为 0") 'contextWindow', # v1.2 §4.3:这个智能体的对话上下文窗口(轮) ) 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: """ 全部智能体。**出口统一归一化 `image`**(v1.2 的立绘表,见 `normalize_image`)。 ★ 归一化放在这里而不是写入时:老数据(`agents.json` 里 `front` 是字符串) 已经在磁盘上了,写时归一化管不到它们。读时归一化一次覆盖新旧两种, 而且写入路径一行都不用改。 """ file_path = paths.get().agents_file if not os.path.isfile(file_path): _write_json(file_path, {'agents': DEFAULT_AGENTS}) return [normalize_image_agent(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 [normalize_image_agent(dict(a)) for a in DEFAULT_AGENTS] return [normalize_image_agent(a) for a in data['agents']] def normalize_image_agent(agent: dict) -> dict: """把一个智能体(或世界观)的 `image` 归一化。就地改那份 dict,也返回它""" if isinstance(agent, dict): agent['image'] = normalize_image(agent.get('image')) return agent 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', # ★ rulePackId:这个世界观挂的**数值状态包**(需求 §3.6: # "v1.2 起,世界观同时是数值状态包的挂载点")。 # 没有它的话这个字段会被 _apply_resource_patch 丢掉 —— # 表现是"设置界面里配了、读出来没有",排查起来得一路看到字段表。 'text': ('name', 'setting', 'rulePackId'), 'dict': ('image',), 'label': '世界观', }, # 数值状态包(需求附录 D):定义 + 对应 Python 脚本 'rulepacks': { 'file': lambda: paths.get().rulepacks_file, 'key': 'rulepacks', 'text': ('name', 'note'), # info 是解析好的 info.json(stats / statuses 两张表); # scripts 是 {文件名: 源码} —— **整包一起存**,因为脚本要落盘才能跑 'dict': ('info', 'scripts'), 'label': '规则包', }, # 全局模型列表(需求 3.3):名称 + API 端点 + Key + 模型标识 + 单价 'models': { 'file': lambda: paths.get().models_file, 'key': 'models', 'text': ('name', 'apiBase', 'apiKey', 'model', 'provider'), 'num': ('pricePerK',), # 元/千 Token,0 = 不显示费用估算 # ★ noTools:这个模型不支持 function calling(需求 3.3 的兼容降级)。 # 打开之后不传 tools、改成正文内的调用约定 —— 见 agent_loop.DEGRADED_HINT。 'bool': ('noTools',), '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] # ★★ **不要对每个值调 `_as_text`**。 # # 原来那么写是因为 `image` 的值全是字符串(路径),转一下无妨。 # 但 v1.2 的规则包里 `info` 的值是**嵌套结构** # (`stats: [{name, min, max, ranges: [...]}]`)—— # 转成字符串之后 `sync_defs` 读到的就是 `"[{'name': 'A'}]"`, # 于是**整个规则引擎静默失效**(解析不出来 → 当成没定义 → 不报错)。 # 这种"看起来存进去了、实际全废"的坑最难查。 item[key] = _json_safe(raw) if isinstance(raw, dict) else {} return item def _json_safe(v): """ 只留下 JSON 存得下的东西(dict / list / 字符串 / 数字 / 布尔 / None)。 别的(set、datetime、自定义对象)转成字符串 —— 不让它们把写盘搞炸, 同时**保留嵌套结构**(这是 `_as_text` 做不到的)。 """ if isinstance(v, dict): return {str(k): _json_safe(x) for k, x in v.items()} if isinstance(v, (list, tuple)): return [_json_safe(x) for x in v] if v is None or isinstance(v, (str, int, float, bool)): return v return str(v) def create_resource(name: str, payload: dict) -> dict: """ 新建一种资源。 ★ 允许 `payload` 里带 `id`(**校验过才用**):规则包需要它 —— 数值定义表的 key 是规则包 id(`sync_defs` 用它写库), 如果 `create_resource` 自己生成 id,调用方就得"先建再改"两步, 中途失败会留下一个没有定义的孤儿包。 已经存在同名 id 时**自动换一个**,不覆盖别人的东西。 """ cfg = _res(name) items = list_resource(name) want_id = _as_text((payload or {}).get('id')).strip() if want_id and (len(want_id) > 64 or any(x.get('id') == want_id for x in items)): want_id = '' # 不合法或撞了 → 当作没给 item = { 'id': want_id or 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