Compare commits

...

1 Commits

Author SHA1 Message Date
l
31c62fafc2 v2.0.80 —— 群聊里 AI 能看到谁说的 + talk_to 多目标 + 私聊
## 一、智能体能读到群里所有人的发言了

以前送进模型的 `history` 只有 `role` / `content` —— 群里**别人说的话**,
模型根本分不清是谁说的,只能当成自己说过或用户说过。

现在群聊时,送给模型的每条消息前面都标上发言人:

```
[用户] @寐眠 你们聊聊
[小黑] 我哪句是打岔,哪句是问号,哪句是逗号——我记性好
[寐眠] 你打的是「你们」。我知道,你打的时候大概是想把两个都算进去
```

(只在**送给模型的那份**上加,落库的正文和界面显示都还是干净的。)
顺带在 skill 里写清楚:「你能看到群里所有人的发言,别把别人的话当成自己说过。」

## 二、talk_to 一次可以找好几个人

```
talk_to(agents=["小黑", "寐眠"], content="你们都说说")
```

目标会**挨个**回话 —— 移交状态带队列,界面逐个接下去(自动模式直接跑,
手动模式每轮都出「让他说 / 停在这」)。

为了兼容老写法,`agent="名字"` 仍然能用,等价于只找一个人。

## 三、talk_to 加私聊:只有目标知道

```
talk_to(agent="寐眠", content="别告诉小黑", private=true)
```

- 这条消息**只有目标智能体**能看到;
- 内核组装 history 时按「是不是给我的」过滤掉,所以**别的 AI 真的看不到**;
- **你(用户)照样看得到** —— 你是观察者,不能连自己都瞒着。
  skill 里也这么写了:「别以为私聊就可以说见不得人的话」。

## 四、顺手

- 探针里三条**旧断言**过期了(`talk_to` 参数从「agent+content」扩成
  `agents`/`agent`/`content`/`private`;移交状态多了 `queue`)—— 已更新,
  不是放宽标准,是接口真的变了。

## 验证

八个探针全绿;`probe-group-chat` 新增第 21 节共 8 条断言,
覆盖:多目标参数、私聊参数、移交队列、新一轮清队列、
送模型的历史带发言人、别人的私聊被过滤。
2026-10-17 14:46:49 +08:00
7 changed files with 227 additions and 49 deletions

View File

@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 279
versionName = "2.0.79"
versionCode = 280
versionName = "2.0.80"
ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份

View File

