fix(agent): 会话隔离(用户报的'串味')+ 记忆注入窗口与置顶(v2.0.52)

## 串味:会话没做隔离

会话本来就有 agentId 字段,但两处都没用:
  · 新建会话时从来不填 → 所有会话的主人都空着
  · 取历史消息时从来不检查 → 切了智能体还在同一会话里接着聊

于是历史消息是上一个角色说的、system prompt 却是新角色的,
新角色把别人的话当成自己的经历接着聊。

修法:一个会话属于一个智能体。
  · 新建时记住主人
  · 换人时界面主动换会话(useAgent → newTopic)
  · 内核兜底:取历史时发现主人不对就另起一个,并发 rebased 事件让界面切
  · 老会话(没主人)认领而不是另起,否则历史会话第一次聊天就跳走
  · 已有主人的会话不许改嫁

## 记忆的窗口和置顶(用户选的 A 方案)

'无上限 + 每轮全量注入'长期矛盾:几百条时提示词被撑爆,
而且早期的记忆反而把最近的对话上下文挤掉。

  · memoryWindow(默认 50,0 = 不限):每轮最多注入多少条
  · 置顶的永远注入、排最前,不受窗口限制
  · 被裁掉的没丢,memory_search 还能搜到(降级为仅可检索)
  · 记忆页顶部显示'这一轮会带进去 N / M 条',可就地调整
  · 「必须保留」改叫「置顶」

## 探针

新增 14 节(会话隔离 4 项)和 15 节(窗口与置顶 8 项)。

顺带修掉两个真问题:
  · set_conversation_agent 绕过内存缓存直接读写文件(会话有缓存)
  · 探针自己的 pinned is True —— SQLite 布尔是 0/1 整数
This commit is contained in:
l
2026-10-16 16:11:36 +08:00
parent f8ab075f5e
commit 9ff60e684b
11 changed files with 324 additions and 22 deletions

View File

@@ -272,6 +272,15 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
'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')), # 是不是共享空间(界面要提示)
@@ -282,6 +291,9 @@ def _memory_payload(agent: dict, force_own: bool = False) -> dict:
# ★ 绑定世界观之后,私有空间里可能还留着以前攒的记忆 ——
# 条数一并告诉界面,它才知道要不要显示"以前那些在这"这个入口
'ownCount': 0 if scope == own else len(agentdb.memory_list(own)),
'window': window,
'pinnedCount': pinned_count,
'injected': injected,
'emotion': agentdb.emotion_get(agent.get('id') or ''),
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
}

View File

@@ -103,22 +103,65 @@ def build_emotion(agent: dict) -> str:
def build_memory(agent: dict) -> str:
"""
`<memory>` 段:那个记忆空间的**全部条目**(标题 + 正文,需求 3.2 的"全量注入")。
`<memory>` 段:那个记忆空间里**会注入给模型**的条目。
★★ 共享空间里的条目**带作者署名**(复查报告第 5 条)。
## 注入窗口 + 置顶保护
为什么必须带:共享记忆是几个人往同一个本子上写。没有署名的时候,
别人写的"我小时候住在海边"在模型眼里就是**它自己的经历** ——
它会当成自己的过去来讲,甚至在用户问起时说"我不记得有这事"。
署名之后它才知道"这条是仙辰写的,不是我的"(需求 3.6 的
"交模型调和矛盾记忆"也才有前提:得先分得清谁写的)。
"无上限 + 全量注入"这两条长期是矛盾的:攒到几百上千条时,提示词会被
记忆撑爆(每条几十字,一千条就是几万 token),而且**越靠后越贵、
早期记忆反而挤掉了最近的对话上下文**。
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
所以这里按**窗口**裁:
· **置顶的永远注入**,且排在最前面 —— 那是用户明确说了"这条重要"的
· 其余按时间取**最近**的,凑够窗口
· 置顶条数超过窗口时,置顶的**全部**注入(窗口是给普通记忆设的,
不是用来否决用户明确置顶的东西)
· 被裁掉的**没有丢**,AI 还能用 `memory_search` 检索到 ——
也就是"降级为仅可检索"
窗口大小在全局设置里(`memoryWindow`),0 = 不限(退回全量注入)。
## 共享记忆带作者署名
共享空间是几个人往同一个本子上写。没有署名的时候,别人写的
"我小时候住在海边"在模型眼里就是**它自己的经历** —— 它会当成自己的
过去来讲,甚至在用户问起时说"我不记得有这事"。署名之后它才知道
"这条是仙辰写的"(需求 3.6 的"交模型调和矛盾记忆"也才有前提:
得先分得清谁写的)。
私有空间**不加**署名:那里只有它自己写的,加一句"(你记的)"是纯噪音。
"""
scope = memory_scope(agent)
items = _safe(lambda: agentdb.memory_list(scope), [])
if not items:
return ''
# ---- 窗口裁剪 ----
settings = _safe(store.read_settings, {}) or {}
try:
window = int(settings.get('memoryWindow') or 0)
except (TypeError, ValueError):
window = 0
total = len(items)
trimmed = 0
if window > 0 and total > window:
pinned = [m for m in items if m.get('pinned')]
rest = [m for m in items if not m.get('pinned')]
room = max(0, window - len(pinned))
keep = pinned + (rest[-room:] if room else [])
# 顺序:置顶的在前(用户明确要的),其余保持时间顺序
items = keep
trimmed = total - len(keep)
parts = []
if pinned:
parts.append(f'置顶 {len(pinned)} 条')
if trimmed:
parts.append(f'另有 {trimmed} 条较早的没放进来(用 memory_search 还能搜到)')
note = '(' + ';'.join(parts) + ')' if parts else ''
else:
note = ''
tmpl = _safe(
lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE),
DEFAULT_MEMORY_LINE,
@@ -133,15 +176,20 @@ def build_memory(agent: dict) -> str:
title = (it.get('title') or '').strip()
content = (it.get('content') or '').strip()
author = (it.get('author_agent') or '').strip()
tags = []
if it.get('pinned'):
tags.append('置顶')
if shared and author:
# 自己写的也标出来("(你记的)")—— 一眼能分清哪些是自己的立场
who = '你记的' if author == me else f'{names.get(author) or "某人"}记的'
title = f'{title}({who})'
# 自己写的也标出来("你记的")—— 一眼能分清哪些是自己的立场
tags.append('你记的' if author == me else f'{names.get(author) or "某人"}记的')
if tags:
title = f'{title}({",".join(tags)})'
try:
lines.append(tmpl.format(title=title, content=content))
except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试
lines.append(DEFAULT_MEMORY_LINE.format(title=title, content=content))
return '\n'.join(lines)
body = '\n'.join(lines)
return f'{body}\n{note}' if note else body
def build_peer_emotions(agent: dict) -> str:

