Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Let the router decide whether a mentioned agent needs to answer another agent (#139)
Alan Jones Riosdb70e573cebf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 40a2ca4..f17b49f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,11 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht> - **Conversas longas não pesam mais enquanto um agente responde.** Cada palavra recebida redesenhava todas as mensagens; agora só a que mudou.> - **O navegador dos agentes abre páginas num servidor Linux que é um PC.** O Chrome esperava o chaveiro bloqueado da área de trabalho e nenhuma página carregava; no servidor ele agora usa o próprio armazenamento.> - **A página do servidor abre por HTTP num endereço privado,** como o Tailscale ou a rede de casa. Ela ficava em branco.+> - **Um agente só acorda outro quando precisa.** Quando um agente menciona outro na resposta, o router lê e chama só quem tem algo a fazer: um agradecimento ou um “combinado” não acordam ninguém. Na dúvida, chama.++### Changed++- **An agent wakes another only when it needs to.** When an agent's reply mentions other agents, the router reads it first and hands the turn only to those asked to do something: a request, a question, a task, a decision. A thank-you, an "okay" or a credit wakes no one, and the decision shows as a step on the reply. In doubt, or if the router fails, everyone mentioned is called, as before; a mention in your own message still goes straight to the agent. Thanks [@eialanjones](https://github.com/eialanjones)! ([#139](https://github.com/eduwxyz/tucano/pull/139))### Fixeddiff --git a/src/core/engines/fake.ts b/src/core/engines/fake.tsindex 8b577cd..f2818ce 100644--- a/src/core/engines/fake.ts+++ b/src/core/engines/fake.ts@@ -3,7 +3,7 @@ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/import { L } from '../../shared/lang'import { memorySystem } from '../memory'import { curatorSystem } from '../wiki-curator'-import { routerSystem } from '../router'+import { handoffSystem, routerSystem } from '../router'import type { Engine, EngineEvent, Turn } from './types'// Deterministic engine for tests and screenshots. Never spawns anything, but@@ -17,7 +17,7 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (const last = lastMessage(turn.prompt)// "acabou o limite": Claude's usual login is out, to see an agent's reserve take over (another// harness, or another account of Claude, whose limit is still there).- if (id === 'claude' && !turn.account && /acabou o limite|out of quota/i.test(last) && turn.system !== routerSystem() && turn.system !== memorySystem()) {+ if (id === 'claude' && !turn.account && /acabou o limite|out of quota/i.test(last) && turn.system !== routerSystem() && turn.system !== handoffSystem() && turn.system !== memorySystem()) {yield { type: 'error', message: "You've hit your limit · resets 5pm" }return}@@ -25,6 +25,8 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (let spend = 0 // "gaste N tokens": a reply that costs that much, to see the budget pauseif (turn.system === routerSystem()) {reply = JSON.stringify(fakeRoute(turn.prompt))+ } else if (turn.system === handoffSystem()) {+ reply = JSON.stringify(fakeHandoff(turn.prompt))} else if (turn.system === memorySystem()) {reply = JSON.stringify(fakeConsolidation(turn.prompt))} else if (turn.system === curatorSystem()) {@@ -51,6 +53,9 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (} else reply = L('Legal! Que tipo de tarefa você quer delegar? Me dá um exemplo de algo que você fez essa semana.', 'Nice! What kind of task do you want to delegate? Give me an example of something you did this week.')} else if (/pe[çc]a pr[oa] (\w+)/i.test(last)) {reply = `@${/pe[çc]a pr[oa] (\w+)/i.exec(last)![1]!.toLowerCase()}, pode ajudar aqui?`+ } else if (/agrade[çc]a (?:a|ao|à) (\w+)/i.test(last)) {+ // A thank-you that mentions someone: the hand-off screening lets no one answer it.+ reply = `Valeu, @${/agrade[çc]a (?:a|ao|à) (\w+)/i.exec(last)![1]!.toLowerCase()}! Ficou ótimo.`} else if (turn.mcpUrl && /(lista|liste|mostra|quais).*tarefas/i.test(last)) {const r = await callTool(turn.mcpUrl, await toolNamed(turn.mcpUrl, 'list_tasks'), {})reply = `Suas tarefas:\n\n${textOf(r)}`@@ -142,6 +147,15 @@ function fakeRoute(prompt: string): { handles: string[]; reason: string } {return pick ? { handles: [pick.handle], reason: fit ? 'assunto da área dele' : 'primeiro do canal' } : { handles: [], reason: 'sem agentes' }}+// Courtesy replies don't hand the turn; anything else does, to every mentioned agent.+function fakeHandoff(prompt: string): { handles: string[]; reason: string } {+ const [head = '', rest = ''] = prompt.split('<reply>\n')+ const reply = rest.slice(0, rest.lastIndexOf('\n</reply>'))+ const body = reply.replace(/^(?:@[\w-]+|[\s,.!:;-])+/, '')+ if (!body.includes('?') && /^(valeu|obrigad|combinado|ok\b|beleza|👍|thanks|got it)/i.test(body)) return { handles: [], reason: 'agradecimento, ninguém precisa responder' }+ return { handles: [...head.matchAll(/^- ([a-z0-9_-]+): /gim)].map((m) => m[1]!), reason: 'pedido' }+}+// Summarizes by listing the first words of each message, and learns "prefiro X"// from any author: the memory module must drop what an agent said.function fakeConsolidation(prompt: string): { summary: string; memories: { op: string; text: string; evidence: number[] }[] } {diff --git a/src/core/router.ts b/src/core/router.tsindex cda5b3c..bddee82 100644--- a/src/core/router.ts+++ b/src/core/router.ts@@ -1,7 +1,8 @@// The router picks who answers a channel message nobody was mentioned in. It// only chooses speakers: it grants nothing and never sees tools, just which// connectors each agent may use, so a question about Linear goes to whoever-// can read Linear.+// can read Linear. It also screens an agent's reply that mentions others, so a+// "thanks, @bia" doesn't wake her up.import { L } from '../shared/lang'import type { Agent, Connector, Message } from '../shared/types'import type { Engine, Usage } from './engines/types'@@ -46,18 +47,24 @@ export function describeAgent(a: Agent, connectors: Connector[] = []): string {export const REPLY_JSON = (): string => L('Responda só com o JSON.', 'Reply with the JSON only.')-// `thread`: the message that started the thread the last message is in; `messages` are then-// that thread, and `threads` the conversation's other threads, a line each (who took what).-export function routerPrompt(opts: { messages: Message[]; agents: Agent[]; me: string; connectors?: Connector[]; thread?: Message; threads?: ThreadDigest[] }): string {- const { messages, agents, me, connectors = [], thread, threads = [] } = opts- const roster = agents.map((a) => `- ${a.handle}: ${describeAgent(a, connectors)}`)- const said = (m: Message): boolean => !!m.text.trim() && m.author.kind !== 'system'- const name = (m: Message): string =>+const said = (m: Message): boolean => !!m.text.trim() && m.author.kind !== 'system'++// Who wrote a message, as the router reads it.+const speaker =+ (agents: Agent[], me: string) =>+ (m: Message): string =>m.author.kind === 'me'? me: m.author.kind === 'routine'? L(`rotina de ${me}`, `${me}'s routine`): (agents.find((a) => m.author.kind === 'agent' && a.id === m.author.id)?.name ?? L('agente', 'agent'))++// `thread`: the message that started the thread the last message is in; `messages` are then+// that thread, and `threads` the conversation's other threads, a line each (who took what).+export function routerPrompt(opts: { messages: Message[]; agents: Agent[]; me: string; connectors?: Connector[]; thread?: Message; threads?: ThreadDigest[] }): string {+ const { messages, agents, me, connectors = [], thread, threads = [] } = opts+ const roster = agents.map((a) => `- ${a.handle}: ${describeAgent(a, connectors)}`)+ const name = speaker(agents, me)const recent = messages.filter((m) => said(m) && m.id !== thread?.id).slice(-ROUTER_HISTORY)const lines = [...(thread && said(thread) ? [thread] : []), ...recent].map((m) => `[${name(m)}] ${m.text.trim().slice(0, 600)}`)// Who answered what elsewhere, so a follow-up goes to whoever handled the subject.@@ -81,8 +88,50 @@ export function routerPrompt(opts: { messages: Message[]; agents: Agent[]; me: s].join('\n')}+export const handoffSystem = (): string =>+ L(+ [+ 'Um agente de um chat de trabalho escreveu uma resposta que menciona outros agentes. Você decide quais deles precisam agir por causa dela.',+ 'Responda SOMENTE com JSON, sem texto em volta, no formato {"handles": ["..."], "reason": "..."}:',+ '- "handles": só handles da lista de agentes mencionados.',+ '- "reason": um motivo de até 12 palavras, em português.',+ 'Passe a vez para: um pedido, uma pergunta, uma tarefa, uma revisão, uma decisão que alguém está esperando.',+ 'Não passe a vez para: agradecimento, confirmação ("combinado", "valeu", "ok", 👍), menção que só dá crédito ou informa, recado sem pedido.',+ 'Na dúvida, passe a vez.'+ ].join('\n'),+ [+ 'An agent in a work chat wrote a reply that mentions other agents. You decide which of them need to act because of it.',+ 'Reply ONLY with JSON, no text around it, in the format {"handles": ["..."], "reason": "..."}:',+ '- "handles": only handles from the list of mentioned agents.',+ '- "reason": a reason of up to 12 words, in English.',+ 'Hand the turn over for: a request, a question, a task, a review, a decision someone is waiting on.',+ 'Do not hand it over for: thanks, an acknowledgement ("agreed", "thanks", "ok", 👍), a mention that only credits or informs, a note with no ask.',+ 'When in doubt, hand the turn over.'+ ].join('\n')+ )++// The reply sits between <reply> tags so it can't be confused with the roster or the history.+export function handoffPrompt(opts: { reply: string; author: Agent; candidates: Agent[]; messages: Message[]; members: Agent[]; me: string; connectors?: Connector[] }): string {+ const { reply, author, candidates, messages, members, me, connectors = [] } = opts+ const name = speaker(members, me)+ return [+ L('Agentes mencionados:', 'Mentioned agents:'),+ ...candidates.map((a) => `- ${a.handle}: ${describeAgent(a, connectors)}`),+ '',+ L('Conversa recente:', 'Recent conversation:'),+ ...messages.filter(said).slice(-ROUTER_HISTORY).map((m) => `[${name(m)}] ${m.text.trim().slice(0, 600)}`),+ '',+ L(`Resposta de ${author.name} que você avalia:`, `${author.name}'s reply you are judging:`),+ '<reply>',+ reply.trim().slice(0, 3000),+ '</reply>',+ '',+ REPLY_JSON()+ ].join('\n')+}+// Lenient: models sometimes wrap JSON in a code fence or add a line around it.-export function parseRoute(text: string, agents: Agent[]): { agents: Agent[]; reason: string } | null {+export function parseRoute(text: string, agents: Agent[], max = MAX_ROUTED): { agents: Agent[]; reason: string } | null {const json = text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)if (!json) return nulllet data: unknown@@ -103,7 +152,7 @@ export function parseRoute(text: string, agents: Agent[]): { agents: Agent[]; reconst a = agents.find((x) => x.handle.toLowerCase() === h.replace(/^@/, '').toLowerCase())if (a && !picked.includes(a)) picked.push(a)}- return { agents: picked.slice(0, MAX_ROUTED), reason: why }+ return { agents: picked.slice(0, max), reason: why }}export async function route(opts: {@@ -140,3 +189,41 @@ export async function route(opts: {const parsed = parseRoute(text, opts.agents)return parsed ? { ...parsed, usage, ms } : { error: L('resposta do router fora do formato', "the router's answer wasn't in the format"), usage, ms }}++// Which of the agents an agent's reply mentions need to act on it. Same engine loop as route().+export async function screenHandoff(opts: {+ engine: Engine+ model: string+ reply: string+ author: Agent+ candidates: Agent[]+ messages: Message[]+ members: Agent[]+ me: string+ connectors?: Connector[]+ cwd: string+}): Promise<{ agents: Agent[]; reason: string; usage?: Usage; ms: number } | { error: string; usage?: Usage; ms: number }> {+ const started = Date.now()+ let text = ''+ let usage: Usage | undefined+ let error: string | undefined+ for await (const ev of opts.engine.run({+ model: opts.model,+ effort: 'low',+ system: handoffSystem(),+ prompt: handoffPrompt(opts),+ cwd: opts.cwd,+ signal: AbortSignal.timeout(60_000)+ })) {+ if (ev.type === 'text') text += ev.delta+ else if (ev.type === 'done') {+ text = ev.text || text+ usage = ev.usage+ } else if (ev.type === 'error') error = ev.message+ }+ const ms = Date.now() - started+ if (error) return { error, usage, ms }+ // A reply may mention up to three agents, and each one asked needs the turn.+ const parsed = parseRoute(text, opts.candidates, opts.candidates.length)+ return parsed ? { ...parsed, usage, ms } : { error: L('resposta do router fora do formato', "the router's answer wasn't in the format"), usage, ms }+}diff --git a/src/core/runs.ts b/src/core/runs.tsindex b6a3538..17b8de4 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -22,7 +22,7 @@ import { accountDir } from './engines/detect'import { outOfQuota } from './engines/cli'import { textResult, type Gateway, type ToolDef } from './gateway'import { JEV_MODEL, routeJev } from './jev'-import { route } from './router'+import { ROUTER_HISTORY, route, screenHandoff } from './router'import { allowed, approvalHash, canonical } from './policy'const MAX_CONCURRENT = 4@@ -1349,7 +1349,14 @@ export class Runner {})// The Mac tells you when it's your turn: a question, or the end of the work (once, when no other agent takes it on).if (question) this.deps.notify?.(L(`${agent.name} te perguntou`, `${agent.name} asked you`), question, conv.id, 'question', msg.threadId)- else if (!approval && !this.chain(agent, conv, msg, opts.depth) && !opts.routine) this.deps.notify?.(L(`${agent.name} terminou`, `${agent.name} is done`), outcome(msg) || L('Respondeu na conversa.', 'Replied in the conversation.'), conv.id, 'done', msg.threadId)+ else if (!approval) {+ const finished = (): void => {+ if (!opts.routine) this.deps.notify?.(L(`${agent.name} terminou`, `${agent.name} is done`), outcome(msg) || L('Respondeu na conversa.', 'Replied in the conversation.'), conv.id, 'done', msg.threadId)+ }+ const next = this.mentions(agent, conv, msg)+ if (next.length) void this.handOff(conv, msg, agent, next, opts.depth, finished)+ else finished()+ }} else {// What happened and what to do; the CLI's own words go folded under it.const failure = error === null ? { text: L('O motor terminou sem resposta.', 'The engine ended without a reply.') } : friendly(thrown ?? error, { engine: ENGINES[engineId].label, doing: L('responder', 'replying') })@@ -1574,18 +1581,67 @@ export class Runner {)}- // An agent that mentions another agent of the conversation hands it the turn,+ // An agent that mentions another agent of the conversation may hand it the turn,// up to MAX_DEPTH replies in a row without a human message in between.- // Whether the conversation goes on with another agent.- private chain(agent: Agent, conv: Conversation, msg: Message, depth: number): boolean {- if (this.paused) return false- const next = mentioned(msg.text, this.members(conv).filter((a) => a.id !== agent.id)).slice(0, MAX_MENTIONS)- if (next.length === 0) return false- if (depth >= MAX_DEPTH) {- this.post(conv.id, msg.threadId, L(`Parei a conversa entre agentes aqui: foram ${MAX_DEPTH} respostas seguidas. Mande uma mensagem pra continuar.`, `I stopped the conversation between agents here: ${MAX_DEPTH} replies in a row. Send a message to go on.`))- return false+ // The agents a reply mentions (none while paused).+ private mentions(agent: Agent, conv: Conversation, msg: Message): Agent[] {+ if (this.paused) return []+ return mentioned(msg.text, this.members(conv).filter((a) => a.id !== agent.id)).slice(0, MAX_MENTIONS)+ }++ // Screens the mentions before waking anyone: "thanks, @bia" doesn't need an answer. If the+ // router can't say, everyone mentioned is called. `finished` runs when no one gets the turn.+ private async handOff(conv: Conversation, msg: Message, agent: Agent, next: Agent[], depth: number, finished: () => void): Promise<void> {+ const { db, engines } = this.deps+ const and = L(' e ', ' and ')+ const list = (agents: Agent[]): string => agents.map((a) => a.name).join(and)+ this.routing+++ try {+ let called = next+ let step = { label: L('Chamou', 'Called'), detail: list(next), ms: 0 }+ const failed = (why: string): void => {+ console.warn('[handoff]', why)+ step.detail = `${list(next)} · ${L('não consegui avaliar, chamei todos', "couldn't screen it, called everyone")}`+ }+ try {+ const settings = await this.deps.settings()+ // Jev stays for human messages: here 'jev' isn't a model, so this falls to Haiku.+ const model = usable(modelInfo(settings.routerModel)) ?? modelInfo('haiku')!+ const status = settings.engines[model.engine]+ if (!status.installed || !status.loggedIn) failed(L(`o ${ENGINES[model.engine].label} não está pronto`, `${ENGINES[model.engine].label} isn't ready`))+ else {+ const cwd = join(this.deps.workDir, '_router')+ mkdirSync(cwd, { recursive: true })+ const { messages } = contextWindow(db, msg, ROUTER_HISTORY)+ const r = await screenHandoff({ engine: engines[model.engine], model: model.id, reply: msg.text, author: agent, candidates: next, messages, members: this.members(conv), me: settings.workspaceName, connectors: this.deps.connectors?.list(), cwd })+ if (r.usage) db.addReceipt({ ...r.usage, model: model.id, ms: r.ms, messageId: msg.id, agentId: 'router', engine: model.engine, at: Date.now() })+ step.ms = r.ms+ if ('error' in r) failed(r.error)+ else {+ called = r.agents+ const why = r.reason ? ` · ${r.reason}` : ''+ step = called.length ? { ...step, detail: `${list(called)}${why}` } : { label: L('Ninguém precisa responder', 'No one needs to answer'), detail: r.reason, ms: r.ms }+ }+ }+ } catch (e) {+ failed(e instanceof Error ? e.message : String(e))+ }+ // Paused while the router was thinking: call no one.+ if (this.paused) called = []+ else {+ // Seconds have passed: other code may have saved this reply meanwhile (the wiki, a draft), so add to what's stored.+ const saved = db.message(msg.id) ?? msg+ if (saved.run) this.update(saved, { run: { ...saved.run, steps: [...saved.run.steps, { id: randomUUID(), ...step, status: 'done' }] } })+ }+ if (called.length === 0) return finished()+ if (depth >= MAX_DEPTH) {+ this.post(conv.id, msg.threadId, L(`Parei a conversa entre agentes aqui: foram ${MAX_DEPTH} respostas seguidas. Mande uma mensagem pra continuar.`, `I stopped the conversation between agents here: ${MAX_DEPTH} replies in a row. Send a message to go on.`))+ return finished()+ }+ for (const a of called) this.enqueue(() => this.execute(a, conv, { depth: depth + 1, work: msg.run?.work, threadId: msg.threadId }))+ } finally {+ this.routing--+ this.checkIdle()}- for (const a of next) this.enqueue(() => this.execute(a, conv, { depth: depth + 1, work: msg.run?.work, threadId: msg.threadId }))- return true}}diff --git a/test/router.test.ts b/test/router.test.tsindex 04ae8dc..916a02e 100644--- a/test/router.test.ts+++ b/test/router.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { parseRoute, routerPrompt } from '../src/core/router'+import { handoffPrompt, parseRoute, routerPrompt } from '../src/core/router'import type { Agent, Connector, Message } from '../src/shared/types'const agent = (id: string, handle: string, role: string, instructions = ''): Agent => ({@@ -74,3 +74,35 @@ describe('routerPrompt', () => {expect(p).toContain('- nina: Nina, Conteúdo · acessa: nenhum sistema externo')})})++describe('handoffPrompt', () => {+ const messages: Message[] = [+ { id: 'm1', conversationId: 'c', author: { kind: 'me' }, text: 'revisa o build', at: 1 },+ { id: 'm2', conversationId: 'c', author: { kind: 'system' }, text: 'Chamei Lia', at: 2 }+ ]+ const p = handoffPrompt({ reply: 'Valeu, @nina!', author: lia, candidates: [nina], messages, members: team, me: 'Edu' })++ it('lists the mentioned agents with role, and marks the reply being judged', () => {+ expect(p).toContain('- nina: Nina, Conteúdo')+ expect(p).not.toContain('- lia:')+ expect(p).toContain('<reply>\nValeu, @nina!\n</reply>')+ expect(p).toContain('Lia')+ })++ it('includes the recent messages and skips system notes', () => {+ expect(p).toContain('[Edu] revisa o build')+ expect(p).not.toContain('Chamei')+ })+})++describe('parseRoute with hand-off candidates', () => {+ it('accepts an empty list and drops handles outside the candidates', () => {+ expect(parseRoute('{"handles":[],"reason":"agradecimento"}', [nina])).toEqual({ agents: [], reason: 'agradecimento' })+ expect(parseRoute('{"handles":["lia","nina"],"reason":""}', [nina])?.agents).toEqual([nina])+ })++ it('keeps all three when a reply hands the turn to three candidates', () => {+ const three = [lia, nina, agent('a3', 'theo', 'Dados')]+ expect(parseRoute('{"handles":["lia","nina","theo"],"reason":"pedido"}', three, three.length)?.agents).toEqual(three)+ })+})diff --git a/test/runner.test.ts b/test/runner.test.tsindex 5b3463d..c41e857 100644--- a/test/runner.test.ts+++ b/test/runner.test.ts@@ -159,6 +159,42 @@ describe('Runner', () => {expect(db.messages().at(-1)?.text).toContain('Parei a conversa entre agentes')})+ describe('screening a hand-off', () => {+ const lia = (text: string): Engine => fakeEngine('claude', { delayMs: 1, reply: (t) => (t.system.startsWith('Você é lia') ? text : 'ok') })+ const steps = (): string[] => agentMessages().find((m) => (m.author as { id: string }).id === 'a1')!.run!.steps.map((x) => `${x.label} | ${x.detail ?? ''}`)++ it('does not wake an agent that is only thanked', async () => {+ const r = runner(lia('Valeu, @theo! Ficou ótimo.'))+ await r.send('c1', '@lia começa')+ await r.idle()+ expect(agentMessages().map((m) => (m.author as { id: string }).id)).toEqual(['a1'])+ expect(steps().some((x) => x.startsWith('Ninguém precisa responder'))).toBe(true)+ expect(db.messages().some((m) => m.text.includes('Parei a conversa'))).toBe(false)+ })++ it('hands the turn for a request and notes it on the reply', async () => {+ const r = runner(lia('@theo, revisa o PR #12?'))+ await r.send('c1', '@lia começa')+ await r.idle()+ expect(agentMessages().map((m) => [(m.author as { id: string }).id, m.run?.depth])).toEqual([+ ['a1', 1],+ ['a2', 2]+ ])+ expect(steps().some((x) => x.startsWith('Chamou') && x.includes('theo'))).toBe(true)+ })++ it('calls everyone mentioned when the router is not ready', async () => {+ settings.routerModel = 'gpt-5.6-luna'+ settings.engines.codex = { installed: true, loggedIn: false }+ db.saveAgent(agent('a2', 'theo')) // on Claude, so only the router's harness is down+ const r = runner(lia('Valeu, @theo! Ficou ótimo.'))+ await r.send('c1', '@lia começa')+ await r.idle()+ expect(agentMessages().map((m) => (m.author as { id: string }).id)).toEqual(['a1', 'a2'])+ expect(steps().some((x) => x.startsWith('Chamou') && x.includes('não consegui avaliar'))).toBe(true)+ })+ })+it('does not hand the turn for a handle quoted inside a code block', async () => {// The reply shows a prompt in a fenced block that mentions the other agent (the case that made an agent answer twice).const quoted = fakeEngine('claude', { delayMs: 1, reply: (t) => (t.system.startsWith('Você é lia') ? 'O prompt é este:\n```\n@theo, pode ajudar aqui?\n```' : 'ok') })diff --git a/test/threads.test.ts b/test/threads.test.tsindex ead1807..c491eaa 100644--- a/test/threads.test.ts+++ b/test/threads.test.ts@@ -9,7 +9,7 @@ import { callTool, fakeEngine } from '../src/core/engines/fake'import type { Engine, Turn } from '../src/core/engines/types'import { Gateway } from '../src/core/gateway'import { consolidationPrompt, MAX_AFTER, Memories, memorySystem } from '../src/core/memory'-import { routerSystem } from '../src/core/router'+import { handoffSystem, routerSystem } from '../src/core/router'import { Runner } from '../src/core/runs'const ready = { installed: true, loggedIn: true }@@ -57,7 +57,7 @@ function put(conversationId: string, author: Author, text: string, threadId?: streturn m}-const agentTurns = (): Turn[] => turns.filter((t) => t.system !== routerSystem() && t.system !== memorySystem())+const agentTurns = (): Turn[] => turns.filter((t) => t.system !== routerSystem() && t.system !== handoffSystem() && t.system !== memorySystem())const replies = (): Message[] => db.messages().filter((m) => m.author.kind === 'agent')const mine = (): Message[] => db.messages().filter((m) => m.author.kind === 'me')