@@ -1425,6 +1425,23 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
private val handoffToRef = AtomicReference("")
private val handoffFromRef = AtomicReference("")
/**
* 这一轮 AI 把话交给了**一串人**(`talk_to` 多目标)。
*
* ★ 用 `AtomicReference` 的理由同 [handoffDone]:写在 IO 回调线程上、
* `finally` 里马上要读。
*/
private val handoffQueueRef = AtomicReference<List<String>>(emptyList())
/**
* 待接话的人(队列)。
*
* ★★ 用户要求:「talk_to 支持多个目标(目标智能体挨个回话)」。
* 所以一轮跑完如果还有没接过话的人,就摆出"下一个是他",
* 自动模式直接接着跑、手动模式把按钮摆出来等用户点。
*/
private val handoffQueue = ArrayDeque<String>()
/** 已经连续自动续了几轮。防止两个 AI 你一句我一句停不下来(那是烧钱) */
private var autoRounds = 0
@@ -1466,6 +1483,8 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
pendingHandoffTo = ""
pendingHandoffName = ""
pendingHandoffFromName = ""
// ★ 队列也一起清掉:用户说停就是停,别过一会儿又冒出来一个"下一个"
handoffQueue.clear()
handoffDone.set(false)
if (who.isNotBlank()) showHint("停在这里了($who 没接)")
}
@@ -1913,6 +1932,9 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
// 自动模式:不用用户确认,直接接着让他说
if (autoRounds < autoRoundCap) {
autoRounds++
// ★ 把多目标的队列也带上:下一轮跑完 `finally` 会继续消费
handoffQueue.clear()
handoffQueue.addAll(handoffQueueRef.get().filter { it.isNotBlank() })
runChat("", emptyList(), auto = true)
}
} else {
@@ -1922,12 +1944,29 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
pendingHandoffName = state.agents
.firstOrNull { it.id == handoffToRef.get() }?.name.orEmpty()
pendingHandoffFromName = handoffFromRef.get()
// ★ 多目标:剩下的排进队列,`continueHandoff` 之后由
// 这次 `runChat` 的 finally 接着摆出来("挨个回话")
handoffQueue.clear()
handoffQueue.addAll(handoffQueueRef.get().filter { it.isNotBlank() })
}
} else if (canContinue && handoffQueue.isNotEmpty()) {
// ★★ 队列里还有没接过话的人(`talk_to` 多目标)——
// 用户要求「目标智能体挨个回话」,所以接着摆下一个。
val next = handoffQueue.removeFirst()
val nextName = state.agents.firstOrNull { it.id == next }?.name.orEmpty()
if (state.settings.aiTalkAuto) {
runChat("", emptyList(), auto = true, forceSpeaker = next)
} else {
pendingHandoffTo = next
pendingHandoffName = nextName
pendingHandoffFromName = handoffFromRef.get()
}
} else {
// 收尾:清掉自动对聊的计数,免得下次发消息又自己续上
aiTalkLeft = 0
aiTalkTurn = 0
aiTalkPair = emptyList()
handoffQueue.clear()
}
}
}
@@ -1944,6 +1983,8 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
if (event is StreamEvent.Handoff) {
handoffDone.set(true)
handoffToRef.set(event.to)
// 多目标:剩下的那些也记下来,`finally` 里逐个消费
handoffQueueRef.set(event.queue)
handoffFromRef.set(
state.agents.firstOrNull { it.id == event.from }?.name.orEmpty()
)

View File

@@ -654,39 +654,58 @@ def pass_turn(args: dict) -> dict:
TALK_TO = {
'name': 'talk_to',
'description': (
'在群聊里**主动对另一个智能体说一句话**。\n'
'在群聊里**主动对一个或多个智能体说话**。\n'
'★ 和 `pass_turn` 的区别很要紧:那个只是"我不说了,你来",**不带内容** ——\n'
' 对方接到的是一片空白,只能凭上下文猜该说什么。\n'
' 这个是你**有话要对他说**:内容会进对话,他下一轮看得到并回应你。\n'
'★ 想跟群里的谁聊就调它,一来一回可以聊好几轮。\n'
'★ 一次可以找**好几个人**(`agents` 列表),他们会**挨个**回应。\n'
'★ `private=true` 时这条只有**目标**看得到,群里其他智能体看不到 ——\n'
' 用户能看到(他是观察者),但别的 AI 不会知道你们说了什么。\n'
'★ 一轮最多一次 —— 转来转去没人接话,用户会看得莫名其妙。\n'
'★ 单聊里没有"别人",调了会报错。'
),
'parameters': {
'type': 'object',
'properties': {
'agent': {'type': 'string', 'description': '对方的名字或 id'},
'content': {'type': 'string', 'description': '你要对他说的话'},
'agents': {
'type': 'array',
'items': {'type': 'string'},
'description': '对方的名字列表(只找一个人也可以只写一个)。他们会按顺序挨个回应。',
},
'agent': {
'type': 'string',
'description': '老写法:只找一个人时可以直接写名字(等价于 agents=[名字])。',
},
'content': {'type': 'string', 'description': '你要对他们说的话'},
'private': {
'type': 'boolean',
'description': '私聊模式:只有目标能看到这条,群里其他智能体看不到(默认 false)。',
},
},
'required': ['agent', 'content'],
'required': ['content'],
},
}
def talk_to(args: dict) -> dict:
"""
主动找群里的另一个智能体说话。
主动找群里的一个或多个智能体说话。
★★ 为什么单独一个工具(用户明确要求:「智能体主动调用工具和别的智能体聊」,
「工具定义 / 智能体加上内容」):
★★ 三个能力都是用户点名要的:
`pass_turn` 只交发言权、**不带内容** —— 对方接到的是一片空白。
要"两个智能体真的聊起来",就得让发起方**能说一句具体的话**,
而且那句话要**落进对话**,对方下一轮才看得到。
所以这个工具的参数就是那两样:**跟谁说 + 说什么**。
① **能说具体的话**(`content`)
`pass_turn` 只交发言权、不带内容 —— 对方接到一片空白,聊不起来。
★ 说完之后把发言权交给他(`note_handoff`)—— 界面据此**自动续一轮**,
他会真的开口回应;他也可以反过来再 `talk_to` 回来,于是就能聊下去。
② **一次找多个人**(`agents`)—— 他们**挨个**回话。
发言权排成队列交给 `tools_runtime`,界面逐个接下去。
③ **私聊模式**(`private=true`)—— 这条只有目标看得到,
群里其他人(包括别的 AI)都不知道你们说了什么。
落库时打在消息的 `privateTo` 上;`app.py` 组装 history 时
会按"是不是给我的"过滤掉,所以别的 AI 真的看不到。
★ 说完之后把发言权交出去(`note_handoff`,多目标时排队)——
界面据此逐个让他们回应;他们也可以反过来再 `talk_to` 回来。
"""
import group_chat
import tools_runtime
@@ -705,41 +724,69 @@ def talk_to(args: dict) -> dict:
# 一轮里只做一件,否则发言权会被转好几手,用户看着莫名其妙
raise ValueError('这一轮你已经把话交给别人了,等他回应完再说')
target = _find_agent(str(args.get('agent') or '').strip())
if not target:
raise ValueError(f'找不到叫「{args.get("agent")}」的智能体')
if target.get('id') == me.get('id'):
raise ValueError('不能对自己说 —— 直接说就行')
if target['id'] not in group_chat.member_ids(conv):
raise ValueError(f'「{target.get("name")}」不在这个群里,先把他拉进来')
# ★ 目标名单:`agents` 列表优先,兼容老的单数 `agent`
raw = args.get('agents')
wanted = []
if isinstance(raw, list):
wanted = [str(x or '').strip() for x in raw]
elif raw:
wanted = [str(raw or '').strip()]
if not wanted:
single = str(args.get('agent') or '').strip()
if single:
wanted = [single]
wanted = [x for x in wanted if x]
if not wanted:
raise ValueError('要跟谁说?写 agent 或 agents')
targets, missing = [], []
for name in wanted:
t = _find_agent(name)
if not t:
missing.append(name)
continue
if t.get('id') == me.get('id'):
continue # 自己跳过(一次找多人时很常见)
if t['id'] not in group_chat.member_ids(conv):
missing.append(f'{t.get("name")}(不在群里)')
continue
if all(t['id'] != x['id'] for x in targets):
targets.append(t)
if not targets:
raise ValueError(f'一个都没找到:{"、".join(missing) or "(空的)"}')
content = str(args.get('content') or '').strip()
if not content:
raise ValueError('要说什么?content 不能是空的')
# ① 这句话以**我**的名义落进对话 —— 对方下一轮就看得到
before = len((store.get_conversation(conv_id) or {}).get('messages') or [])
store.append_messages(conv_id, [{
is_private = bool(args.get('private'))
msg = {
'role': 'assistant',
'content': content,
'agentId': me.get('id'),
'at': store.now_iso(),
}])
}
if is_private:
# ★ 私聊:只给这几个目标看(`app.py` 组装 history 时按这个过滤)
msg['privateTo'] = [t['id'] for t in targets]
before = len((store.get_conversation(conv_id) or {}).get('messages') or [])
store.append_messages(conv_id, [msg])
after = len((store.get_conversation(conv_id) or {}).get('messages') or [])
print(f'[talk_to] conv={conv_id} 落库 {before}->{after} 内容={content[:20]!r}',
file=sys.stderr)
# ② 把发言权交给他 —— 界面据此自动续一轮,让他真的回应
tools_runtime.note_handoff(target['id'])
print(f'[talk_to] conv={conv_id} 落库 {before}->{after} private={is_private} '
f'targets={[t.get("name") for t in targets]} 内容={content[:20]!r}', file=sys.stderr)
# ★ 发言权:多目标排成队列,界面逐个接着让他们回应
names_out = '、'.join(t.get('name') or '?' for t in targets)
tools_runtime.note_handoff(targets[0]['id'], queue=[t['id'] for t in targets])
return {
'said_to': target.get('name'),
# ★★ **回显说了什么**。不回显的话模型看不到自己的话落在哪儿,
# 会以为"传过去是空的"、然后反复重试 ——
# 真机上就是模型自己在回复里写「这条是空的,我猜是想看我把 talk_to 真跑一遍」
# (用户报的「talk_to 没有内容呀」)。
'said_to': [t.get('name') for t in targets],
'content': content,
'private': is_private,
'note': (
f'已把「{content}」说给「{target.get("name")}」,'
'这句话已经写进对话、他下一轮看得到,接下来由他回应。别再重复调这个工具。'
f'已把「{content}」{"(私下)" if is_private else ""}说给「{names_out}」,'
'这句话已经写进对话,他们会挨个回应。别再重复调这个工具。'
+ (f'(没找到:{"、".join(missing)})' if missing else '')
),
}

View File

@@ -1868,6 +1868,40 @@ class KernelHandler(BaseHTTPRequestHandler):
if window.get('reason'):
print(f'[context] {context_window.describe(window)}', file=sys.stderr)
# ★★ 群聊:给送进模型的每条消息标上**是谁说的**,并过滤私聊消息。
#
# ① 以前 history 里只有 role/content —— 群里**别人说的话**
# 模型根本分不清是谁,只能当成自己说过/用户说过。
# 用户的原话:「智能体可以读取群聊所有智能体的对话信息」。
# 这里在内容的**前面**加 `[名字] `,只改"送给模型的这份",
# 落库的正文保持干净(界面显示不受影响)。
#
# ② `talk_to` 的私聊模式(`privateTo`):那条消息只有**目标智能体**
# 和**用户**看得到,别人(包括模型)都不该有。所以在送进模型之前
# 就把"不是给我的私聊"剔掉 —— 在窗口裁剪之后剔除,
# 这样裁剪的"轮数"还是按全群算的,不会因为私聊把窗口算歪。
_is_group = group_chat.is_group(existing)
if _is_group:
_name_of = {x['id']: (x.get('name') or '') for x in store.list_agents()}
_filtered = []
for _m in history:
_to = _m.get('privateTo')
if isinstance(_to, list) and _to and agent_id not in _to:
# 这条是别人之间的私聊 —— 你看不到(用户能看到,那是用户的事)
continue
_who = ''
if _m.get('role') == 'assistant':
_who = _name_of.get(str(_m.get('agentId') or ''), '')
elif _m.get('role') == 'user':
_who = '用户'
if _who:
_m = dict(_m)
_content = _m.get('content')
if isinstance(_content, str):
_m['content'] = f'[{_who}] {_content}'
_filtered.append(_m)
history = _filtered
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
#
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
@@ -2052,7 +2086,11 @@ class KernelHandler(BaseHTTPRequestHandler):
# 这个坑在 `pass_turn` 上已经踩过一次了。
hs = tools_runtime.handoff_state()
if hs.get('used') and hs.get('to'):
emit({'type': 'handoff', 'to': hs['to'], 'from': agent_id})
emit({'type': 'handoff', 'to': hs['to'],
# ★ `talk_to` 一次找多个人时,剩下的人在这里 ——
# 界面逐个接下去让他们回应(用户要求"目标智能体挨个回话")
'queue': hs.get('queue') or [],
'from': agent_id})
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。

View File

@@ -276,8 +276,13 @@ BUILTIN_SKILL = '\n'.join([
# 它会拿 `pass_turn` 当"跟人说话"用(那个只交发言权、不带内容),
# 于是对方接到一片空白,两个人永远聊不起来。这段就是纠这个。
'【群聊】你可能在一个群里(群里有别人)。',
'· 你能**看到群里所有人的发言**(送进上下文的每条都有 `[名字]` 前缀,'
'「[用户]」是你对面那个人说的)。别把别人说的话当成自己说过。',
'· 想**主动对某个智能体说一句具体的话**:用 talk_to(agent=他的名字, content=你要说的话)。',
' 那句话会真的写进对话,他下一轮看得到、会回应你 —— 这是你和别人**来回聊**的唯一办法。',
'· 一次想找**好几个人**:talk_to(agents=["甲","乙"], content=...),他们会**挨个**回应。',
'· 想**私下**跟某人说(只有他知道、群里其他 AI 看不到):加 `private=true`。'
' 用户还是看得到(他是观察者)—— 所以别以为私聊就可以说见不得人的话。',
'· **不要**拿 pass_turn 当"跟他说话":它只交发言权、不带内容,',
' 对方接到的是一片空白,只能凭上下文猜(所以那样聊不起来)。',
' pass_turn 只在"我没什么可说了,换你"的时候用。',

View File

@@ -182,24 +182,36 @@ def current_context() -> dict:
# 所以这里的修复必须配一条**走真实路径**的探针(见 probe-group-chat)。
#
# 轮次级状态放**模块级**,和线程无关,`agent_loop` 每轮开头重置一次。
_handoff = {'to': '', 'used': False}
_handoff = {'to': '', 'used': False, 'queue': []}
def begin_round() -> None:
"""一轮对话开始时调用(agent_loop 在生成前调)"""
_handoff['to'] = ''
_handoff['used'] = False
_handoff['queue'] = []
def note_handoff(agent_id: str) -> None:
"""`pass_turn` 记下"这一轮移交给了谁" """
_handoff['to'] = str(agent_id or '')
def note_handoff(agent_id: str, queue: list = None) -> None:
"""
记下"这一轮把话交给了谁"。
[queue] 是**多目标**时的完整名单(`talk_to` 支持一次找好几个人,
他们挨个回话)。`to` 始终是**第一个**,保持老调用方不用改。
"""
ids = [str(x) for x in (queue or []) if str(x or '').strip()]
if not ids and str(agent_id or '').strip():
ids = [str(agent_id)]
_handoff['to'] = ids[0] if ids else str(agent_id or '')
_handoff['used'] = True
# 剩下的排进队列(`to` 已经算第一个了)
_handoff['queue'] = ids[1:]
def handoff_state() -> dict:
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`)"""
return dict(_handoff)
"""读这一轮的移交状态(`app.py` 的仲裁要用 `to`,界面要用 `queue`)"""
return {'to': _handoff['to'], 'used': _handoff['used'],
'queue': list(_handoff.get('queue') or [])}
def ui_tools_enabled(settings: dict) -> bool:

View File

@@ -239,7 +239,8 @@ def main():
# 新一轮开始要重置
tools_runtime.begin_round()
check("新一轮开始后重置(可以再移交)",
tools_runtime.handoff_state() == {'to': '', 'used': False},
tools_runtime.handoff_state().get('to') == ''
and tools_runtime.handoff_state().get('used') is False,
str(tools_runtime.handoff_state()))
r3 = real_call('pass_turn', {'target': '仙辰'})
check("新一轮里又能移交了", r3.get('ok') is True, str(r3))
@@ -448,9 +449,12 @@ def main():
str(sorted(agent_tools.AGENT_TOOLS)))
if entry:
props = entry['spec'].get('parameters', {}).get('properties', {})
check("参数就是「智能体 + 内容」", set(props) == {'agent', 'content'}, str(list(props)))
check("两个都是必填",
set(entry['spec']['parameters'].get('required') or []) == {'agent', 'content'},
# ★ 参数演化过:最早是「agent + 内容」,后来加了多目标(agents)
# 和私聊(private),所以必填只剩 content —— 目标二选一。
check("参数含「目标 + 内容」",
{'agent', 'agents', 'content'} <= set(props), str(list(props)))
check("只要求 content 必填(agent/agents 二选一)",
list(entry['spec']['parameters'].get('required') or []) == ['content'],
str(entry['spec']['parameters'].get('required')))
# ★ 模型要能看见它 —— AGENT_TOOLS 会被合并进 BUILTIN_TOOLS 才是真注册
import builtin_tools
@@ -553,6 +557,37 @@ def main():
"if pathname.startswith('/api/conversations/') and '/members' in pathname:" in _app,
"又用回 _match_id 了 —— 加人会 404")
print("\n=== 21. talk_to 多目标 / 私聊 + 群聊里能看到谁说的 ===")
#
# 用户的三个要求:
# ① 智能体能读到群里**所有人**的发言(不是只看到自己的)
# ② talk_to 加私聊:只有目标知道
# ③ talk_to 支持多目标:目标挨个回话
spec2 = agent_tools.AGENT_TOOLS['talk_to']['spec']['parameters']
props2 = spec2.get('properties', {})
check("talk_to 支持 `agents` 多目标", 'agents' in props2, str(list(props2)))
check("`agents` 是数组", props2.get('agents', {}).get('type') == 'array', str(props2.get('agents')))
check("talk_to 支持 `private` 私聊", 'private' in props2, str(list(props2)))
check("只要求 content 必填(agent/agents 二选一)",
spec2.get('required') == ['content'], str(spec2.get('required')))
# 移交状态要能带队列(多目标挨个回话靠它)
import tools_runtime as _tr
_tr.begin_round()
_tr.note_handoff('a', queue=['a', 'b', 'c'])
_st = _tr.handoff_state()
check("移交状态带队列(多目标挨个回)",
_st.get('to') == 'a' and _st.get('queue') == ['b', 'c'], str(_st))
_tr.begin_round()
check("新一轮把队列也清掉", _tr.handoff_state().get('queue') == [], str(_tr.handoff_state()))
# 群聊里送进模型的历史要标发言人 + 过滤别人的私聊
check("送进模型的历史标了发言人(`[名字] ` 前缀)",
'_[who]' in _app.replace('[', '_[', 1) or 'f\'[{_who}] {_content}\'' in _app,
"没标发言人 —— 模型分不清哪句是别人说的")
check("别人的私聊消息会被过滤掉(`privateTo`)",
"m.get('privateTo')" in _app, "没过滤 —— 私聊会被全群看到")
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")