View File

@@ -207,10 +207,16 @@ def memory_get(memory_id: str) -> dict | None:
def memory_list(scope: str) -> list:
"""一个记忆空间的全部条目(**注入 system prompt 用的就是它**)"""
"""
一个记忆空间的全部条目(**注入 system prompt 用的就是它**)。
★ 顺序是**置顶的排最前**,其余按时间。
界面和提示词注入用**同一个顺序** —— 两处各排一次的话,很容易出现
"界面上看着在第一条、实际没进提示词"这种对不上的情况。
"""
init()
rows = _connect().execute(
'SELECT * FROM memories WHERE scope = ? ORDER BY created_at ASC', (scope,),
'SELECT * FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,),
).fetchall()
return [dict(r) for r in rows]

View File

@@ -928,7 +928,13 @@ class KernelHandler(BaseHTTPRequestHandler):
body = self.read_json_body()
except ValueError:
body = {}
self.send_json(200, {'conversation': store.create_conversation(body.get('title') or '新对话')})
self.send_json(200, {'conversation': store.create_conversation(
body.get('title') or '新对话',
# ★ 新会话要**记住它属于谁** —— 会话隔离的依据就是它。
# 不传的话所有会话的主人都是空,切换智能体时就没法判断
# "这是不是同一个人的对话",只能一直串着(用户报的 bug)。
agent_id=(body.get('agentId') or '').strip(),
)})
return True
conv_id = self._match_id(pathname, '/api/conversations/')
if conv_id is not None:
@@ -1661,6 +1667,27 @@ class KernelHandler(BaseHTTPRequestHandler):
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
agent_id = (agent or {}).get('id') or ''
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
#
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
# 还在同一个会话里接着聊 —— 历史消息是上一个角色说的,
# 而 system prompt 已经换成新角色的了。新角色**会把别人的话
# 当成自己说的**(用户的原话:"智能体怎么串味了")。
#
# 处理:主人不一致就**另起一个会话**,并通知界面换 id。
# · 老会话(本次改动之前建的)没有 agentId —— 那种**认领**它,
# 而不是也另起一个,否则所有历史会话第一次聊天都会跳走。
owner = (existing.get('agentId') or '').strip()
if existing and agent_id:
if not owner:
store.set_conversation_agent(conversation_id, agent_id)
elif owner != agent_id:
conversation_id = store.create_conversation(agent_id=agent_id)['id']
existing = store.get_conversation(conversation_id) or {}
# 界面据此把当前会话切过去(不然它会往老 id 上继续追加)
emit({'type': 'rebased', 'conversationId': conversation_id,
'reason': 'agent_changed'})
# ★★ Token 限额:**发起前**拦(需求 3.1)。
#
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是

View File

@@ -166,6 +166,15 @@ for _key, _url in PROVIDER_CONSOLE_URLS.items():
DEFAULT_SETTINGS = {
# 记忆注入窗口(条数):每轮最多把多少条记忆放进提示词。
#
# ★ "记忆无上限"和"每轮全量注入"这两条长期是矛盾的 —— 攒到几百上千条时
# 提示词会被记忆撑爆(一千条 × 几十字 ≈ 几万 token),而且**越靠后的
# 记忆越贵、反而把最近的对话上下文挤掉**。
# 所以给一个窗口:置顶的永远注入,其余取最近的。
# 被裁掉的没丢,AI 还能用 memory_search 检索到("降级为仅可检索")。
# 0 = 不限(退回全量注入)。
'memoryWindow': 50,
'provider': 'ark',
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
'model': PROVIDER_PRESETS['ark']['defaultModel'],

View File

@@ -932,6 +932,26 @@ def delete_conversation(conv_id: str) -> bool:
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: