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
Make the limit on chained agent replies a setting (#162)
Alan Jones Riosc3d0217c9982
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5f31645..fa3c1cb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht## [Unreleased]+### Added++- **How many replies agents give in a row is a setting.** Agents mentioning each other stopped after 3 replies from one message, which cut flows like planner → developer → reviewer → developer halfway. **Settings › Agents › Limits** now has **Agent replies in a row**, from 1 to 10; left alone, it stays 3.+### Changed- **Long skill recipes are kept whole.** A recipe over 20,000 characters was refused when written or proposed, cut when linked from Claude Code or Codex, and left out of an imported team. Now 10,000 characters is a recommendation: past it, Tucano says by how much and keeps the whole recipe, up to a million characters.diff --git a/docs/spec-mvp.md b/docs/spec-mvp.mdindex 1dbccda..4a7c724 100644--- a/docs/spec-mvp.md+++ b/docs/spec-mvp.md@@ -54,7 +54,7 @@ Usuário do MVP: eu, numa máquina só. Quem baixar o repositório usa do mesmo- O router só decide quem fala. Ele **não** concede permissão nem altera grants.- O router roda num motor e modelo pequenos, configuráveis (default: Claude Code + Haiku, com `--json-schema`). Gera recibo próprio, atribuído ao workspace.- **Jev (opcional):** em Configurações, o router pode ser o Jev, o modelo de decisão da TypeSafe, com a chave do usuário. A pergunta vai como uma escolha tipada entre os handles do canal e "ninguém" (com o mesmo texto que o Haiku lê como estado); um segundo agente é chamado quando ganha pelo menos 30%. Decide em menos de 1 s, contra ~17 s medidos com o Haiku. É a única exceção a "sem chave de API": cada decisão manda as últimas 10 mensagens do canal pra TypeSafe e é cobrada lá, e a tela diz isso. A chave é conferida em `/v1/models` antes de ser guardada, fica cifrada no cofre do sistema e o renderer só sabe se ela existe. Se o Jev falhar (sem chave, recusada, limite, fora do ar), o Haiku decide e a mensagem do router diz por quê.-- Mensagens de agente **nunca** passam pelo router. Um agente pode @mencionar outro, o que dispara um run dele. A profundidade da cadeia é limitada a 3 por mensagem humana original.+- Mensagens de agente **nunca** passam pelo router. Um agente pode @mencionar outro, o que dispara um run dele. A profundidade da cadeia é limitada por mensagem humana original: 3 por padrão, ajustável em Configurações → Agentes → Limites (de 1 a 10).### 3. Run@@ -357,7 +357,7 @@ Quem chega de outro app de agentes traz o time em vez de montar de novo, sem que1. **Chat básico:** crio um agente no Claude Code, abro DM, mando uma mensagem e vejo a resposta em streaming, com rodapé de modelo/tokens/duração. O mesmo funciona com um agente no Codex.2. **Router:** num canal com dois agentes de papéis distintos ("engenharia", "conteúdo"), uma pergunta de código sem menção é respondida só pelo agente de engenharia. Uma mensagem tipo "bom dia" pode não ter resposta. A decisão do router aparece num step discreto.3. **Menção:** `@a @b` dispara os dois sem chamar o router.-4. **Anti-loop:** dois agentes se mencionando mutuamente param na profundidade 3.+4. **Anti-loop:** dois agentes se mencionando mutuamente param na profundidade 3 por padrão (ajustável em Configurações → Agentes → Limites, de 1 a 10).5. **Grants:** um agente com `read` no GitHub MCP lista issues, mas não vê a ferramenta de criar issue (o `tools/list` do gateway no log não a contém). Uma chamada forçada a uma ferramenta não permitida (teste com motor fake) é rejeitada pelo gateway.6. **Aprovação:** com `read_write`, o pedido "mergeia o PR X" gera um card. Recusar com motivo faz o agente responder considerando o motivo. Aprovar executa a chamada com exatamente os argumentos mostrados.7. **Aprovação sobrevive a reinício:** fecho o app com uma aprovação pendente, reabro, aprovo, e o run continua.diff --git a/src/core/runs.ts b/src/core/runs.tsindex a787dc3..a29d6de 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -5,7 +5,7 @@ import { L, locale } from '../shared/lang'import { friendly, toolLabel } from '../shared/errors'import type { CoreEvent } from '../shared/rpc'import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'-import { ACCESS_REQUEST, CACHE_READ_WEIGHT, describeSchedule, workIn, ENGINES, ERRORS_STOP, usable, modelInfo, PENDING_WAIT_MINUTES, REPEAT_STOP, REPEAT_WARN, SAME_TOOL_STOP, SAME_TOOL_WARN, SLEEPS_FREE, SLEEPS_STOP, RUN_BUDGET_PCT, RUN_STALL_MINUTES, IMAGE_MIMES, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, type Account, type Agent, type Approval, type Artifact, type ImageUpload, type Connector, type ConnectorTool, type Conversation, type EngineId, type Message, type Quota, type Receipt, type Person, type Question, type Routine, type Run, type RunStatus, type Settings, type Step, delegating, wikiAccess } from '../shared/types'+import { ACCESS_REQUEST, CACHE_READ_WEIGHT, describeSchedule, workIn, ENGINES, ERRORS_STOP, usable, modelInfo, PENDING_WAIT_MINUTES, REPEAT_STOP, REPEAT_WARN, SAME_TOOL_STOP, SAME_TOOL_WARN, SLEEPS_FREE, SLEEPS_STOP, RUN_BUDGET_PCT, RUN_STALL_MINUTES, chainDepthCap, IMAGE_MIMES, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, type Account, type Agent, type Approval, type Artifact, type ImageUpload, type Connector, type ConnectorTool, type Conversation, type EngineId, type Message, type Quota, type Receipt, type Person, type Question, type Routine, type Run, type RunStatus, type Settings, type Step, delegating, wikiAccess } from '../shared/types'import { BUSCAR_THREADS, clock, HISTORY_LIMIT, LER_THREAD, liveContext, mentioned, NO_LIVE, snip, systemPrompt, transcript, transcriptBlocks, type PromptOpts } from './context'import { BUSCAR_MEMORIAS, contextWindow, LEMBRAR, searchThreads, type Memories } from './memory'import { WIKI_TOOL_NAMES, WIKI_TOOLS, wikiCall, type Wiki } from './wiki'@@ -49,7 +49,6 @@ export const MAX_CONCURRENT_URGENT = 6const MAX_TURN_IMAGES = 6 // attached images a reply sees as images; older ones only by nameconst mimeOf = (name: string): string => ({ png: 'image/png', gif: 'image/gif', webp: 'image/webp' })[name.split('.').pop()!.toLowerCase()] ?? 'image/jpeg'const MAX_MENTIONS = 3-const MAX_DEPTH = 3 // agent replies chained from one human messageconst DELTA_FLUSH_MS = 40const RETRYABLE: RunStatus[] = ['failed', 'stopped', 'interrupted', 'limit_reached']// Per tool result handed back to the model, in UTF-8 bytes. Under Claude Code's own cut (about 50 KB,@@ -1850,7 +1849,7 @@ export class Runner {}this.callPeople(conv, msg, agent.name)const next = this.mentions(agent, conv, msg)- if (next.length) void this.handOff(conv, msg, agent, next, opts.depth, finished)+ if (next.length) void this.handOff(conv, msg, agent, next, opts.depth, chainDepthCap(settings.chainDepth), finished)else finished()}} else {@@ -2183,7 +2182,7 @@ export class Runner {}// 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.+ // up to the limit set in Settings (chainDepth) without a human message in between.// The agents a reply mentions (none while paused).private mentions(agent: Agent, conv: Conversation, msg: Message): Agent[] {if (this.paused) return []@@ -2192,7 +2191,7 @@ export class Runner {// 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> {+ private async handOff(conv: Conversation, msg: Message, agent: Agent, next: Agent[], depth: number, limit: number, finished: () => void): Promise<void> {const { db, engines } = this.depsconst and = L(' e ', ' and ')const list = (agents: Agent[]): string => agents.map((a) => a.name).join(and)@@ -2243,8 +2242,8 @@ export class Runner {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.`))+ if (depth >= limit) {+ this.post(conv.id, msg.threadId, L(`Parei a conversa entre agentes aqui: ${limit === 1 ? 'foi 1 resposta seguida' : `foram ${limit} respostas seguidas`}. Mande uma mensagem pra continuar.`, `I stopped the conversation between agents here: ${limit === 1 ? '1 reply' : `${limit} replies`} in a row. Send a message to go on.`))return finished()}// A noted follow-up counts as someone taking the turn: the agent will answer it, so no "done" yet.diff --git a/src/core/settings-patch.ts b/src/core/settings-patch.tsindex 353d955..8d7af18 100644--- a/src/core/settings-patch.ts+++ b/src/core/settings-patch.ts@@ -27,6 +27,7 @@ const RULES: Partial<Record<keyof Settings, { kind: Kind; max: number; nullable?openAtLogin: { kind: 'boolean', max: 10, nullable: true },runBudgetPct: { kind: 'number', max: 30, nullable: true },runStallMinutes: { kind: 'number', max: 30, nullable: true },+ chainDepth: { kind: 'number', max: 30, nullable: true },paused: { kind: 'boolean', max: 10, nullable: true },quietHours: { kind: 'object', max: 200, nullable: true },harnesses: { kind: 'array', max: 1_000, nullable: true },diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex 4a5ac18..9f9b32c 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -38,6 +38,8 @@ import {EFFORTS,ENGINES,MAX_AGENT_ROUTINES,+ MAX_CHAIN_DEPTH,+ chainDepthCap,RUN_BUDGET_PCT,routineCap,RUN_STALL_MINUTES,@@ -2300,6 +2302,14 @@ export function SettingsPage(): ReactNode {onChange={(n) => updateSettings({ runStallMinutes: Math.max(5, Math.round(n)) })}/></Field>+ <Field label={L('Respostas seguidas entre agentes', 'Agent replies in a row')} hint={L('Quantas respostas os agentes podem dar em sequência, passando a vez entre si, antes de parar e esperar você. De 1 a 10.', 'How many replies agents can give in a row, passing the turn between them, before they stop and wait for you. From 1 to 10.')}>+ <NumberInput+ min={1}+ max={MAX_CHAIN_DEPTH}+ value={chainDepthCap(settings.chainDepth)}+ onChange={(n) => updateSettings({ chainDepth: chainDepthCap(n) })}+ />+ </Field><Field label={L('Expiração de aprovações', 'Approvals expire after')}><select value={settings.approvalTtlHours} onChange={(e) => updateSettings({ approvalTtlHours: Number(e.target.value) })}><option value="1">{L('1 hora', '1 hour')}</option>diff --git a/src/shared/types.ts b/src/shared/types.tsindex 516e1ba..536c831 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -382,6 +382,7 @@ export interface Settings {openAtLogin?: boolean // so routines run without me opening the apprunBudgetPct?: number // per reply, % of the agent's monthly limit before it pauses; default RUN_BUDGET_PCTrunStallMinutes?: number // without any sign of life; default RUN_STALL_MINUTES+ chainDepth?: number // agent replies in a row from one human message; default CHAIN_DEPTHtelegram?: TelegramInfo // computed: the phone bot (spec §19)paused?: boolean // "Pausar tudo": no agent starts working, no routine runsquietHours?: { from: string; to: string } | null // "HH:MM": routines and triggers wait, and run late when it ends; null: off@@ -507,6 +508,10 @@ export const SAME_TOOL_STOP = 60 // ...and past it, that tool is refused for theexport const SLEEPS_FREE = 1 // commands that start by sleeping 20 s or more: the first runs, the next ones are refusedexport const SLEEPS_STOP = 4 // refused sleeps in a reply before it stopsexport const PENDING_WAIT_MINUTES = 5 // a connector result still running (a SQL statement) is awaited by the app this long+export const CHAIN_DEPTH = 3 // agent replies chained from one human message before Tucano stops them+export const MAX_CHAIN_DEPTH = 10+// Agents mentioning each other can't loop and burn tokens with nobody watching: a whole number from 1 to MAX_CHAIN_DEPTH, whatever reached the core.+export const chainDepthCap = (n: number | undefined): number => (Number.isFinite(n) ? Math.min(MAX_CHAIN_DEPTH, Math.max(1, Math.round(n as number))) : CHAIN_DEPTH)// What a reply counts against limits: a token read from the cache costs about a// tenth of a new one, so it counts a tenth.diff --git a/src/shared/workspaces.ts b/src/shared/workspaces.tsindex cf23f97..6a5d40f 100644--- a/src/shared/workspaces.ts+++ b/src/shared/workspaces.ts@@ -6,7 +6,7 @@ export const workspaceLabel = (s: Pick<Settings, 'workspaceName' | 'workspaceLab// The general settings: how things work, not what the workspace holds (never its context, wiki// folder, accounts, keys or phone).-export const GENERAL_SETTINGS = ['workspaceName', 'language', 'routerModel', 'memoryModel', 'memoryLearning', 'defaultLimit', 'approvalTtlHours', 'runBudgetPct', 'runStallMinutes', 'quietHours', 'harnesses', 'sounds', 'voice', 'browserJev', 'wikiCapture', 'wikiEdits', 'wikiReview'] as const satisfies readonly (keyof Settings)[]+export const GENERAL_SETTINGS = ['workspaceName', 'language', 'routerModel', 'memoryModel', 'memoryLearning', 'defaultLimit', 'approvalTtlHours', 'runBudgetPct', 'runStallMinutes', 'chainDepth', 'quietHours', 'harnesses', 'sounds', 'voice', 'browserJev', 'wikiCapture', 'wikiEdits', 'wikiReview'] as const satisfies readonly (keyof Settings)[]// What a new workspace takes from another, each picked when creating it (a duplicate takes it all).// The wiki isn't copied: the new workspace uses the same one, and what one keeps the other reads.// Never messages, memories, approvals, usage, computers' files, browser sessions or extra logins.diff --git a/test/runner.test.ts b/test/runner.test.tsindex 1096f8d..f89df7d 100644--- a/test/runner.test.ts+++ b/test/runner.test.ts@@ -157,6 +157,43 @@ describe('Runner', () => {['a1', 3]])expect(db.messages().at(-1)?.text).toContain('Parei a conversa entre agentes')+ expect(db.messages().at(-1)?.text).toContain('foram 3 respostas seguidas')+ })++ it('the chain goes as far as the limit set in Settings', async () => {+ const pingPong = fakeEngine('claude', { delayMs: 1, reply: (t) => (t.system.startsWith('Você é lia') ? '@theo, sua vez' : '@lia, sua vez') })+ const r = runner(pingPong)+ settings.engines.codex = ready+ settings.chainDepth = 5+ db.saveAgent(agent('a2', 'theo'))+ await r.send('c1', '@lia começa')+ await r.idle()+ expect(agentMessages().map((m) => m.run?.depth)).toEqual([1, 2, 3, 4, 5])+ expect(db.messages().at(-1)?.text).toContain('foram 5 respostas seguidas')+ })++ it('a limit below 1 is raised to 1', async () => {+ const pingPong = fakeEngine('claude', { delayMs: 1, reply: (t) => (t.system.startsWith('Você é lia') ? '@theo, sua vez' : '@lia, sua vez') })+ const r = runner(pingPong)+ settings.engines.codex = ready+ settings.chainDepth = 0+ db.saveAgent(agent('a2', 'theo'))+ await r.send('c1', '@lia começa')+ await r.idle()+ expect(agentMessages().map((m) => m.run?.depth)).toEqual([1])+ expect(db.messages().at(-1)?.text).toContain('foi 1 resposta seguida')+ })++ it('a limit above 10 is brought down to 10', async () => {+ const pingPong = fakeEngine('claude', { delayMs: 1, reply: (t) => (t.system.startsWith('Você é lia') ? '@theo, sua vez' : '@lia, sua vez') })+ const r = runner(pingPong)+ settings.engines.codex = ready+ settings.chainDepth = 50+ db.saveAgent(agent('a2', 'theo'))+ await r.send('c1', '@lia começa')+ await r.idle()+ expect(agentMessages().map((m) => m.run?.depth)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])+ expect(db.messages().at(-1)?.text).toContain('foram 10 respostas seguidas')})describe('screening a hand-off', () => {diff --git a/test/team-round5.test.ts b/test/team-round5.test.tsindex 9c2fa81..da1f95e 100644--- a/test/team-round5.test.ts+++ b/test/team-round5.test.ts@@ -281,6 +281,8 @@ describe('8. channel messages from before the heritage are the owner’s', () =>describe('9. two wordings', () => {it('an unknown setting is refused in plain words, whatever its key is called', () => {expect(settingsPatchError({ quota: 1 })).toBe('Essa configuração não existe.')+ expect(settingsPatchError({ chainDepth: 5 })).toBeUndefined() // the limit on agent replies in a row+ expect(settingsPatchError({ chainDepth: 'muitas' })).toBeTruthy()expect(settingsPatchError({ quota: 1 })).not.toMatch(/quota/)})it('the router’s limit note reads as one sentence, no parentheses around the reason', async () => {