## 缓存友好段序(附录 C 的 v1.2 修订)
主流模型的上下文缓存是**前缀匹配**:一处不同则其后全部失效。
原来的段序把 `<emotion>` 夹在 `<memory>` **前面** —— 情绪一变,
连最长的 memory 段一起失效,而情绪是 AI 每聊几句就可能改的东西。
按稳定性重排:
稳定前缀 {prompt} → <skills> → <worldview> → <memory>
易变尾巴 <stats> → <status> → <emotion> → <peer_emotions>
顺带把 `<stats>`/`<status>` 两个占位段位留好(阶段 3 实现)。先留是为了让
模板和渲染两边**一开始就一致**,否则会有"模板里有、渲染不管"的中间状态,
表现是提示词里原样留着 `{stats}` 大括号。
★ 这是整个 v1.2 里**改动最小、省的钱最多**的一处。
## 缓存统计归一化
三家的字段名完全不同,且后两家**只给命中**、未命中要自己推:
DeepSeek prompt_cache_hit_tokens / prompt_cache_miss_tokens
Claude cache_read_input_tokens
OpenAI prompt_tokens_details.cached_tokens(嵌套)
不归一化的话,界面上那个"缓存命中率"会因为换模型就**静默变成 0** ——
静默的 0 最难发现。都没给时返回 0/0,界面**不显示**那一列,
而不是显示一个假的 0%。
落库:`token_usage` 加 `cache_hit`/`cache_miss` 两列 + 老库迁移。
接口:`_usage_payload` 和 `get_token_usage` 都带上了。
## 验证
探针新增两节 17 项:段序 7 项(含"模板顺序必须和 SECTIONS 一致"、
"空段不能留裸占位符")+ 缓存 10 项(四种格式、跨提供商累加、
落库查询、老库迁移)。
★ 顺带证明了一件事:段序一改,探针第 8 节那条**记着旧顺序**的老断言
立刻变红。顺序是协议的一部分,改它就该有人拦。
五个探针全绿。阶段 2 下半(对话上下文窗口 + 用量界面缓存列)下一轮。
1186 lines
47 KiB
Python
1186 lines
47 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),
|
||
而界面每次都要显示它 —— 存文件名的话每次都得再去找一遍包。
|
||
|
||
★ v1.2:`front` 是**五档立绘表**,所以它单独处理 —— 每一档各自落盘,
|
||
文件名带上档位(`front-喜-happy.png`),否则五档会互相覆盖。
|
||
老格式(单个文件名)落成「平常」档,和需求说的兼容规则一致。
|
||
"""
|
||
out = {}
|
||
target_dir = _asset_dir(owner_id)
|
||
|
||
front = (image_spec or {}).get('front')
|
||
fronts = {}
|
||
if isinstance(front, dict):
|
||
for preset, fname in front.items():
|
||
slot = str(preset or '').strip()
|
||
if not slot:
|
||
continue
|
||
hit = _pick_asset(files, fname)
|
||
if not hit:
|
||
continue
|
||
name, data = hit
|
||
dest = os.path.join(target_dir, f'front-{_safe_segment(slot)}-{_safe_segment(name)}')
|
||
with open(dest, 'wb') as fh:
|
||
fh.write(data)
|
||
fronts[slot] = dest
|
||
elif front:
|
||
hit = _pick_asset(files, front)
|
||
if hit:
|
||
name, data = hit
|
||
dest = os.path.join(target_dir, f'front-{_safe_segment(name)}')
|
||
with open(dest, 'wb') as fh:
|
||
fh.write(data)
|
||
fronts['平常'] = dest
|
||
if fronts:
|
||
out['front'] = fronts
|
||
|
||
for key in ('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=provider.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 _world_memories(handler, wid: str, err) -> bool:
|
||
"""
|
||
一个世界观的共享记忆(只读快照)。
|
||
|
||
★ 为什么世界观也要有这个入口:记忆挂在**空间**上,而空间是世界观定义的
|
||
(`world:<uuid>`)。从智能体进去看到的是"这个空间里的记忆",
|
||
但从世界观进去问的是另一个问题 —— "这个世界里大家共同记得什么"。
|
||
有五个智能体共用同一个世界观时,后者才是你要看的那个视角。
|
||
|
||
★ 只读:增删改仍然从智能体那边做。世界观视角没有"我",
|
||
而共享空间的写入限权是**按 author 判的**(需求 3.6),
|
||
这里没有一个"我"可以拿来判 —— 硬做只会做出一个权限含义不明的界面。
|
||
"""
|
||
world = store.get_resource('worldviews', wid)
|
||
if not world:
|
||
err(404, '没有这个世界观')
|
||
return True
|
||
scope = agentdb.world_scope(wid)
|
||
items = agentdb.memory_list(scope)
|
||
names = {a.get('id'): (a.get('name') or '某人') for a in store.list_agents()}
|
||
for m in items:
|
||
m['authorName'] = names.get((m.get('author_agent') or '').strip(), '')
|
||
return _send_json_ok(handler, {
|
||
'ok': True,
|
||
'worldviewId': wid,
|
||
'name': world.get('name') or '',
|
||
'shared': True,
|
||
'memories': items,
|
||
'count': len(items),
|
||
})
|
||
|
||
|
||
def _memory_space(agent: dict) -> str:
|
||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||
|
||
|
||
def _memory_payload(agent: dict, force_own: bool = False) -> dict:
|
||
"""
|
||
一个记忆空间的完整视图(列表 + 情绪 + 用量)。
|
||
|
||
[force_own] = True 时看**私有空间**,不看当前生效的那个 —— 给界面一个
|
||
"我原来那些记忆去哪了"的入口(复查报告 4.1)。绑定世界观之后,
|
||
默认空间变成 world:<id>,私有空间里那条一条都没丢,只是不在这儿显示。
|
||
"""
|
||
scope = _memory_space(agent)
|
||
own = agentdb.agent_scope(agent.get('id') or '')
|
||
if force_own and scope != own:
|
||
return {
|
||
'ok': True,
|
||
'shared': False,
|
||
'own': True, # 界面据此说明"这是绑定前的私有记忆"
|
||
'activeScope': scope, # 当前生效的是哪个空间
|
||
'worldviewId': agent.get('worldviewId') or '',
|
||
'memories': agentdb.memory_list(own),
|
||
'emotion': agentdb.emotion_state(agent.get('id') or ''),
|
||
'suggestion': '',
|
||
}
|
||
items = agentdb.memory_list(scope)
|
||
# 注入窗口(条数):界面要显示"这一轮实际会带多少条进去",
|
||
# 而"列表里有 300 条"和"带进去 50 条"是完全不同的两件事 ——
|
||
# 不显示的话用户会以为全都在提示词里。
|
||
try:
|
||
window = int((store.read_settings() or {}).get('memoryWindow') or 0)
|
||
except (TypeError, ValueError):
|
||
window = 0
|
||
pinned_count = sum(1 for m in items if m.get('pinned'))
|
||
injected = len(items) if window <= 0 or len(items) <= window else max(window, pinned_count)
|
||
return {
|
||
'ok': True,
|
||
'shared': bool(agent.get('worldviewId')), # 是不是共享空间(界面要提示)
|
||
'own': False,
|
||
'activeScope': scope,
|
||
'worldviewId': agent.get('worldviewId') or '',
|
||
'memories': items,
|
||
# ★ 绑定世界观之后,私有空间里可能还留着以前攒的记忆 ——
|
||
# 条数一并告诉界面,它才知道要不要显示"以前那些在这"这个入口
|
||
'ownCount': 0 if scope == own else len(agentdb.memory_list(own)),
|
||
'window': window,
|
||
'pinnedCount': pinned_count,
|
||
'injected': injected,
|
||
'emotion': agentdb.emotion_state(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_state(agent['id'])})
|
||
return True
|
||
if method in ('PUT', 'POST'):
|
||
b = body()
|
||
# ★ 这条路由是**界面**在用的(记忆页的情绪区)——
|
||
# 所以它**允许**把「死亡」改回别的值:那是需求 3.5 说的
|
||
# "用户手动改回是兜底主权"。禁止自愈只发生在 AI 的工具通道上。
|
||
nxt = agentdb.emotion_set(
|
||
agent['id'],
|
||
preset=str(b.get('preset') or '').strip() or None,
|
||
text=None if b.get('text') is None else str(b.get('text') or '')[:200],
|
||
)
|
||
handler.send_json(200, {'ok': True, 'emotion': nxt})
|
||
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, 'agents', 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:]
|
||
|
||
# `?space=own`:看**私有空间**(复查报告 4.1)。
|
||
#
|
||
# ★ 为什么需要这个:用户在没绑世界观时攒了三个月记忆,一绑世界观,
|
||
# 记忆管理的列表就空了 —— 因为读的空间从 agent:<id> 换成了 world:<id>。
|
||
# 记忆**一条没丢**,但界面不说明的话,用户必然判定"绑定把我的记忆清了"。
|
||
want_own = 'space=own' in (getattr(handler, 'path', '') or '')
|
||
|
||
# /memories
|
||
if not tail:
|
||
if method == 'GET':
|
||
handler.send_json(200, _memory_payload(agent, force_own=want_own))
|
||
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_state(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 '', **agentdb.emotion_from_export(payload.get('Emotion')))
|
||
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 _tag_world_agents(items: list) -> list:
|
||
"""
|
||
给每个世界观补一个 `agents: [{id, name}]` —— "谁绑了它"。
|
||
|
||
★ 为什么在**列表接口**里一起给,而不是开一个 `/worldviews/<id>/agents`:
|
||
界面本来就要拉这个列表(进资源页就拉),多一个子路由只换来
|
||
"多一次请求 + 一个可能和列表不同步的缓存"。这个数据量很小
|
||
(智能体通常几个到几十个),一起算的成本可以忽略。
|
||
|
||
★ 顺便能看出**没绑的**(`agents` 为空)—— 那意味着这个世界观
|
||
目前没人用,它的共享记忆也没有人在读写。
|
||
"""
|
||
by_world = {}
|
||
for a in store.list_agents():
|
||
wid = (a.get('worldviewId') or '').strip()
|
||
if wid:
|
||
by_world.setdefault(wid, []).append({
|
||
'id': a.get('id') or '',
|
||
'name': a.get('name') or '未命名',
|
||
})
|
||
out = []
|
||
for it in items or []:
|
||
it = dict(it)
|
||
it['agents'] = by_world.get((it.get('id') or '').strip(), [])
|
||
out.append(it)
|
||
return out
|
||
|
||
|
||
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] == 'asset' and method == 'POST':
|
||
# 世界观的外观图(需求 3.6:沿用同一套四件套)
|
||
return _set_asset(handler, 'worldviews', seg[2], body(), err)
|
||
if len(seg) == 4 and seg[3] == 'memories' and method == 'GET':
|
||
# 世界观的**共享记忆**(大家共同记得什么)—— 只读视角
|
||
return _world_memories(handler, seg[2], 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':
|
||
items = store.list_resource(name)
|
||
if name == 'worldviews':
|
||
# ★ 给世界观补上"哪些智能体绑了它"(用户要求)。
|
||
# 没有这个的话,你在绑之前想知道"这个世界观已经有谁在用了",
|
||
# 只能回智能体列表一个个翻 —— 而那正是"互通"该解决的问题。
|
||
# 在**列表接口里一起给**,而不是再开一个 `/agents` 子路由:
|
||
# 界面本来就要拉列表,多一次请求只是多一次等待。
|
||
items = _tag_world_agents(items)
|
||
handler.send_json(200, {'ok': True, 'items': items})
|
||
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'],
|
||
# v1.2 缓存统计:两家都没给时是 0/0,界面据此不显示那一列
|
||
'cacheHit': usage['total'].get('cacheHit', 0),
|
||
'cacheMiss': usage['total'].get('cacheMiss', 0),
|
||
'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')
|
||
|
||
#: v1.2 立绘表支持的五档(和情绪 preset 对齐,需求 2.5)
|
||
PORTRAIT_PRESETS = ('喜', '怒', '哀', '平常', '死亡')
|
||
|
||
|
||
def portrait_of(image: dict, preset: str) -> str:
|
||
"""
|
||
**当前该显示哪张立绘**(需求 2.6 的回退链):
|
||
|
||
当前 preset 档 → 平常档 → 旧格式的单一 front → (空串)
|
||
|
||
空串的意思是"没有自定义立绘",界面据此用**内置默认人物**
|
||
(需求 2.6 的最后一级)。
|
||
|
||
★ 为什么由内核算好再给界面:回退链是**一条规则**,而选择界面、对话界面、
|
||
编辑界面的预览三处都要用。各自实现一遍的话,改一处必漏两处 ——
|
||
而这个仓库里"同一逻辑抄两份、改的时候只改一份"已经反复出现过。
|
||
|
||
★ `os.path.isfile` 要查:用户可能手动删过 `agent-assets/` 里的文件,
|
||
指着不存在的路径会让界面显示空白 —— 那比回退到默认图糟得多。
|
||
"""
|
||
if not isinstance(image, dict):
|
||
return ''
|
||
front = image.get('front')
|
||
# 老数据(没归一化的字符串)也要认:有些路径会直接读 JSON,绕过 store
|
||
if isinstance(front, str):
|
||
return front.strip()
|
||
if not isinstance(front, dict):
|
||
return ''
|
||
# ① 当前档 ② 平常档
|
||
for key in (preset, '平常'):
|
||
path = str(front.get(key) or '').strip()
|
||
if path and os.path.isfile(path):
|
||
return path
|
||
# ③ 字典里任何一个还能用的(用户可能只传了「喜」这一档)
|
||
for path in front.values():
|
||
path = str(path or '').strip()
|
||
if path and os.path.isfile(path):
|
||
return path
|
||
return ''
|
||
|
||
|
||
def _set_asset(handler, kind: str, owner_id: str, body: dict, err) -> bool:
|
||
"""
|
||
设置外观四件套里的**一个槽位**。
|
||
|
||
[kind] 是 `'agents'` 或 `'worldviews'` —— 两者用的是同一套四件套
|
||
(需求 3.6 明确说世界观"图片资源沿用四件套与同一套默认回退机制"),
|
||
所以这里只写一份,按 kind 分派到对应的存储。
|
||
|
||
界面把图片读成 base64 发过来,这里落盘到 `agent-assets/<id>/`,
|
||
再把**路径**写进 `image`。
|
||
|
||
★ 存路径不存字节:展示区和列表每次都要显示它,每次从 base64 解一遍太贵。
|
||
★ `data` 传空 = **清掉这个槽位**(回到内置默认 / 方框)——
|
||
这是"我不想要这张图了"的唯一出口,不给的话用户只能换、不能删。
|
||
"""
|
||
if kind == 'agents':
|
||
owner = store.get_agent(owner_id)
|
||
else:
|
||
owner = store.get_resource('worldviews', owner_id)
|
||
if not owner:
|
||
err(404, '没有这一项')
|
||
return True
|
||
|
||
# ★ v1.2:立绘是**五档**,所以槽位名允许带档位 —— `front:喜`。
|
||
# 不带档位的 `front` 视为「平常」档(兼容旧界面和旧调用)。
|
||
base, _, slot = key.partition(':')
|
||
base = base.strip()
|
||
slot = slot.strip()
|
||
if base not in ASSET_KEYS:
|
||
err(400, f'不认识的外观槽位:{base}(可选:{"、".join(ASSET_KEYS)})')
|
||
return True
|
||
if base == 'front':
|
||
slot = slot or '平常'
|
||
if slot not in PORTRAIT_PRESETS:
|
||
err(400, f'立绘档位只能是:{"、".join(PORTRAIT_PRESETS)}')
|
||
return True
|
||
|
||
def save(image: dict):
|
||
if kind == 'agents':
|
||
return store.update_agent(owner_id, {'image': image})
|
||
return store.update_resource('worldviews', owner_id, {'image': image})
|
||
|
||
image = store.normalize_image(owner.get('image') or {})
|
||
raw = body.get('data') or body.get('base64') or ''
|
||
|
||
if base == 'front':
|
||
fronts = dict(image.get('front') or {})
|
||
if not raw:
|
||
old = fronts.pop(slot, '')
|
||
image['front'] = fronts
|
||
_drop_file(old)
|
||
return _send_json_ok(handler, {'item': save(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'{slot}.png'))
|
||
dest = os.path.join(_asset_dir(owner_id), f'front-{_safe_segment(slot)}-{name}')
|
||
with open(dest, 'wb') as fh:
|
||
fh.write(blob)
|
||
_drop_file(fronts.get(slot)) # 换图时把旧的那张删掉,不然越攒越多
|
||
fronts[slot] = dest
|
||
image['front'] = fronts
|
||
return _send_json_ok(handler, {
|
||
'item': save(image), 'path': dest, 'bytes': len(blob), 'slot': slot,
|
||
})
|
||
|
||
if not raw:
|
||
old = image.pop(base, '')
|
||
_drop_file(old)
|
||
return _send_json_ok(handler, {'item': save(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'{base}.png'))
|
||
dest = os.path.join(_asset_dir(owner_id), f'{base}-{name}')
|
||
with open(dest, 'wb') as fh:
|
||
fh.write(blob)
|
||
_drop_file(image.get(base))
|
||
image[base] = dest
|
||
return _send_json_ok(handler, {
|
||
'item': save(image),
|
||
'path': dest,
|
||
'bytes': len(blob),
|
||
})
|
||
|
||
|
||
def _drop_file(path) -> None:
|
||
"""删掉一个不再被引用的资源文件(失败就算了,不值得让整个请求报错)"""
|
||
p = str(path or '').strip()
|
||
if not p or not os.path.isfile(p):
|
||
return
|
||
try:
|
||
os.remove(p)
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
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
|