## 界面
- 新增 AgentEditScreen:智能体的**全屏**编辑界面。字段从 8 个涨到二十多个
(基本信息 / 外观四件套 / 人设 / 模型引用 / 世界观绑定 / 情绪开关 / Token 限额 /
技能多选 / 音色),弹窗装不下 —— AGENTS.md 那张表写得很清楚。
三处容易困惑的地方在界面上直接说清:介绍文案 vs 一句话介绍、
绑世界观 = 记忆变共享、限额留空 = 无限制。
- 新增 Provider「设置外观图片」接口(/api/agents/<id>/asset):
选图 → 读字节 → base64 → **立刻上传**(不等保存,图可能好几 MB)。
传空 data = 清除该槽位(回到内置默认),这是"我不想要这张图了"的唯一出口。
- 会话级 Token 用量(需求 4.1):输入框上方一行小字(输入/输出分列),
点「累计 ›」进智能体累计用量页。**按消息加起来算**,所以"重新生成"
替换上一条时消耗自动消失,不会虚高。
- 删掉 AgentsScreen 里那个被取代的 AgentEditDialog(179 行)——
用带断言的脚本删(scripts/migrate-drop-agent-dialog.py),
不留死代码,也不冒"按行号剪贴算错下标"的险。
## ★★ 一个必须记下来的教训:Python 语法错误构建阶段不报
加 /api/agents/<id>/asset 时手滑把函数签名和 docstring 挤到了一行
(上一个"删空行"的 edit 把换行吃掉了),结果:
Gradle: BUILD SUCCESSFUL ← 完全看不出来
APK: 正常产出、正常安装
打开 App:「本地内核启动失败:IndentationError (agent_api.py, line 797)」
**Gradle 不编译 Python**(Chaquopy 只是把 .py 打进 APK),所以这类错误
一路畅通到手机上才炸,而且炸的是整个内核 —— App 直接不可用。
Kotlin 那边一个类型不对就编不过,落差太大。
修法:scripts/build-apk.mjs 里加一道 **Python 语法自检**(用和 Chaquopy
同一个解释器 py_compile 一遍内核里所有 .py,几秒钟),有错直接中止构建。
以后不用靠人记得跑。
顺带:我自己那次也是"改完没跑 py_compile 就构建"——探针脚本能覆盖运行时,
但覆盖不了"根本 import 不进来",所以语法检查必须在构建这一层。
## 其它
- VoicePickerInline 从 private 改 internal(编辑界面要复用;它是既有的
音色选择器,这里只选音色不选引擎 —— 引擎属于全局设置,
混在一起必然出现"换了引擎、音色还是上一家的")。
- 用户可见文案里的字面 `**` 去掉(普通 Text 不渲染 Markdown)。
验证:探针 11 节 60+ 项全绿;装机确认内核恢复、管理列表、全屏编辑界面
(基本信息 + 外观槽位带预览与清除)。
932 lines
35 KiB
Python
932 lines
35 KiB
Python
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||
|
||
## 为什么单独一个模块
|
||
|
||
`app.py` 已经 1800 行,而这一批有二十多个接口。抽出来之后:
|
||
|
||
· 路由写得下、看得清(一段一段对应需求的章节)
|
||
· `app.py` 只要在它的路由链里加一句 `agent_api.handle(...)` 就行
|
||
· 这一批接口的**数据源**(`store` 的 JSON + `agentdb` 的 SQLite)也集中在一处,
|
||
以后换存储只改这里
|
||
|
||
## 路由总表
|
||
|
||
GET/POST /api/agents 列表 / 新建
|
||
PATCH/DELETE /api/agents/<id> 改 / 删
|
||
GET /api/agents/<id>/memories 记忆列表
|
||
POST /api/agents/<id>/memories 手动加一条
|
||
POST /api/agents/<id>/memories/summarize AI 整理(一次独立 LLM 调用)
|
||
GET/POST /api/agents/<id>/memories/export|import 记忆 JSON 导出/导入
|
||
GET /api/agents/<id>/suggestion AI 提的"该整理记忆了"
|
||
GET/PUT /api/agents/<id>/emotion 情绪
|
||
POST /api/agents/<id>/skills 绑定 Skill(整体替换)
|
||
GET /api/agents/<id>/usage Token 用量
|
||
POST /api/agents/<id>/usage/reset 清零
|
||
GET /api/agents/<id>/package 导出智能体包(base64 zip)
|
||
POST /api/agents/import 导入智能体包
|
||
PATCH/DELETE /api/memories/<mid> 改 / 删一条
|
||
POST /api/memories/<mid>/pin 标记「必须保留」
|
||
GET/POST /api/worldviews (+ /<id>) 世界观 CRUD
|
||
GET/POST /api/model-entries (+ /<id>) 全局模型列表 CRUD
|
||
GET/POST /api/skills (+ /<id>) Skill CRUD
|
||
GET/POST /api/skills/export|import Skill JSON
|
||
GET/POST /api/worldviews/<id>/package|import
|
||
|
||
★ `/api/model-entries` 而不是 `/api/models`:后者早就被"**拉上游**的可用模型列表"
|
||
占了(`app.py` 的 `/api/models` 会去请求提供商的 `/v1/models`)。
|
||
两个东西完全不是一回事,不能共用一个路径。
|
||
"""
|
||
|
||
import base64
|
||
import io
|
||
import json
|
||
import os
|
||
import re
|
||
import sys
|
||
import zipfile
|
||
|
||
import agentdb
|
||
import paths
|
||
import store
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 小工具
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
_SAFE_NAME = re.compile(r'[^\w.\-\u4e00-\u9fff]+')
|
||
|
||
|
||
def _safe_segment(name: str) -> str:
|
||
"""
|
||
包里的文件名/目录名清洗。
|
||
|
||
★ 防路径穿越:zip 里完全可以有一条叫 `../../settings.json` 的条目,
|
||
照原样拼路径就会**写出数据目录之外**。所以只保留字母数字下划线
|
||
连字符点号和中文,其余一律换成下划线。
|
||
"""
|
||
base = os.path.basename(str(name or '').replace('\\', '/'))
|
||
cleaned = _SAFE_NAME.sub('_', base).strip('._')
|
||
return cleaned[:80] or 'file'
|
||
|
||
|
||
def _asset_dir(owner_id: str) -> str:
|
||
d = os.path.join(paths.get().agent_assets_dir, _safe_segment(owner_id))
|
||
os.makedirs(d, exist_ok=True)
|
||
return d
|
||
|
||
|
||
def _read_zip(data: bytes) -> dict:
|
||
"""
|
||
解一个 zip,返回 `{相对路径: 字节}`。
|
||
|
||
★ 只收**文件**、忽略目录;条目数/总大小有上限(防 zip 炸弹:
|
||
一个 10KB 的 zip 能解出几十 GB)。
|
||
"""
|
||
out = {}
|
||
total = 0
|
||
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
||
for info in z.infolist():
|
||
if info.is_dir():
|
||
continue
|
||
if len(out) >= 200:
|
||
raise ValueError('包里文件太多了(上限 200 个)')
|
||
total += info.file_size
|
||
if total > 60 * 1024 * 1024:
|
||
raise ValueError('包解出来太大了(上限 60MB)')
|
||
out[info.filename] = z.read(info)
|
||
return out
|
||
|
||
|
||
def _zip_of(files: dict) -> bytes:
|
||
buf = io.BytesIO()
|
||
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as z:
|
||
for name, data in files.items():
|
||
z.writestr(name, data)
|
||
return buf.getvalue()
|
||
|
||
|
||
def _pick_asset(files: dict, wanted: str):
|
||
"""
|
||
按 `smartInfo.json` 里写的文件名找那个资源。
|
||
|
||
★ 找不到时**退一步**按扩展名猜一个:用户手写的包经常是
|
||
`"front": "角色图.png"` 但实际文件叫 `character.png` ——
|
||
严格匹配的话整张图就白丢了,而"图没显示"用户只会觉得功能坏了。
|
||
"""
|
||
if not wanted:
|
||
return None
|
||
want = os.path.basename(str(wanted).replace('\\', '/')).lower()
|
||
for name, data in files.items():
|
||
if os.path.basename(name).lower() == want:
|
||
return name, data
|
||
stem, ext = os.path.splitext(want)
|
||
if not ext:
|
||
return None
|
||
for name, data in files.items():
|
||
if os.path.splitext(name)[1].lower() == ext:
|
||
return name, data
|
||
return None
|
||
|
||
|
||
def _save_assets(owner_id: str, files: dict, image_spec: dict) -> dict:
|
||
"""
|
||
把包里的四件套落到磁盘,返回新的 image 字段(**存绝对路径**)。
|
||
|
||
★ 为什么存路径而不是存"包内文件名":包解完就没了(用户不会留着那个 zip),
|
||
而界面每次都要显示它 —— 存文件名的话每次都得再去找一遍包。
|
||
"""
|
||
out = {}
|
||
target_dir = _asset_dir(owner_id)
|
||
for key in ('front', 'back', 'border-main', 'border-info'):
|
||
hit = _pick_asset(files, (image_spec or {}).get(key))
|
||
if not hit:
|
||
continue
|
||
name, data = hit
|
||
dest = os.path.join(target_dir, f'{key}-{_safe_segment(name)}')
|
||
with open(dest, 'wb') as fh:
|
||
fh.write(data)
|
||
out[key] = dest
|
||
return out
|
||
|
||
|
||
def _llm_once(settings: dict, agent: dict, system: str, user: str):
|
||
"""
|
||
跑一次**独立**的 LLM 调用,返回 `(文本, usage)`。
|
||
|
||
给"AI 整理记忆"用(需求 3.2:一次独立 LLM 调用)。
|
||
★ 不用工具、不开思考 —— 整理是个纯文本活,开思考只是白花时间和 token。
|
||
"""
|
||
import providers
|
||
|
||
provider = store.provider_info(settings, agent)
|
||
chunks = []
|
||
usage = None
|
||
for ev in providers.stream_chat(
|
||
provider=provider.get('provider') or settings.get('provider'),
|
||
base_url=provider.get('baseUrl'),
|
||
api_key=settings.get('apiKey') or '',
|
||
model=provider.get('model'),
|
||
messages=[
|
||
{'role': 'system', 'content': system},
|
||
{'role': 'user', 'content': user},
|
||
],
|
||
temperature=0.2,
|
||
thinking_level='off',
|
||
):
|
||
kind = ev.get('type')
|
||
if kind == 'text':
|
||
chunks.append(ev['text'])
|
||
elif kind == 'usage':
|
||
import agent_loop
|
||
|
||
usage = agent_loop.add_usage(usage, ev.get('usage'))
|
||
return ''.join(chunks), usage
|
||
|
||
|
||
def _extract_json(text: str):
|
||
"""
|
||
从模型回复里抠出 JSON。
|
||
|
||
★ 必须容错:模型几乎总会把 JSON 包在 ```json 代码块里,
|
||
直接 `json.loads` 十次有八次失败。而且失败的表现是"整理功能报错",
|
||
用户根本不知道是模型多打了三个反引号。
|
||
"""
|
||
raw = (text or '').strip()
|
||
fence = re.search(r'```(?:json)?\s*([\s\S]*?)```', raw)
|
||
if fence:
|
||
raw = fence.group(1).strip()
|
||
try:
|
||
return json.loads(raw)
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
# 再退一步:从第一个 [ 或 { 到最后一个 ] 或 }
|
||
for left, right in (('[', ']'), ('{', '}')):
|
||
i, j = raw.find(left), raw.rfind(right)
|
||
if i >= 0 and j > i:
|
||
try:
|
||
return json.loads(raw[i:j + 1])
|
||
except Exception: # noqa: BLE001
|
||
continue
|
||
raise ValueError('模型没有返回能解析的 JSON')
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 记忆
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def _memory_space(agent: dict) -> str:
|
||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||
|
||
|
||
def _memory_payload(agent: dict) -> dict:
|
||
"""一个记忆空间的完整视图(列表 + 情绪 + 用量),界面进页面时一次拿够"""
|
||
scope = _memory_space(agent)
|
||
items = agentdb.memory_list(scope)
|
||
return {
|
||
'ok': True,
|
||
'shared': bool(agent.get('worldviewId')), # 是不是共享空间(界面要提示)
|
||
'worldviewId': agent.get('worldviewId') or '',
|
||
'memories': items,
|
||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||
}
|
||
|
||
|
||
MEMORY_SUMMARY_SYSTEM = '\n'.join([
|
||
'你是一个记忆整理器。用户会给你一份记忆清单(JSON 数组),',
|
||
'你要把**零散、重复、可以合并**的条目压缩成更少、更完整的几条。',
|
||
'',
|
||
'规则:',
|
||
'1. 只输出一个 JSON 数组,每项 {"title": "...", "content": "..."},不要任何别的文字。',
|
||
'2. **不许编造**:只能合并和改写已有的信息,不能新增原始记忆里没有的事实。',
|
||
'3. 合并同类项:说同一件事的几条合成一条;时间上连续的经过可以并成一条。',
|
||
'4. 具体的数字、名字、日期**必须保留**("他每月话费 36"不能变成"他有话费支出")。',
|
||
'5. 条数控制在原来的 1/2 到 2/3;如果本来就不多(少于 8 条),原样返回即可。',
|
||
'6. 用中文,标题短(10 字以内),正文说清楚。',
|
||
])
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 路由
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def handle(handler, pathname: str, method: str) -> bool:
|
||
"""
|
||
处理一个请求。返回 True = 已经响应过了。
|
||
|
||
[handler] 是 `app.py` 的那个 Handler 实例(借用它的 send_json / read_json_body)。
|
||
"""
|
||
seg = [s for s in (pathname or '').split('/') if s]
|
||
# 全都是 /api/... 开头的
|
||
if len(seg) < 2 or seg[0] != 'api':
|
||
return False
|
||
|
||
def body():
|
||
"""
|
||
解析请求体。
|
||
|
||
★ 做成**函数**而不是进来就解析:GET 请求没有 body,提前解析会抛异常。
|
||
★ 但注意:往下传的时候必须**调用它**(`body()`)——
|
||
直接把函数对象当 dict 传,报的是 `'function' object has no attribute 'get'`,
|
||
而那个错看起来像"字段名写错了"。这里踩过一次。
|
||
"""
|
||
try:
|
||
return handler.read_json_body()
|
||
except Exception: # noqa: BLE001
|
||
return {}
|
||
|
||
def err(code: int, msg: str):
|
||
handler.send_json(code, {'ok': False, 'error': msg})
|
||
|
||
try:
|
||
# ---------------- 智能体 ----------------
|
||
if seg[1] == 'agents' and len(seg) == 2:
|
||
if method == 'GET':
|
||
handler.send_json(200, {'ok': True, 'agents': store.list_agents()})
|
||
return True
|
||
if method == 'POST':
|
||
handler.send_json(200, {'ok': True, 'agent': store.create_agent(body())})
|
||
return True
|
||
|
||
if seg[1] == 'agents' and len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||
return _import_agent(handler, body(), err)
|
||
|
||
if seg[1] == 'agents' and len(seg) == 3:
|
||
aid = seg[2]
|
||
if method == 'PATCH':
|
||
updated = store.update_agent(aid, body())
|
||
if updated is None:
|
||
err(404, '没有这个智能体')
|
||
else:
|
||
handler.send_json(200, {'ok': True, 'agent': updated})
|
||
return True
|
||
if method == 'DELETE':
|
||
# ★ 内置智能体不给删:删了内核下次读 agents.json 会**重建**它,
|
||
# 用户看到"删了又回来"(界面也拦,但接口不能只靠界面拦)
|
||
target = store.get_agent(aid)
|
||
if target and target.get('builtin'):
|
||
err(400, '内置智能体不能删除(删了会被自动重建)')
|
||
return True
|
||
handler.send_json(200, {'ok': True, 'deleted': store.delete_agent(aid)})
|
||
return True
|
||
|
||
# ---------------- 记忆(挂在智能体下) ----------------
|
||
if seg[1] == 'agents' and len(seg) >= 4 and seg[3] == 'memories':
|
||
return _memories(handler, method, seg, body, err)
|
||
|
||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'suggestion':
|
||
agent = store.get_agent(seg[2])
|
||
if not agent:
|
||
err(404, '没有这个智能体')
|
||
return True
|
||
handler.send_json(200, {
|
||
'ok': True,
|
||
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||
})
|
||
return True
|
||
|
||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'emotion':
|
||
agent = store.get_agent(seg[2])
|
||
if not agent:
|
||
err(404, '没有这个智能体')
|
||
return True
|
||
if method == 'GET':
|
||
handler.send_json(200, {'ok': True, 'emotion': agentdb.emotion_get(agent['id'])})
|
||
return True
|
||
if method in ('PUT', 'POST'):
|
||
emo = str(body().get('emotion') or '')
|
||
agentdb.emotion_set(agent['id'], emo[:200])
|
||
handler.send_json(200, {'ok': True, 'emotion': emo[:200]})
|
||
return True
|
||
|
||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'skills':
|
||
agent = store.get_agent(seg[2])
|
||
if not agent:
|
||
err(404, '没有这个智能体')
|
||
return True
|
||
if method == 'GET':
|
||
handler.send_json(200, {'ok': True, 'skillIds': agentdb.skills_of(agent['id'])})
|
||
return True
|
||
if method in ('PUT', 'POST'):
|
||
ids = body().get('skillIds') or []
|
||
agentdb.bind_skills(agent['id'], ids if isinstance(ids, list) else [])
|
||
handler.send_json(200, {'ok': True, 'skillIds': agentdb.skills_of(agent['id'])})
|
||
return True
|
||
|
||
# ---------------- Token 用量 ----------------
|
||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'usage':
|
||
agent = store.get_agent(seg[2])
|
||
if not agent:
|
||
err(404, '没有这个智能体')
|
||
return True
|
||
if method == 'GET':
|
||
handler.send_json(200, {'ok': True, **_usage_payload(agent)})
|
||
return True
|
||
if method == 'POST':
|
||
agentdb.token_reset(agent['id'])
|
||
handler.send_json(200, {'ok': True, **_usage_payload(agent)})
|
||
return True
|
||
|
||
# ---------------- 智能体包 ----------------
|
||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'package' and method == 'GET':
|
||
return _export_agent(handler, seg[2], err)
|
||
|
||
# ---------------- 外观图片(四件套)----------------
|
||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'asset' and method == 'POST':
|
||
return _set_asset(handler, seg[2], body(), err)
|
||
|
||
# ---------------- 单条记忆 ----------------
|
||
if seg[1] == 'memories' and len(seg) == 3:
|
||
mid = seg[2]
|
||
item = agentdb.memory_get(mid)
|
||
if not item:
|
||
err(404, '没有这条记忆')
|
||
return True
|
||
if method == 'PATCH':
|
||
b = body()
|
||
# ★ 界面上改是**用户**在改,不受"只能改自己写的"限制
|
||
# (那条限制是给 AI 的工具定的,见 agent_tools.py)
|
||
updated = agentdb.memory_update(
|
||
mid,
|
||
title=b.get('title') if 'title' in b else None,
|
||
content=b.get('content') if 'content' in b else None,
|
||
)
|
||
handler.send_json(200, {'ok': True, 'memory': updated})
|
||
return True
|
||
if method == 'DELETE':
|
||
agentdb.memory_forget(mid)
|
||
handler.send_json(200, {'ok': True, 'deleted': True})
|
||
return True
|
||
|
||
if seg[1] == 'memories' and len(seg) == 4 and seg[3] == 'pin' and method == 'POST':
|
||
ok = agentdb.memory_set_pinned(seg[2], bool(body().get('pinned', True)))
|
||
handler.send_json(200, {'ok': ok})
|
||
return True
|
||
|
||
# ---------------- 世界观 / 模型列表 / Skill ----------------
|
||
res = _resource_route(handler, seg, method, body, err)
|
||
if res is not None:
|
||
return res
|
||
|
||
except Exception as exc: # noqa: BLE001 - 接口层不能把内核带崩
|
||
print(f'[agent_api] {pathname} 出错:{exc}', file=sys.stderr)
|
||
err(500, f'{type(exc).__name__}: {exc}')
|
||
return True
|
||
return False
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 记忆的具体路由
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def _memories(handler, method: str, seg: list, body, err) -> bool:
|
||
agent = store.get_agent(seg[2])
|
||
if not agent:
|
||
err(404, '没有这个智能体')
|
||
return True
|
||
tail = seg[4:]
|
||
|
||
# /memories
|
||
if not tail:
|
||
if method == 'GET':
|
||
handler.send_json(200, _memory_payload(agent))
|
||
return True
|
||
if method == 'POST':
|
||
b = body()
|
||
item = agentdb.memory_add(
|
||
scope=_memory_space(agent),
|
||
title=str(b.get('title') or ''),
|
||
content=str(b.get('content') or ''),
|
||
# 用户手动加的:author 记成自己(空 = 不是任何智能体写的)
|
||
author_agent=str(b.get('author_agent') or ''),
|
||
)
|
||
handler.send_json(200, {'ok': True, 'memory': item})
|
||
return True
|
||
|
||
# /memories/summarize —— AI 整理(需求 3.2)
|
||
if tail == ['summarize'] and method == 'POST':
|
||
return _summarize(handler, agent, err)
|
||
|
||
# /memories/export
|
||
if tail == ['export'] and method == 'GET':
|
||
payload = _memory_export(agent)
|
||
handler.send_json(200, {'ok': True, **payload})
|
||
return True
|
||
|
||
# /memories/import
|
||
if tail == ['import'] and method == 'POST':
|
||
return _memory_import(handler, agent, body(), err)
|
||
|
||
return False
|
||
|
||
|
||
def _memory_export(agent: dict) -> dict:
|
||
"""
|
||
导出成需求 3.4 那个格式。
|
||
|
||
★ **不含 `author_agent`**:需求原话"导出不含 author_agent(导入后全部归属当前智能体)"。
|
||
带上它的话,把记忆导给另一个智能体之后,它会在共享空间里
|
||
顶着"别人写的"身份出现、连自己都改不了。
|
||
"""
|
||
scope = _memory_space(agent)
|
||
items = [
|
||
{'title': m.get('title') or '', 'content': m.get('content') or '',
|
||
'pinned': bool(m.get('pinned'))}
|
||
for m in agentdb.memory_list(scope)
|
||
]
|
||
return {
|
||
'type': 'world-memory' if agent.get('worldviewId') else 'agent-memory',
|
||
'version': 1,
|
||
'name': agent.get('name') or '',
|
||
'smartMemory': items,
|
||
'Emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||
}
|
||
|
||
|
||
def _memory_import(handler, agent: dict, body: dict, err) -> bool:
|
||
"""
|
||
导入记忆(需求 3.4)。默认**合并**,可选**覆盖**。
|
||
|
||
合并按**标题去重**:标题相同的跳过(保留现有的)。
|
||
"""
|
||
payload = body.get('data') if isinstance(body.get('data'), dict) else body
|
||
if not isinstance(payload, dict) or 'smartMemory' not in payload:
|
||
err(400, '这不是一个记忆文件(缺少 smartMemory 字段)')
|
||
return True
|
||
if payload.get('type') and payload['type'] not in ('agent-memory', 'world-memory'):
|
||
err(400, f'不认识的文件类型:{payload.get("type")}')
|
||
return True
|
||
|
||
incoming = payload.get('smartMemory')
|
||
if not isinstance(incoming, list):
|
||
err(400, 'smartMemory 必须是数组')
|
||
return True
|
||
|
||
scope = _memory_space(agent)
|
||
mode = str(body.get('mode') or 'merge').lower()
|
||
before = len(agentdb.memory_list(scope))
|
||
|
||
if mode == 'replace':
|
||
agentdb.memory_replace_all(scope, incoming, keep_pinned=False)
|
||
added = len(agentdb.memory_list(scope)) - 0
|
||
skipped = 0
|
||
else:
|
||
existing = {(m.get('title') or '').strip() for m in agentdb.memory_list(scope)}
|
||
added = skipped = 0
|
||
for it in incoming:
|
||
if not isinstance(it, dict):
|
||
continue
|
||
title = str(it.get('title') or '').strip()
|
||
if title and title in existing:
|
||
skipped += 1
|
||
continue
|
||
agentdb.memory_add(
|
||
scope=scope,
|
||
title=title,
|
||
content=str(it.get('content') or ''),
|
||
author_agent=agent.get('id') or '',
|
||
)
|
||
existing.add(title)
|
||
added += 1
|
||
|
||
emotion_kept = True
|
||
if mode == 'replace' and payload.get('Emotion') is not None:
|
||
# 覆盖模式连情绪一起换(需求 3.4);合并模式保留当前值
|
||
agentdb.emotion_set(agent.get('id') or '', str(payload.get('Emotion') or ''))
|
||
emotion_kept = False
|
||
|
||
return _send_json_ok(handler, {
|
||
'mode': mode,
|
||
'added': added,
|
||
'skipped': skipped,
|
||
'before': before,
|
||
'after': len(agentdb.memory_list(scope)),
|
||
'emotionReplaced': not emotion_kept,
|
||
})
|
||
|
||
|
||
def _summarize(handler, agent: dict, err) -> bool:
|
||
"""
|
||
AI 整理记忆(需求 3.2)。
|
||
|
||
流程:全部记忆 + pinned 清单一并给模型 → 拿回压缩后的列表 →
|
||
整体写回(**pinned 的原样保留**)。
|
||
|
||
★ Token 消耗计入该智能体统计(需求明确要求)。
|
||
★ **不受限额约束**(需求 3.1 的豁免条款)—— 额度用完了还得能整理记忆,
|
||
否则用户的记忆就永远是一团乱麻、还解不开。
|
||
"""
|
||
scope = _memory_space(agent)
|
||
items = agentdb.memory_list(scope)
|
||
if not items:
|
||
return _send_json_ok(handler, {'summarized': False, 'reason': '还没有记忆可以整理'})
|
||
|
||
settings = store.read_settings()
|
||
plain = [
|
||
{'title': m.get('title') or '', 'content': m.get('content') or '',
|
||
'pinned': bool(m.get('pinned'))}
|
||
for m in items
|
||
]
|
||
try:
|
||
text, usage = _llm_once(
|
||
settings, agent, MEMORY_SUMMARY_SYSTEM,
|
||
json.dumps(plain, ensure_ascii=False, indent=1),
|
||
)
|
||
merged = _extract_json(text)
|
||
except Exception as exc: # noqa: BLE001
|
||
err(500, f'整理失败:{exc}')
|
||
return True
|
||
|
||
if isinstance(merged, dict):
|
||
merged = merged.get('smartMemory') or merged.get('items') or []
|
||
if not isinstance(merged, list):
|
||
err(500, '模型返回的不是列表')
|
||
return True
|
||
|
||
# ★ pinned 的那几条**不能进这次替换**(需求 3.2:原样保留、不参与合并)
|
||
kept = [m for m in items if m.get('pinned')]
|
||
kept_titles = {(m.get('title') or '').strip() for m in kept}
|
||
clean = [
|
||
{'title': str(x.get('title') or ''), 'content': str(x.get('content') or '')}
|
||
for x in merged
|
||
if isinstance(x, dict) and (x.get('title') or x.get('content'))
|
||
and (str(x.get('title') or '').strip() not in kept_titles)
|
||
]
|
||
if not clean:
|
||
err(500, '模型返回的列表是空的,为了不丢数据这次不写回')
|
||
return True
|
||
|
||
agentdb.memory_replace_all(scope, clean, keep_pinned=True)
|
||
|
||
# 计入用量(记失败不影响结果)
|
||
try:
|
||
import agent_loop
|
||
|
||
i, o = agent_loop.usage_pair(usage)
|
||
if i or o:
|
||
model = (store.provider_info(settings, agent) or {}).get('model') or ''
|
||
agentdb.token_add(agent.get('id') or '', model, i, o)
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f'[agent_api] 整理记忆的用量没记上:{exc}', file=sys.stderr)
|
||
|
||
store.take_summary_suggestion(agent.get('id') or '')
|
||
return _send_json_ok(handler, {
|
||
'summarized': True,
|
||
'before': len(items),
|
||
'after': len(agentdb.memory_list(scope)),
|
||
'keptPinned': len(kept),
|
||
})
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 三种资源的通用路由
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
_RES_PATH = {
|
||
'worldviews': 'worldviews',
|
||
'model-entries': 'models',
|
||
'skills': 'skills',
|
||
}
|
||
|
||
|
||
def _resource_route(handler, seg: list, method: str, body, err):
|
||
if seg[1] not in _RES_PATH:
|
||
return None
|
||
name = _RES_PATH[seg[1]]
|
||
|
||
# 包 / JSON 的导入导出(世界观包、Skill 文件)
|
||
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||
return _resource_import(handler, name, body(), err)
|
||
if len(seg) == 4 and seg[3] == 'package' and method == 'GET':
|
||
return _resource_export(handler, name, seg[2], err)
|
||
if len(seg) == 4 and seg[3] == 'export' and method == 'GET':
|
||
return _resource_export(handler, name, seg[2], err)
|
||
|
||
if len(seg) == 2:
|
||
if method == 'GET':
|
||
handler.send_json(200, {'ok': True, 'items': store.list_resource(name)})
|
||
return True
|
||
if method == 'POST':
|
||
handler.send_json(200, {'ok': True, 'item': store.create_resource(name, body())})
|
||
return True
|
||
|
||
if len(seg) == 3:
|
||
rid = seg[2]
|
||
if method == 'PATCH':
|
||
updated = store.update_resource(name, rid, body())
|
||
if updated is None:
|
||
err(404, '没有这一项')
|
||
else:
|
||
handler.send_json(200, {'ok': True, 'item': updated})
|
||
return True
|
||
if method == 'DELETE':
|
||
handler.send_json(200, {'ok': True, 'deleted': store.delete_resource(name, rid)})
|
||
return True
|
||
return None
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 导入导出
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def _usage_payload(agent: dict) -> dict:
|
||
usage = agentdb.token_usage(agent.get('id') or '')
|
||
try:
|
||
limit = int(float(agent.get('tokenLimit') or 0))
|
||
except (TypeError, ValueError):
|
||
limit = 0
|
||
used = usage['total']['input'] + usage['total']['output']
|
||
# 单价(元/千 Token):在**全局模型列表**里配,填了才估费用
|
||
price = 0.0
|
||
mid = agent.get('modelId') or ''
|
||
if mid:
|
||
entry = store.get_resource('models', mid) or {}
|
||
try:
|
||
price = float(entry.get('pricePerK') or 0)
|
||
except (TypeError, ValueError):
|
||
price = 0.0
|
||
return {
|
||
'agentId': agent.get('id') or '',
|
||
'name': agent.get('name') or '',
|
||
'input': usage['total']['input'],
|
||
'output': usage['total']['output'],
|
||
'total': used,
|
||
'byModel': usage['byModel'],
|
||
'limit': limit,
|
||
'remaining': None if limit <= 0 else max(0, limit - used),
|
||
'pricePerK': price,
|
||
'cost': round(used / 1000.0 * price, 4) if price > 0 else None,
|
||
}
|
||
|
||
|
||
def _export_agent(handler, agent_id: str, err) -> bool:
|
||
"""导出智能体包(需求 2.5:zip,只含 smartInfo.json + 图片)"""
|
||
agent = store.get_agent(agent_id)
|
||
if not agent:
|
||
err(404, '没有这个智能体')
|
||
return True
|
||
files = {}
|
||
image = agent.get('image') or {}
|
||
for key, path in image.items():
|
||
if not path or not os.path.isfile(path):
|
||
continue
|
||
try:
|
||
with open(path, 'rb') as fh:
|
||
files[f'{key}{os.path.splitext(path)[1]}'] = fh.read()
|
||
except OSError:
|
||
continue
|
||
# ★ 包里**不存内部 ID、不存模型引用、不存限额**(需求 2.5 的"包的边界约定")
|
||
info = {
|
||
'name': agent.get('name') or '',
|
||
'description': agent.get('description') or '',
|
||
'prompt': agent.get('systemPrompt') or '',
|
||
'image': {k: f'{k}{os.path.splitext(v)[1]}' for k, v in image.items() if v},
|
||
}
|
||
files['smartInfo.json'] = json.dumps(info, ensure_ascii=False, indent=2).encode('utf-8')
|
||
blob = _zip_of(files)
|
||
return _send_json_ok(handler, {
|
||
'fileName': f'{(agent.get("name") or "agent")}.zip',
|
||
'data': base64.b64encode(blob).decode('ascii'),
|
||
'bytes': len(blob),
|
||
})
|
||
|
||
|
||
#: 外观四件套的槽位名(和需求 2.5 的 smartInfo.json 一一对应)
|
||
ASSET_KEYS = ('front', 'back', 'border-main', 'border-info')
|
||
|
||
|
||
def _set_asset(handler, agent_id: str, body: dict, err) -> bool:
|
||
"""
|
||
设置外观四件套里的**一个槽位**(需求 2.5)。
|
||
|
||
界面把图片读成 base64 发过来,这里落盘到 `agent-assets/<id>/`,
|
||
再把**路径**写进 `agent.image`。
|
||
|
||
★ 存路径不存字节:展示区和列表每次都要显示它,每次从 base64 解一遍太贵。
|
||
★ `data` 传空 = **清掉这个槽位**(回到内置默认 / 方框)——
|
||
这是"我不想要这张图了"的唯一出口,不给的话用户只能换、不能删。
|
||
"""
|
||
agent = store.get_agent(agent_id)
|
||
if not agent:
|
||
err(404, '没有这个智能体')
|
||
return True
|
||
key = str(body.get('key') or '').strip()
|
||
if key not in ASSET_KEYS:
|
||
err(400, f'不认识的外观槽位:{key}(可选:{"、".join(ASSET_KEYS)})')
|
||
return True
|
||
|
||
image = dict(agent.get('image') or {})
|
||
raw = body.get('data') or body.get('base64') or ''
|
||
if not raw:
|
||
old = image.pop(key, '')
|
||
if old and os.path.isfile(old):
|
||
try:
|
||
os.remove(old)
|
||
except OSError:
|
||
pass
|
||
return _send_json_ok(handler, {'agent': store.update_agent(agent_id, {'image': image}), 'cleared': True})
|
||
|
||
try:
|
||
blob = base64.b64decode(raw)
|
||
except Exception as exc: # noqa: BLE001
|
||
err(400, f'图片数据解不开:{exc}')
|
||
return True
|
||
if len(blob) > 20 * 1024 * 1024:
|
||
err(400, '图片太大了(上限 20MB)')
|
||
return True
|
||
|
||
name = _safe_segment(str(body.get('name') or f'{key}.png'))
|
||
dest = os.path.join(_asset_dir(agent_id), f'{key}-{name}')
|
||
with open(dest, 'wb') as fh:
|
||
fh.write(blob)
|
||
image[key] = dest
|
||
return _send_json_ok(handler, {
|
||
'agent': store.update_agent(agent_id, {'image': image}),
|
||
'path': dest,
|
||
'bytes': len(blob),
|
||
})
|
||
|
||
|
||
def _import_agent(handler, body, err) -> bool:
|
||
"""
|
||
导入智能体包(需求 2.5)。
|
||
|
||
★ **同一个包导入两次 = 两个互相独立的智能体**(需求原话)——
|
||
所以这里每次都 `create_agent` 生成新 UUID,不做"按名字去重"。
|
||
★ 模型引用 / 世界观绑定 / 限额这些**不进包**,导入后用默认值。
|
||
"""
|
||
raw = body.get('data') or body.get('base64') or ''
|
||
if not raw:
|
||
err(400, '缺少包内容')
|
||
return True
|
||
try:
|
||
blob = base64.b64decode(raw)
|
||
files = _read_zip(blob)
|
||
except Exception as exc: # noqa: BLE001
|
||
err(400, f'包读不出来:{exc}')
|
||
return True
|
||
|
||
info = None
|
||
for name in files:
|
||
if os.path.basename(name).lower() == 'smartinfo.json':
|
||
try:
|
||
info = json.loads(files[name].decode('utf-8'))
|
||
except Exception as exc: # noqa: BLE001
|
||
err(400, f'smartInfo.json 解析失败:{exc}')
|
||
return True
|
||
break
|
||
if info is None:
|
||
err(400, '包里没有 smartInfo.json —— 这不是一个智能体包')
|
||
return True
|
||
|
||
agent = store.create_agent({
|
||
'name': str(info.get('name') or '未命名').strip()[:24],
|
||
'description': str(info.get('description') or ''),
|
||
'systemPrompt': str(info.get('prompt') or ''),
|
||
'avatar': 'custom',
|
||
})
|
||
image = _save_assets(agent['id'], files, info.get('image') or {})
|
||
if image:
|
||
agent = store.update_agent(agent['id'], {'image': image}) or agent
|
||
return _send_json_ok(handler, {'agent': agent, 'assets': len(image)})
|
||
|
||
|
||
def _resource_export(handler, name: str, rid: str, err) -> bool:
|
||
item = store.get_resource(name, rid)
|
||
if not item:
|
||
err(404, '没有这一项')
|
||
return True
|
||
if name == 'skills':
|
||
# Skill 是**单个 JSON**(需求 3.7),不是 zip
|
||
payload = {
|
||
'type': 'agent-skill',
|
||
'version': 1,
|
||
'name': item.get('name') or '',
|
||
'content': item.get('content') or '',
|
||
}
|
||
return _send_json_ok(handler, {
|
||
'fileName': f'{(item.get("name") or "skill")}.json',
|
||
'json': json.dumps(payload, ensure_ascii=False, indent=2),
|
||
})
|
||
# 世界观:zip,含 worldInfo.json + 图片
|
||
files = {}
|
||
image = item.get('image') or {}
|
||
for key, path in image.items():
|
||
if not path or not os.path.isfile(path):
|
||
continue
|
||
try:
|
||
with open(path, 'rb') as fh:
|
||
files[f'{key}{os.path.splitext(path)[1]}'] = fh.read()
|
||
except OSError:
|
||
continue
|
||
info = {
|
||
'name': item.get('name') or '',
|
||
'setting': item.get('setting') or '',
|
||
'image': {k: f'{k}{os.path.splitext(v)[1]}' for k, v in image.items() if v},
|
||
}
|
||
files['worldInfo.json'] = json.dumps(info, ensure_ascii=False, indent=2).encode('utf-8')
|
||
blob = _zip_of(files)
|
||
return _send_json_ok(handler, {
|
||
'fileName': f'{(item.get("name") or "world")}.zip',
|
||
'data': base64.b64encode(blob).decode('ascii'),
|
||
'bytes': len(blob),
|
||
})
|
||
|
||
|
||
def _resource_import(handler, name: str, body, err) -> bool:
|
||
if name == 'skills':
|
||
payload = body.get('data') if isinstance(body.get('data'), dict) else body
|
||
if isinstance(payload, str):
|
||
try:
|
||
payload = json.loads(payload)
|
||
except Exception: # noqa: BLE001
|
||
err(400, '不是合法的 JSON')
|
||
return True
|
||
if not isinstance(payload, dict) or not (payload.get('content') or payload.get('name')):
|
||
err(400, '这不是一个 Skill 文件(缺 name / content)')
|
||
return True
|
||
if payload.get('type') and payload['type'] != 'agent-skill':
|
||
err(400, f'不认识的文件类型:{payload.get("type")}')
|
||
return True
|
||
item = store.create_resource('skills', {
|
||
'name': payload.get('name') or '未命名 Skill',
|
||
'content': payload.get('content') or '',
|
||
})
|
||
return _send_json_ok(handler, {'item': item})
|
||
|
||
# 世界观包
|
||
raw = body.get('data') or body.get('base64') or ''
|
||
if not raw:
|
||
err(400, '缺少包内容')
|
||
return True
|
||
try:
|
||
files = _read_zip(base64.b64decode(raw))
|
||
except Exception as exc: # noqa: BLE001
|
||
err(400, f'包读不出来:{exc}')
|
||
return True
|
||
info = None
|
||
for fname in files:
|
||
if os.path.basename(fname).lower() == 'worldinfo.json':
|
||
try:
|
||
info = json.loads(files[fname].decode('utf-8'))
|
||
except Exception as exc: # noqa: BLE001
|
||
err(400, f'worldInfo.json 解析失败:{exc}')
|
||
return True
|
||
break
|
||
if info is None:
|
||
err(400, '包里没有 worldInfo.json —— 这不是一个世界观包')
|
||
return True
|
||
item = store.create_resource('worldviews', {
|
||
'name': str(info.get('name') or '未命名').strip()[:40],
|
||
'setting': str(info.get('setting') or ''),
|
||
})
|
||
image = _save_assets(item['id'], files, info.get('image') or {})
|
||
if image:
|
||
item = store.update_resource('worldviews', item['id'], {'image': image}) or item
|
||
return _send_json_ok(handler, {'item': item, 'assets': len(image)})
|
||
|
||
|
||
def _send_json_ok(handler, payload: dict) -> bool:
|
||
handler.send_json(200, {'ok': True, **payload})
|
||
return True
|