"""智能体系统(需求 v1.1)的端到端探针 —— 不装机就能验整条链路。 ## 怎么做到的 内核的存储层是**无状态**的(路径全靠 `paths.get()` 从数据目录推), 所以只要把 `DOUBAO_DATA` 指到一个临时目录,就能在一个进程里把 "建智能体 → 记东西 → 检索 → 拼提示词 → 导包 → 再导入"整条链路跑一遍。 比装机验证快得多,而且**能断言具体字段**(装机只能截图看个大概)。 ## 覆盖 1. 建智能体拿到的是 UUID(需求附录 A) 2. 记忆增删改查 + 检索 3. pinned 保护(AI 改不动) 4. 情绪读写 5. Token 统计(按模型分桶、输入输出分开) 6. 世界观 + **共享记忆**(两个智能体共用一个空间) 7. 写入限权(只能删自己写的) 8. system prompt 注入(附录 C 的五段都在、空段被删掉) 9. 智能体包导出 → 导入(导入两次 = 两个独立实体) 10. 记忆导出/导入(合并按标题去重) 11. 资源 CRUD(世界观 / 模型列表 / Skill) 用法: python scripts/probe-agent-system.py """ import io import json import os import shutil import sys import tempfile try: sys.stdout.reconfigure(encoding="utf-8", errors="replace") except Exception: pass HERE = os.path.dirname(os.path.abspath(__file__)) REPO = os.path.abspath(os.path.join(HERE, "..")) KERNEL = os.path.join(REPO, "android", "kernel") # ★ 必须在 import 内核之前设好:paths.get() 是**懒加载 + 缓存**的 DATA = tempfile.mkdtemp(prefix="doubao-agent-probe-") os.environ["DOUBAO_DATA"] = DATA sys.path.insert(0, KERNEL) fails = [] def check(label, cond, detail=""): if cond: print(f" ✓ {label}") else: fails.append(label) print(f" ✗ {label} {detail}") def section(title): print(f"\n=== {title} ===") import agent_context # noqa: E402 import agent_tools # noqa: E402 import agentdb # noqa: E402 import store # noqa: E402 class FakeHandler: """冒充 app.py 的 Handler:只要 send_json / read_json_body 两个方法""" def __init__(self): self.status = 200 self.payload = None def send_json(self, code, payload): self.status = code self.payload = payload def read_json_body(self, *a, **k): return self._body def call(self, pathname, method, body=None): body = body or {} self._body = body import agent_api self.status, self.payload = 200, None agent_api.handle(self, pathname, method) return self.payload or {} def main(): print(f"临时数据目录:{DATA}") h = FakeHandler() # ---------------------------------------------------------------- 1 section("1. 智能体:UUID 主键 + 扩展字段") a1 = store.create_agent({"name": "玄辰", "description": "仙门大师兄", "systemPrompt": "你是玄辰。"}) check("新建的 id 是 UUID", len(a1["id"]) == 36 and a1["id"].count("-") == 4, a1["id"]) check("description 存下来了", a1.get("description") == "仙门大师兄") a1 = store.update_agent(a1["id"], {"tokenLimit": 5000, "emotionEnabled": True, "skillIds": []}) or a1 check("tokenLimit 存成数字", a1.get("tokenLimit") == 5000, repr(a1.get("tokenLimit"))) check("emotionEnabled 是布尔", a1.get("emotionEnabled") is True) a2 = store.create_agent({"name": "仙辰"}) check("两个智能体 id 不同", a1["id"] != a2["id"]) # 内置的还在、短 id 没被动过 check("内置智能体保留了短 id", any(x["id"] == "a_doubao" for x in store.list_agents())) # ---------------------------------------------------------------- 2 section("2. 记忆:增删改查 + 检索") scope = agentdb.scope_of(a1["id"]) m1 = agentdb.memory_add(scope, "用户的名字", "他叫小林", author_agent=a1["id"]) m2 = agentdb.memory_add(scope, "喝咖啡", "每天早上喝一杯美式", author_agent=a1["id"]) check("加了两条", len(agentdb.memory_list(scope)) == 2) check("检索命中正文", len(agentdb.memory_search(scope, "美式")) == 1) check("检索命中标题", len(agentdb.memory_search(scope, "名字")) == 1) check("检索无关词不命中", len(agentdb.memory_search(scope, "量子力学")) == 0) agentdb.memory_update(m1["id"], content="他叫小林,做前端的") check("改正文生效", "前端" in agentdb.memory_get(m1["id"])["content"]) agentdb.memory_forget(m2["id"]) check("删掉一条", len(agentdb.memory_list(scope)) == 1) # ---------------------------------------------------------------- 3 section("3. pinned 保护(AI 改不动)") agentdb.memory_set_pinned(m1["id"], True) import tools_runtime tools_runtime.push_context(agentId=a1["id"], conversationId="c_test") try: agent_tools.memory_forget({"id": m1["id"]}) check("pinned 的删不掉", False, "居然删成功了") except ValueError as exc: check("pinned 的删不掉", "必须保留" in str(exc), str(exc)) try: agent_tools.memory_update({"id": m1["id"], "content": "改了"}) check("pinned 的改不动", False, "居然改成功了") except ValueError: check("pinned 的改不动", True) check("pinned 的还在", agentdb.memory_get(m1["id"]) is not None) agentdb.memory_set_pinned(m1["id"], False) # ---------------------------------------------------------------- 4 section("4. 工具:memory_add / emotion_set / get_token_usage") r = agent_tools.memory_add({"title": "喜欢猫", "content": "他家有两只猫"}) check("memory_add 返回 id", bool(r.get("id"))) r = agent_tools.memory_search({"keyword": "猫"}) check("memory_search 找到刚记的", r["count"] >= 1, str(r["count"])) agent_tools.emotion_set({"emotion": "刚被夸了,有点得意"}) check("情绪写进去了", "得意" in agentdb.emotion_get(a1["id"])) agentdb.token_add(a1["id"], "doubao-pro", 1200, 800) agentdb.token_add(a1["id"], "doubao-pro", 300, 100) agentdb.token_add(a1["id"], "deepseek-r1", 500, 200) u = agent_tools.get_token_usage({}) check("总量 = 输入+输出", u["used"] == 1200 + 800 + 300 + 100 + 500 + 200, str(u["used"])) check("输入输出分开", u["input"] == 2000 and u["output"] == 1100, f'{u["input"]}/{u["output"]}') check("按模型分桶", len(u["byModel"]) == 2, str([m["model"] for m in u["byModel"]])) check("剩余额度按限额算", u["remaining"] == 5000 - u["used"], str(u["remaining"])) # ---------------------------------------------------------------- 5 section("5. 世界观 + 共享记忆") wv = store.create_resource("worldviews", {"name": "九霄", "setting": "一个仙侠世界,灵气复苏。"}) check("世界观有 UUID", len(wv["id"]) == 36) store.update_agent(a1["id"], {"worldviewId": wv["id"]}) store.update_agent(a2["id"], {"worldviewId": wv["id"]}) a1 = store.get_agent(a1["id"]) a2 = store.get_agent(a2["id"]) check("绑定后 scope 变成世界观的", agentdb.scope_of(a1["id"], a1["worldviewId"]).startswith("world:")) wscope = agentdb.scope_of(a1["id"], a1["worldviewId"]) agentdb.memory_add(wscope, "共同约定", "两人都怕师父", author_agent=a1["id"]) check("共享空间两人都看得到", len(agentdb.memory_list(agentdb.scope_of(a2["id"], a2["worldviewId"]))) == 1) # ---------------------------------------------------------------- 6 section("6. 写入限权:只能删自己写的") tools_runtime.push_context(agentId=a2["id"], conversationId="c_test") shared_item = agentdb.memory_list(wscope)[0] try: agent_tools.memory_forget({"id": shared_item["id"]}) check("删不了别人写的", False, "居然删成功了") except ValueError as exc: check("删不了别人写的", "其他智能体" in str(exc), str(exc)) # 自己写的能删 mine = agent_tools.memory_add({"title": "仙辰的事", "content": "他喜欢御剑"}) agent_tools.memory_forget({"id": mine["id"]}) check("自己的能删", agentdb.memory_get(mine["id"]) is None) # ---------------------------------------------------------------- 7 section("7. system prompt 注入(附录 C)") tools_runtime.push_context(agentId=a1["id"], conversationId="c_test") agentdb.emotion_set(a2["id"], "有点烦") store.update_agent(a2["id"], {"emotionEnabled": True}) # ★ a1 在这一节之前已经绑了世界观 → 它的记忆空间是**共享**的那个, # 所以验证"记忆进提示词"要往当前 scope 里写(这正是绑定世界观的正确行为) agentdb.memory_add(agentdb.scope_of(a1["id"], a1["worldviewId"]), "用户的名字", "他叫小林,做前端的", author_agent=a1["id"]) # 感知开关先关掉,验证"没开就没有同伴情绪段" store.update_agent(a1["id"], {"emotionEnabled": False}) a1 = store.get_agent(a1["id"]) sk = store.create_resource("skills", {"name": "写作", "content": "写东西要先列大纲。"}) agentdb.bind_skills(a1["id"], [sk["id"]]) prompt = agent_context.build_system_prompt(store.read_settings(), a1) for tag in ("", "", "", ""): check(f"{tag} 段在", tag in prompt) check("人设在最前面", prompt.startswith("你是玄辰。"), prompt[:20]) check("世界观设定进去了", "灵气复苏" in prompt) check("记忆进去了(标题+正文)", "【用户的名字】" in prompt and "前端" in prompt) check("自定义 Skill 进去了", "写东西要先列大纲" in prompt) check("顺序:skills 在 worldview 前", prompt.index("") < prompt.index("")) check("顺序:worldview 在 emotion 前", prompt.index("") < prompt.index("")) check("顺序:emotion 在 memory 前", prompt.index("") < prompt.index("")) # 没开感知 → 不该有同伴情绪段 check("没开感知时没有同伴情绪段", "" not in prompt) store.update_agent(a1["id"], {"emotionEnabled": True}) prompt2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"])) check("开了感知后有同伴情绪", "" in prompt2 and "仙辰-有点烦" in prompt2, prompt2[-200:]) # 空段要整段删掉 a3 = store.create_agent({"name": "空白的"}) p3 = agent_context.build_system_prompt(store.read_settings(), a3) check("没记忆时 整段没了", "" not in p3, p3[-120:]) check("但 还在(内置手册)", "" in p3) # ---------------------------------------------------------------- 8 section("8. HTTP 接口") r = h.call("/api/agents", "GET") check("GET /api/agents", r.get("ok") and len(r["agents"]) >= 4) r = h.call("/api/agents", "POST", {"name": "接口建的"}) new_id = (r.get("agent") or {}).get("id") check("POST /api/agents", bool(new_id)) r = h.call(f"/api/agents/{new_id}", "PATCH", {"description": "改过的"}) check("PATCH 生效", (r.get("agent") or {}).get("description") == "改过的") r = h.call("/api/agents/a_doubao", "DELETE") check("内置的删不掉", r.get("ok") is False, str(r.get("error"))) check("内置的还在", store.get_agent("a_doubao") is not None) r = h.call(f"/api/agents/{a1['id']}/memories", "GET") check("GET 记忆列表", r.get("ok") and r.get("shared") is True) r = h.call(f"/api/agents/{a1['id']}/usage", "GET") check("GET 用量", r.get("ok") and r.get("total", 0) > 0) r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"emotion": "挺开心的"}) check("PUT 情绪", r.get("emotion") == "挺开心的") r = h.call("/api/worldviews", "GET") check("GET 世界观列表", r.get("ok") and len(r["items"]) == 1) r = h.call("/api/model-entries", "POST", {"name": "豆包 Pro", "model": "doubao-pro", "pricePerK": 0.8}) check("POST 模型列表", r.get("ok") and (r.get("item") or {}).get("id")) r = h.call("/api/skills", "GET") check("GET Skill 列表", r.get("ok") and len(r["items"]) == 1) # ---------------------------------------------------------------- 9 section("9. 智能体包导出 / 导入") r = h.call(f"/api/agents/{a1['id']}/package", "GET") check("导出拿到 base64 zip", bool(r.get("data")), str(r.get("error"))) blob = r.get("data") r = h.call("/api/agents/import", "POST", {"data": blob}) imported = r.get("agent") or {} check("导入成功", bool(imported.get("id")), str(r.get("error"))) check("导入的是**新** UUID(不是原来那个)", imported.get("id") not in (None, a1["id"])) check("名字带过来了", imported.get("name") == "玄辰") check("提示词带过来了", imported.get("systemPrompt") == "你是玄辰。") check("描述带过来了", imported.get("description") == "仙门大师兄") check("**模型引用没带过来**(需求 2.5 的边界)", not imported.get("modelId")) check("**世界观绑定没带过来**", not imported.get("worldviewId")) check("**限额没带过来**", not imported.get("tokenLimit")) r2 = h.call("/api/agents/import", "POST", {"data": blob}) check("同一个包导入两次 = 两个独立实体", (r2.get("agent") or {}).get("id") not in (None, imported.get("id"), a1["id"])) r = h.call("/api/agents/import", "POST", {"data": "bm90IGEgemlw"}) check("坏包报错而不是崩", r.get("ok") is False, str(r.get("error"))) # ---------------------------------------------------------------- 10 section("10. 记忆导出 / 导入(合并按标题去重)") r = h.call(f"/api/agents/{a1['id']}/memories/export", "GET") check("导出 type 正确", r.get("type") == "world-memory", str(r.get("type"))) check("导出带 version", r.get("version") == 1) check("导出带 Emotion", "Emotion" in r) check("导出**不含** author_agent", all("author_agent" not in m for m in r.get("smartMemory") or [])) exported = dict(r) exported["smartMemory"] = [ {"title": "新的一条", "content": "这是导入进来的", "pinned": False}, ] + list(exported["smartMemory"]) r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST", {"data": exported, "mode": "merge"}) check("合并模式:新增了 1 条", r.get("added") == 1, str(r)) check("合并模式:同名的跳过了", r.get("skipped", 0) >= 1, str(r)) check("合并模式:保留当前情绪", agentdb.emotion_get(a1["id"]) == "挺开心的") r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST", {"data": {"type": "agent-memory", "version": 1, "smartMemory": [], "Emotion": "换掉了"}, "mode": "replace"}) check("覆盖模式:情绪也换了", agentdb.emotion_get(a1["id"]) == "换掉了", agentdb.emotion_get(a1["id"])) # ---------------------------------------------------------------- 11 section("11. 资源 CRUD + Skill 导入导出") r = h.call("/api/skills", "POST", {"name": "另一个", "content": "内容"}) sid = (r.get("item") or {}).get("id") r = h.call(f"/api/skills/{sid}", "PATCH", {"content": "改过的内容"}) check("PATCH skill", (r.get("item") or {}).get("content") == "改过的内容") r = h.call(f"/api/skills/{sid}/export", "GET") check("导出 skill 是单 JSON", r.get("json") and json.loads(r["json"])["type"] == "agent-skill") r = h.call("/api/skills/import", "POST", {"data": json.loads(r["json"])}) check("导入 skill", (r.get("item") or {}).get("id") not in (None, sid)) r = h.call(f"/api/skills/{sid}", "DELETE") check("删 skill", r.get("deleted") is True) # ---------------------------------------------------------------- 汇总 print() if fails: print(f"❌ {len(fails)} 项不合格:") for f in fails: print(" -", f) return 1 print("✅ 全部通过") return 0 if __name__ == "__main__": try: code = main() finally: shutil.rmtree(DATA, ignore_errors=True) sys.exit(code)