Skip to content

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.

Make an alarm triage take minutes, not half an hour (#137)

Dias364f897e9051
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3df13f0..f261752 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
> - **A página do servidor abre por HTTP num endereço privado,** como o Tailscale ou a rede de casa. Ela ficava em branco.
> - **Os agentes do Claude respondem mais rápido e gastam menos do plano em conversas longas.** Cada agente continua a mesma sessão do Claude Code na conversa e manda só o que é novo; entre uma resposta e outra o processo fica aberto por 5 minutos. O primeiro trecho da resposta chega quase 1 segundo antes, e uma conversa longa não é mandada inteira de novo a cada resposta.
> - **A resposta começa enquanto você digita.** O Tucano já abre o Claude Code de quem vai responder: o router escolhe quem responde num canal em 1,5 s em vez de 2,8 s, e numa DM parada há mais de 5 minutos a resposta começa meio segundo antes.
+> - **Uma triagem de alarmes leva minutos, não meia hora.** Uma consulta de conector que volta ainda rodando (um SQL demorado) o app espera sozinho, com a ferramenta de status do conector, em vez de o agente dormir e perguntar de novo; um agente com conectores lê só a janela que precisa, e é avisado quando pagina um histórico inteiro.
> - **Um agente responde uma vez de cada vez na mesma conversa.** Quando outro agente passa a vez pra quem já está respondendo ali, não abre uma segunda resposta ao lado: fica anotado, e quando a resposta acaba vem uma só, que lê tudo o que chegou no meio. Em outras conversas e threads ele segue em paralelo.
> - **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.
> - **O app abre fora do instalador mesmo com uma versão estranha.** O atualizador, que nem é usado ali, conferia a versão ao abrir e derrubava o app.
@@ -27,6 +28,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
### Changed
+- **An alarm triage takes minutes, not half an hour.** A connector query that comes back still running (a slow Databricks SQL statement) is now awaited by the app with the connector's own status tool, backing off from 2 to 15 s for up to five minutes, and the agent gets the finished result in the one call it made, instead of sleeping a minute and asking again. A status tool the agent calls itself, or a write that starts a job, still answers right away. An agent with connectors sees each message's time with the year, the UTC offset and the Unix seconds, and is told to read only the window a task needs (the last hour, for something happening now) and to narrow a cut result before paging the rest, which now says how much was left out. Two guards catch what's left: a connector read called 15 times in a reply gets a note to narrow it, and past 60 it's refused for that reply; and for an agent with connectors, a bare `sleep` of 20 s or more with nothing checked after it runs once per reply. Writes, and a sleep before checking something on the computer, are never counted. A reproduced triage (30 days of alarms in Slack, a 3-minute query) went from 439 agent calls and 40 minutes to 2 calls and 3.4 minutes. Thanks [@rjgdias](https://github.com/rjgdias)! ([#137](https://github.com/eduwxyz/tucano/pull/137))
- **Claude agents reply faster, and long conversations spend less of the plan.** An agent now keeps its Claude Code session for each conversation and thread: its first reply sends the conversation, and the next ones only what's new since (other people's and agents' messages, and the task). The process stays open for five minutes after a reply (two at most at a time), so the next reply skips starting Claude Code. Measured with Haiku in a DM of about 16k tokens, the first words of a reply come about 0.9 s sooner (1.45 s instead of 2.33 s). Past the conversation's window, where each reply used to write the whole history to the prompt cache again (about 16,600 tokens), it now writes about 200. The session starts over when the agent's instructions, memories or tools change, a message it saw is edited, its last reply was stopped or failed, or after an hour idle. Thanks [@rjgdias](https://github.com/rjgdias)! ([#147](https://github.com/eduwxyz/tucano/pull/147))
- **Replies get going while you type.** As you write, Tucano starts Claude Code for whoever will answer, so the reply doesn't wait the second it takes to start: in a channel of several agents, a process for the router, which then picks who answers in about 1.5 s instead of 2.8 s; in a DM whose agent's process closed after its five idle minutes, that process again, and the first words come about 0.6 s sooner. A process started for the router that goes unused (you mentioned someone, or didn't send) closes after two minutes. Thanks [@rjgdias](https://github.com/rjgdias)! ([#148](https://github.com/eduwxyz/tucano/pull/148))
- **A reply's steps say what each call did, as it runs.** A connector call shows what it asked (the SQL, a path, a search) from the moment it starts, and what came back once it ends, in a few words: the rows of a table or a SQL answer, the items of a list, the lines of a long text. A command shows whole, or as **Ran SQL** with the SQL taken out of it, and ends with what it printed or its exit code and the last lines of stderr; reading a skill says which skill and file. Tokens, passwords, keys and auth headers are masked on the screen and in the log (the agent still gets the real output). The steps list stays open while the agent works, unless closed, and folds when the reply is done. Thanks [@rjgdias](https://github.com/rjgdias)! ([#135](https://github.com/eduwxyz/tucano/pull/135))
diff --git a/src/core/context.ts b/src/core/context.ts
index e1ae520..ba10f20 100644
--- a/src/core/context.ts
+++ b/src/core/context.ts
@@ -29,8 +29,9 @@ export function systemPrompt(opts: {
publish?: string[] // the GitHub repositories it can push agent/* branches to
builder?: string // the Tuca's view of the workspace: models, connectors, the team
wiki?: { pages: number; kinds: string[] } // the wiki it may read
+ connectors?: boolean // it has connector tools (Slack, Databricks…)
}): string {
- const { agent, settings, conversation, peers, memories, canRemember, hasComputer, computerOff, macFolder, offline, web, browser, apps, routines, skills, publish, builder, wiki } = opts
+ const { agent, settings, conversation, peers, memories, canRemember, hasComputer, computerOff, macFolder, offline, web, browser, apps, routines, skills, publish, builder, wiki, connectors } = opts
const me = settings.workspaceName || L('o usuário', 'the user')
const where =
conversation.kind === 'dm'
@@ -147,6 +148,7 @@ export function systemPrompt(opts: {
`- Suas outras ferramentas são as que ${me} liberou pra você. Ações sensíveis não rodam na hora: viram um pedido de aprovação, e você recebe o resultado depois da decisão.`,
`- Your other tools are the ones ${me} granted you. Sensitive actions don't run right away: they become an approval request, and you get the result after the decision.`
),
+ connectors && readingData(me),
offline?.length &&
L(
`- Você tem acesso a ${offline.join(', ')}, mas ${offline.length > 1 ? 'eles estão desconectados' : 'ele está desconectado'} agora, então as ferramentas não aparecem pra você. Se precisar, peça a ${me} pra reconectar em Conectores (não é falta de permissão).`,
@@ -166,6 +168,21 @@ export function systemPrompt(opts: {
.join('\n\n')
}
+// Reading a channel, a history, logs or a table: only the window the task needs, and no waiting by hand.
+// Without it an agent asked about "the alarm" pages through the whole channel and sleeps on slow queries.
+export function readingData(me: string): string {
+ return [
+ L(
+ `- Pra ler um canal, um histórico, logs ou uma tabela, peça só a janela que a tarefa precisa, com o filtro de tempo da ferramenta, uma busca ou um limite, em vez de paginar tudo. Cada mensagem traz a hora, com os segundos Unix; a última é de agora. Ex.: "o alarme da última hora" é oldest = (unix da última mensagem − 3600). Se o pedido é sobre algo de agora (um alarme, um erro) e ${me} não disser a janela, comece pela última hora e só amplie se faltar. Se um resultado vier cortado, estreite a pergunta (janela menor, filtro, menos campos, uma agregação) em vez de chamar de novo pro resto.`,
+ `- To read a channel, a history, logs or a table, ask only for the window the task needs, with the tool's time filter, a search or a limit, instead of paging through everything. Each message carries its time, with the Unix seconds; the last one is from now. E.g. "the alarm from the last hour" is oldest = (the last message's unix − 3600). If it's about something happening now (an alarm, an error) and ${me} doesn't say the window, start with the last hour and widen it only if something's missing. If a result comes back cut, narrow the question (a shorter window, a filter, fewer fields, an aggregate) instead of calling again for the rest.`
+ ),
+ L(
+ '- Uma consulta que volta ainda rodando (um SQL demorado) o app espera por você, com a ferramenta de status do próprio conector: ela só te devolve quando terminar. Não espere com sleep nem rode a mesma consulta de novo.',
+ "- A query that comes back still running (a slow SQL) is awaited by the app for you, with the connector's own status tool: it only comes back once it's done. Don't wait with sleep or run the same query again."
+ )
+ ].join('\n')
+}
+
// The language of the app is the one agents answer in, unless the person writes in another.
export function replyLanguage(me: string): string {
return lang() === 'en'
@@ -263,7 +280,15 @@ function memorySection(me: string, m: { aboutMe: Memory[]; own: Memory[]; search
.join('\n\n')
}
-const now = (): string => new Date().toLocaleString(locale(), { weekday: 'long', day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
+// "UTC-03:00": message times are local, and the tools that filter by time often want UTC or Unix seconds.
+const utcOffset = (d: Date): string => {
+ const m = -d.getTimezoneOffset()
+ const a = Math.abs(m)
+ return `UTC${m < 0 ? '-' : '+'}${String(Math.floor(a / 60)).padStart(2, '0')}:${String(a % 60).padStart(2, '0')}`
+}
+const zone = (at: number): string => `${utcOffset(new Date(at))}, unix ${Math.floor(at / 1000)}`
+
+const now = (): string => `${new Date().toLocaleString(locale(), { weekday: 'long', day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })} (${zone(Date.now())})`
// "sáb 18/10 14:02": with the weekday, so "toda segunda" and "amanhã" can be worked out.
export const clock = (at: number): string => {
@@ -272,6 +297,10 @@ export const clock = (at: number): string => {
return `${day} ${d.toLocaleString(locale(), { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }).replace(',', '')}`
}
+// A message's time in the transcript: the clock with the year, the offset and the Unix seconds, so
+// "the last hour" goes straight into a tool's time filter. It never changes, so the cache still holds.
+export const stamp = (at: number): string => `${clock(at).replace(/^(\S+ \d{2}\/\d{2})/, `$1/${new Date(at).getFullYear()}`)} (${zone(at)})`
+
// The conversation as blocks, one per message, oldest first. Nothing in them
// changes between turns (no "now", no closing line), so a kept session can tell
// what it already saw by its block. `task` (to continue after an approval, a
@@ -290,6 +319,7 @@ type TranscriptOpts = {
images?: Map<string, string[]>
thread?: Message
searchable?: boolean
+ unix?: boolean // message times with the year, the offset and the Unix seconds: for an agent whose tools filter by time
}
export function transcript(opts: TranscriptOpts): string[] {
@@ -304,7 +334,7 @@ export const snip = (text: string, max: number): string => {
// The blocks, and which block each message became (where its images go).
export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; blockOf: Map<string, number> } {
- const { agent, conversation, messages, agents, me, task, summary, images, thread, searchable } = opts
+ const { agent, conversation, messages, agents, me, task, summary, images, thread, searchable, unix } = opts
const name = (m: Message): string | null => {
if (m.author.kind === 'me') return me
if (m.author.kind === 'system') return null
@@ -363,7 +393,7 @@ export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; bloc
: `${summary?.trim() ? L('Mensagens desde o resumo', 'Messages since the summary') : L(`Conversa em ${where}`, `Conversation in ${where}`)}, ${L('das mais antigas pras mais novas', 'oldest to newest')}:`
].filter((b): b is string => !!b)
const blockOf = new Map(shown.map((m, i) => [m.id, head.length + i]))
- const blocks = [...head, ...shown.map((m) => `[${name(m)} · ${clock(m.at)}]\n${body(m)}`), ...(task ? [`${task}\n\n${L('Agora', 'Now')}: ${now()}.`] : [])]
+ const blocks = [...head, ...shown.map((m) => `[${name(m)} · ${unix ? stamp(m.at) : clock(m.at)}]\n${body(m)}`), ...(task ? [`${task}\n\n${L('Agora', 'Now')}: ${now()}.`] : [])]
return { blocks, blockOf }
}
diff --git a/src/core/runs.ts b/src/core/runs.ts
index 6002bae..3613665 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, REPEAT_STOP, REPEAT_WARN, 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 Routine, type Run, type RunStatus, type Settings, type Step, 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, 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 Routine, type Run, type RunStatus, type Settings, type Step, wikiAccess } from '../shared/types'
import { BUSCAR_THREADS, clock, HISTORY_LIMIT, LER_THREAD, mentioned, snip, systemPrompt, transcript, transcriptBlocks } from './context'
import { BUSCAR_MEMORIAS, contextWindow, LEMBRAR, searchThreads, type Memories } from './memory'
import { WIKI_TOOL_NAMES, WIKI_TOOLS, wikiCall, type Wiki } from './wiki'
@@ -26,6 +26,7 @@ import { sessionConfig, Sessions, type SessionPlan, type Shown } from './session
import { JEV_MODEL, routeJev } from './jev'
import { ROUTER_HISTORY, route, routerTurn, screenHandoff } from './router'
import { allowed, approvalHash, canonical } from './policy'
+import { awaitDone, idleSleepSeconds, isStatusTool, pendingOf, pollTool } from './waits'
import { callError, contentText, errorReason } from './connectors'
import { commandStep, execSummary, keyArg, maskSecrets, resultSummary } from './step-text'
@@ -89,6 +90,7 @@ export interface RunnerDeps {
models?: () => { id: string; label: string }[] // what the Tuca may propose; without it, the plans' listed models
wiki?: Pick<Wiki, 'indexText' | 'search' | 'page' | 'count' | 'kinds'> // without it, agents have no wiki
wikiCurator?: { afterReply(conversationId: string): void } // reads the conversation after a reply, to keep what lasts
+ timers?: { wait(ms: number, signal?: AbortSignal): Promise<void>; now(): number } // how the app waits on a pending result; tests pass a fake clock
}
// What the runner needs from the connector manager.
@@ -118,9 +120,13 @@ export function resultText(r: CallToolResult): string {
if (bytes.length <= MAX_RESULT_BYTES) return text
// Cut on a whole character: a split one decodes as U+FFFD at the end.
const kept = bytes.subarray(0, MAX_RESULT_BYTES).toString('utf8').replace(/�+$/, '')
+ // How much was left out, so the agent narrows the question instead of paging through the rest.
+ const kb = (n: number): string => `${Math.round(n / 1000).toLocaleString(locale())} KB`
+ const lines = (s: string): number => s.split('\n').length
+ const shown = Math.max(1, Math.round((MAX_RESULT_BYTES / bytes.length) * 100))
return `${kept}\n${L(
- `[… resultado cortado em ${MAX_RESULT_BYTES / 1000} KB: o resto não chegou. Se precisar dele, chame de novo pedindo menos de uma vez (paginação, filtro, menos campos).]`,
- `[… result cut at ${MAX_RESULT_BYTES / 1000} KB: the rest didn't come through. If you need it, call again asking for less at once (pagination, a filter, fewer fields).]`
+ `[… resultado cortado: chegaram ${kb(MAX_RESULT_BYTES)} de ${kb(bytes.length)} (${shown}%, ${lines(kept)} de ${lines(text)} linhas). Se precisar de mais, pergunte de um jeito mais estreito (uma janela de tempo menor, um filtro, menos campos, uma agregação); leia o resto em partes só se precisar mesmo de tudo.]`,
+ `[… result cut: ${kb(MAX_RESULT_BYTES)} of ${kb(bytes.length)} came through (${shown}%, ${lines(kept)} of ${lines(text)} lines). If you need more, ask more narrowly (a shorter time window, a filter, fewer fields, an aggregate); read the rest in parts only if you really need all of it.]`
)}`
}
@@ -140,7 +146,7 @@ export interface RoutineEvent {
// msg is the live reply: a decision taken mid-run must land on it, or the run's last save overwrites it.
type ReplyOpts = { depth: number; existing?: Message; task?: string; work?: string; routine?: boolean; threadId?: string }
-type Control = { ctl: AbortController; msg: Message; reason?: 'stopped' | 'limit' | 'budget' | 'loop' | 'errors' | 'stall' | 'computer' }
+type Control = { ctl: AbortController; msg: Message; reason?: 'stopped' | 'limit' | 'budget' | 'loop' | 'errors' | 'stall' | 'computer' | 'sleeping' }
export class Runner {
private queue: (() => Promise<unknown>)[] = []
@@ -749,6 +755,11 @@ export class Runner {
seen.set(key, { result, n })
return n
}
+ // Calls per connector tool, whatever the arguments: paging a whole channel changes the cursor each
+ // time, so the repeat guard never sees it.
+ const callsOf = new Map<string, number>()
+ let sleeps = 0 // commands that started by sleeping
+ let refusedSleeps = 0
let pending = ''
let timer: NodeJS.Timeout | null = null
@@ -981,6 +992,21 @@ export class Runner {
if (computers && COMPUTER_TOOL_NAMES.has(name)) {
const current = db.agent(agent.id)
if (!current?.computer) return textResult(L('Seu computador foi desligado.', 'Your computer was turned off.'), true)
+ // An agent with connectors sleeping with nothing checked after it is waiting for something outside
+ // (a query, a job): that holds the reply a minute at a time and makes nothing come sooner. The first
+ // runs; the next ones don't. A sleep before checking something here (a server, a build) always runs.
+ const slept = exposed.size && name === 'bash' && typeof args['command'] === 'string' ? idleSleepSeconds(args['command']) : 0
+ if (slept >= 20 && ++sleeps > SLEEPS_FREE) {
+ if (++refusedSleeps >= SLEEPS_STOP) halt('sleeping')
+ addSteps({ id: randomUUID(), label: L('Não esperou com sleep', "Didn't wait with sleep"), detail: snip(String(args['command']), 80), status: 'error' })
+ return textResult(
+ L(
+ `Não rodei: dormir sem conferir nada não faz nada chegar mais cedo e segura a resposta. Uma consulta de conector que volta ainda rodando (um SQL demorado) o app espera por você, por até ${PENDING_WAIT_MINUTES} minutos: rode-a uma vez só. Se precisar esperar algo no seu computador, durma e confira no mesmo comando (ex.: sleep 30 && curl …, ou um laço). Se não há o que esperar, siga com o que já tem ou encerre dizendo o que falta.`,
+ `Not run: sleeping without checking anything makes nothing come sooner and holds the reply. A connector query that comes back still running (a slow SQL) is awaited by the app for you, for up to ${PENDING_WAIT_MINUTES} minutes: run it only once. If you need to wait for something on your computer, sleep and check in the same command (e.g. sleep 30 && curl …, or a loop). If there's nothing to wait for, go on with what you have or end saying what's left.`
+ ),
+ true
+ )
+ }
const t0 = Date.now()
const { label, detail } = stepFor(name, args, current.computerKind === 'mac')
// A command shows whole (or the SQL it runs, pulled out), masked, from the moment it starts.
@@ -1267,10 +1293,43 @@ export class Runner {
save()
}
try {
- const r = await this.deps.connectors!.call(hit.connector.id, current.name, toolArgs)
- if (r.isError) finish('error', errorReason(r))
- else finish('done', undefined, resultSummary(resultText(r)))
- return clip(r)
+ const { [REASON_PARAM]: _reason, ...toolArgs } = args
+ const first = await this.deps.connectors!.call(hit.connector.id, current.name, toolArgs)
+ // A query still running: the app waits for it here, with the connector's own status tool, instead
+ // of the agent sleeping and asking again. Not a status tool the agent called itself (asking whether a
+ // deploy finished wants the answer now), nor a write (starting a job doesn't mean waiting for it).
+ const pending = current.cls === 'read' && !isStatusTool(current.name) ? pendingOf(first) : undefined
+ const poller = pending && pollTool(db.tools(hit.connector.id), pending, (t) => allowed(t, db.agent(agent.id)?.grants[hit.connector.id]))
+ const done = (r: CallToolResult): void => (r.isError ? finish('error', errorReason(r)) : finish('done', undefined, resultSummary(resultText(r))))
+ if (!pending || !poller) {
+ done(first)
+ return clip(first)
+ }
+ const w = await awaitDone(first, async (p) => this.deps.connectors!.call(hit.connector.id, poller.tool.name, pollTool([poller.tool], p, () => true)?.args ?? poller.args), {
+ maxMs: PENDING_WAIT_MINUTES * 60_000,
+ wait: this.deps.timers?.wait,
+ now: this.deps.timers?.now,
+ signal: control.ctl.signal
+ })
+ const took = w.ms >= 60_000 ? `${Math.round(w.ms / 60_000)} min` : `${Math.max(1, Math.round(w.ms / 1000))} s`
+ msg.run = { ...msg.run!, steps: msg.run!.steps.map((s) => (s.id === step.id ? { ...s, detail: `${detail} · ${L(`esperou ${took}`, `waited ${took}`)}` } : s)) }
+ done(w.result)
+ if (!w.pending) return clip(w.result)
+ const ids = Object.entries(poller.args).map(([k, v]) => `${k}=${v}`).join(', ')
+ const r = clip(w.result)
+ return {
+ ...r,
+ content: [
+ ...r.content,
+ {
+ type: 'text',
+ text: L(
+ `[Ainda ${w.pending.state} depois de ${took} esperando (${w.polls} consultas a ${poller.tool.name}). Não fique esperando nem durma: diga a ${settings.workspaceName} que ainda está rodando (${ids}) e siga com o que já dá pra fazer, ou chame ${poller.tool.name} uma vez mais no fim.]`,
+ `[Still ${w.pending.state} after waiting ${took} (${w.polls} checks with ${poller.tool.name}). Don't keep waiting or sleep: tell ${settings.workspaceName} it's still running (${ids}) and go on with what you can do, or call ${poller.tool.name} once more at the end.]`
+ )
+ }
+ ]
+ }
} catch (e) {
const why = callError(e)
finish('error', why)
@@ -1291,6 +1350,19 @@ export class Runner {
true
)
}
+ // Only reads: paging a history is reading, and many writes in a row (filing 80 issues) are the work.
+ const count = exposed.get(name)?.tool.cls === 'read' ? (callsOf.get(name) ?? 0) + 1 : 0
+ if (count) callsOf.set(name, count)
+ if (count > SAME_TOOL_STOP) {
+ if (++failing >= ERRORS_STOP) halt('errors')
+ return textResult(
+ L(
+ `Recusada: você já chamou ${name} ${SAME_TOOL_STOP} vezes nesta resposta. Trabalhe com o que já tem: escreva o que achou e o que falta. Se precisar de mais, use um recorte estreito (uma busca, um filtro de tempo) com outra ferramenta, ou peça a ${settings.workspaceName} pra continuar.`,
+ `Refused: you've already called ${name} ${SAME_TOOL_STOP} times in this reply. Work with what you have: write what you found and what's left. If you need more, use a narrow cut (a search, a time filter) with another tool, or ask ${settings.workspaceName} to go on.`
+ ),
+ true
+ )
+ }
inFlight++
acted = true
sign()
@@ -1308,6 +1380,13 @@ export class Runner {
`Careful: this call gave exactly the same result ${n} times in this reply. Repeating won't change anything: change your approach, or end saying where you got stuck.`
)
return { ...r, content: [...r.content, { type: 'text', text: warning }] }
+ } else if (count === SAME_TOOL_WARN) {
+ addSteps({ id: randomUUID(), label: L('Chamou a mesma ferramenta muitas vezes', 'Called the same tool many times'), detail: `${name} · ${count}×`, status: 'error' })
+ const warning = L(
+ `Atenção: você já chamou ${name} ${count} vezes nesta resposta. Se está paginando um histórico inteiro (um canal, logs, uma tabela), pare: peça só a janela que a tarefa precisa, com o filtro de tempo da ferramenta (ex.: oldest/latest em segundos Unix), uma busca ou um limite. Depois de ${SAME_TOOL_STOP} chamadas, ela é recusada nesta resposta.`,
+ `Careful: you've called ${name} ${count} times in this reply. If you're paging through a whole history (a channel, logs, a table), stop: ask only for the window the task needs, with the tool's time filter (e.g. oldest/latest in Unix seconds), a search or a limit. Past ${SAME_TOOL_STOP} calls, it's refused for this reply.`
+ )
+ return { ...r, content: [...r.content, { type: 'text', text: warning }] }
}
return r
} finally {
@@ -1328,7 +1407,7 @@ export class Runner {
const names = new Map<string, string[]>()
for (const a of attached) names.set(a.messageId, [...(names.get(a.messageId) ?? []), a.name])
const thread = msg.threadId ? db.message(msg.threadId) : undefined
- const { blocks, blockOf } = transcriptBlocks({ agent, conversation: conv, messages: history, agents: db.agents(), me: settings.workspaceName, task, summary, images: names, thread, searchable: canSeekThreads })
+ const { blocks, blockOf } = transcriptBlocks({ agent, conversation: conv, messages: history, agents: db.agents(), me: settings.workspaceName, task, summary, images: names, thread, searchable: canSeekThreads, unix: exposed.size > 0 })
const images: TurnImage[] = attached
.slice(-MAX_TURN_IMAGES)
.flatMap((a) => (blockOf.has(a.messageId) ? [{ block: blockOf.get(a.messageId)!, path: join(this.deps.dataDir!, 'artifacts', a.id, a.name), mime: mimeOf(a.name) }] : []))
@@ -1350,6 +1429,7 @@ export class Runner {
skills: skills && mySkills,
wiki: wiki ? { pages: wiki.count(), kinds: wiki.kinds() } : undefined,
publish: repos,
+ connectors: exposed.size > 0,
builder: builds ? builderSection(settings, { models: this.deps.models?.() ?? availableModels(settings), connectors: this.deps.connectors?.list() ?? [], team: db.agents().filter((a) => !a.archived && a.kind !== 'tuca'), own: agent.modelId }) : undefined
})
@@ -1482,9 +1562,10 @@ export class Runner {
const base = { depth: opts.depth, work, receipt, question, approvalId: approval?.id, memoryIds: memoryIds.length ? memoryIds : undefined, artifactIds: artifactIds.length ? artifactIds : undefined, services: services.length ? services : undefined, routineIds: routineIds.length ? routineIds : undefined, browser: msg.run?.browser, agentDraft: msg.run?.agentDraft }
if (control.reason === 'stopped') {
save({ run: { ...base, ...again, status: 'stopped', steps: closeThinking('error', L('Parado', 'Stopped')) } })
- } else if (control.reason === 'loop' || control.reason === 'errors' || control.reason === 'stall') {
+ } else if (control.reason === 'loop' || control.reason === 'errors' || control.reason === 'stall' || control.reason === 'sleeping') {
const why = {
loop: L(`repeti a mesma coisa, com o mesmo resultado, ${REPEAT_STOP} vezes. Parecia um loop`, `I repeated the same thing, with the same result, ${REPEAT_STOP} times. It looked like a loop`),
+ sleeping: L('fiquei tentando esperar com sleep por algo que não chegava', 'I kept trying to wait with sleep for something that wasn’t coming'),
errors: L(`${ERRORS_STOP} ferramentas falharam seguidas`, `${ERRORS_STOP} tools failed in a row`),
stall: L(`fiquei ${Math.round(stallMs / 60_000)} minutos sem nenhum sinal, travado`, `I went ${Math.round(stallMs / 60_000)} minutes without any sign of life, stuck`)
}[control.reason]
diff --git a/src/core/waits.ts b/src/core/waits.ts
new file mode 100644
index 0000000..d27e510
--- /dev/null
+++ b/src/core/waits.ts
@@ -0,0 +1,127 @@
+// Waiting, done by the app instead of the agent. A connector's result can come back still being made
+// (a SQL statement queued or running, a job started): left to the agent, it sleeps in a shell and asks
+// again, a model step and a minute each time, and the repeat guards miss it since every answer differs
+// a little. Here the app asks the connector's own status tool, with backoff, and hands back the result
+// once it's done, in the one call the agent made.
+import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
+import type { ConnectorTool } from '../shared/types'
+
+// States that mean "not done yet", as async APIs spell them (Databricks SQL: PENDING, RUNNING).
+const NOT_DONE = /^(pending|running|queued|in_progress|in-progress|starting|submitted|scheduled|waiting|processing|accepted)$/i
+const STATE_KEY = /^(state|status|life_cycle_state|lifecycle_state|run_state|statement_state)$/i
+const ID_KEY = /(^id$|_id$|Id$)/
+
+export interface Pending {
+ state: string
+ ids: Record<string, string> // every id-looking field of the result, by its key ("statement_id")
+}
+
+const text = (r: CallToolResult): string => r.content.map((c) => (c.type === 'text' ? c.text : '')).join('\n')
+
+// Walks a parsed result for a not-done state and the ids next to it.
+function walk(v: unknown, out: { state?: string; ids: Record<string, string> }, depth = 0): void {
+ if (depth > 6 || !v || typeof v !== 'object') return
+ if (Array.isArray(v)) return // a list of rows is data, not a status
+ for (const [k, x] of Object.entries(v as Record<string, unknown>)) {
+ if (typeof x === 'string') {
+ if (STATE_KEY.test(k) && NOT_DONE.test(x.trim())) out.state ??= x.trim().toUpperCase()
+ else if (ID_KEY.test(k) && x.trim() && x.length <= 200) out.ids[k] ??= x.trim()
+ } else if (x && typeof x === 'object') walk(x, out, depth + 1)
+ }
+}
+
+// What a result says when it isn't done yet: its state and its ids. Undefined when it's done, failed,
+// or isn't a status at all. Only structured results count (JSON text): prose saying "pending" doesn't.
+export function pendingOf(r: CallToolResult): Pending | undefined {
+ if (r.isError) return undefined
+ const t = text(r).trim()
+ if (!t.startsWith('{')) return undefined
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(t)
+ } catch {
+ return undefined
+ }
+ const out: { state?: string; ids: Record<string, string> } = { ids: {} }
+ walk(parsed, out)
+ return out.state && Object.keys(out.ids).length ? { state: out.state, ids: out.ids } : undefined
+}
+
+type Tool = ConnectorTool & { inputSchema?: Record<string, unknown> }
+
+const POLL_NAME = /poll|status|wait|get_?(statement|result|run|job|query|operation|execution)/i
+
+// A tool that asks how something is going (poll_sql_result, get_workflow_run): the agent calling it
+// wants the answer as it is now, so its own result is never waited on.
+export const isStatusTool = (name: string): boolean => POLL_NAME.test(name) || /^(get|describe|check)_?\w*?(statement|result|run|job|query|operation|execution|build|deploy(ment)?|pipeline|task)s?$/i.test(name)
+
+// The connector's own status tool for a pending result: a read tool whose name says it polls, and
+// whose required arguments are all ids the result gave. The tool that was just called counts too
+// (asking poll_sql_result again is how the agent would have waited).
+export function pollTool(tools: Tool[], p: Pending, can: (t: Tool) => boolean): { tool: Tool; args: Record<string, string> } | undefined {
+ for (const t of tools) {
+ if (t.cls !== 'read' || !POLL_NAME.test(t.name) || !can(t)) continue
+ const schema = (t.inputSchema ?? {}) as { required?: unknown; properties?: Record<string, unknown> }
+ const required = Array.isArray(schema.required) ? (schema.required as string[]) : []
+ const keys = required.length ? required : Object.keys(schema.properties ?? {}).filter((k) => k in p.ids)
+ if (!keys.length || !keys.every((k) => k in p.ids)) continue
+ return { tool: t, args: Object.fromEntries(keys.map((k) => [k, p.ids[k]!])) }
+ }
+ return undefined
+}
+
+// Seconds the command sleeps before anything else: "sleep 60", "sleep 1m && curl …". 0 when it doesn't
+// start by sleeping (a sleep inside a loop that checks something is a real wait, and runs).
+export function sleepSeconds(command: string): number {
+ const m = /^\s*(?:\(\s*)?sleep\s+(\d+(?:\.\d+)?)([smhd]?)(?=\s|;|&|\)|$)/.exec(command)
+ if (!m) return 0
+ const unit = { '': 1, s: 1, m: 60, h: 3600, d: 86_400 }[m[2] as '' | 's' | 'm' | 'h' | 'd']
+ return Number(m[1]) * unit
+}
+
+// Seconds a command sleeps with nothing checked after it ("sleep 60", "sleep 60 && echo check 3"): a wait
+// for something outside the computer. 0 when something runs after the sleep ("sleep 30 && curl …").
+export function idleSleepSeconds(command: string): number {
+ const s = sleepSeconds(command)
+ if (!s) return 0
+ const rest = command.replace(/^\s*(?:\(\s*)?sleep\s+\d+(?:\.\d+)?[smhd]?\s*\)?/, '')
+ return /^(?:\s*(?:&&|;|\|\|)\s*(?:echo\b[^;&|]*|printf\b[^;&|]*|true|:|date)\s*)*\s*;?\s*$/.test(rest) ? s : 0
+}
+
+export const realWait = (ms: number, signal?: AbortSignal): Promise<void> =>
+ new Promise((resolve) => {
+ if (signal?.aborted) return resolve()
+ const t = setTimeout(done, ms)
+ function done(): void {
+ clearTimeout(t)
+ signal?.removeEventListener('abort', done)
+ resolve()
+ }
+ signal?.addEventListener('abort', done, { once: true })
+ })
+
+// Polls until the result is done, the time is up or the reply is stopped: 2 s, 4 s, 8 s… up to 15 s apart.
+export async function awaitDone(
+ first: CallToolResult,
+ poll: (p: Pending) => Promise<CallToolResult | undefined>, // undefined: nothing to poll with
+ opts: { maxMs: number; wait?: (ms: number, signal?: AbortSignal) => Promise<void>; now?: () => number; signal?: AbortSignal }
+): Promise<{ result: CallToolResult; polls: number; ms: number; pending?: Pending }> {
+ const wait = opts.wait ?? realWait
+ const now = opts.now ?? Date.now
+ const start = now()
+ let result = first
+ let polls = 0
+ let pause = 2_000
+ for (let p = pendingOf(result); p; p = pendingOf(result)) {
+ const left = opts.maxMs - (now() - start)
+ if (left <= 0 || opts.signal?.aborted) return { result, polls, ms: now() - start, pending: p }
+ await wait(Math.min(pause, left), opts.signal)
+ pause = Math.min(pause * 2, 15_000)
+ if (opts.signal?.aborted) return { result, polls, ms: now() - start, pending: p }
+ const next = await poll(p)
+ if (!next) return { result, polls, ms: now() - start, pending: p }
+ polls++
+ result = next
+ }
+ return { result, polls, ms: now() - start }
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 996371a..35db4c9 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -380,6 +380,11 @@ export const RUN_STALL_MINUTES = 20 // no text, no tokens, no tool finishing: st
export const REPEAT_WARN = 3 // the same call with the same result: the agent is told to change course
export const REPEAT_STOP = 5 // ...and then the reply stops
export const ERRORS_STOP = 8 // tool calls failing in a row
+export const SAME_TOOL_WARN = 15 // one connector tool called this many times in a reply (paging a whole history): told to narrow it
+export const SAME_TOOL_STOP = 60 // ...and past it, that tool is refused for the rest of the reply
+export const SLEEPS_FREE = 1 // commands that start by sleeping 20 s or more: the first runs, the next ones are refused
+export const SLEEPS_STOP = 4 // refused sleeps in a reply before it stops
+export const PENDING_WAIT_MINUTES = 5 // a connector result still running (a SQL statement) is awaited by the app this long
// 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/test/context.test.ts b/test/context.test.ts
index 44e00c3..a7a0f6f 100644
--- a/test/context.test.ts
+++ b/test/context.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { mentioned, systemPrompt, transcript } from '../src/core/context'
+import { mentioned, stamp, systemPrompt, transcript } from '../src/core/context'
import type { Agent, Conversation, Message } from '../src/shared/types'
const agent = (id: string, handle: string, extra: Partial<Agent> = {}): Agent => ({
@@ -71,6 +71,8 @@ describe('systemPrompt', () => {
describe('transcript', () => {
const at = new Date(2026, 9, 17, 14, 2).getTime()
+ const off = -new Date(at).getTimezoneOffset()
+ const stampZone = `UTC${off < 0 ? '-' : '+'}${String(Math.floor(Math.abs(off) / 60)).padStart(2, '0')}:${String(Math.abs(off) % 60).padStart(2, '0')}`
const messages: Message[] = [
{ id: 'm1', conversationId: 'c1', author: { kind: 'me' }, text: 'Oi, time', at },
{ id: 'm2', conversationId: 'c1', author: { kind: 'system' }, text: 'Router chamou Lia', at },
@@ -82,6 +84,22 @@ describe('transcript', () => {
it('labels authors, marks the agent itself, skips system lines and empty messages', () => {
const blocks = transcript({ agent: lia, conversation: channel, messages, agents: [lia, theo], me: 'Edu' })
expect(blocks).toEqual(['Conversa em #engenharia, das mais antigas pras mais novas:', '[Edu · sáb 17/10 14:02]\nOi, time', '[Theo · agente · sáb 17/10 14:02]\nOi!', '[Lia (você) · agente · sáb 17/10 14:02]\nOlá'])
+ // An agent whose tools filter by time gets the year, the offset and the Unix seconds too.
+ const when = `sáb 17/10/2026 14:02 (${stampZone}, unix ${Math.floor(at / 1000)})`
+ expect(transcript({ agent: lia, conversation: channel, messages, agents: [lia, theo], me: 'Edu', unix: true })[1]).toBe(`[Edu · ${when}]\nOi, time`)
+ })
+
+ it('gives each message its time with the year, the UTC offset and the Unix seconds, for tools that filter by time', () => {
+ expect(stamp(at)).toMatch(/^sáb 17\/10\/2026 14:02 \(UTC[+-]\d\d:\d\d, unix \d{10}\)$/)
+ expect(Number(/unix (\d+)/.exec(stamp(at))![1])).toBe(Math.floor(at / 1000))
+ })
+
+ it('tells an agent with connectors to read only the window it needs, and not to wait with sleep', () => {
+ const s = systemPrompt({ agent: theo, settings: { workspaceName: 'Edu', context: '' }, conversation: dm, peers: [], connectors: true })
+ expect(s).toContain('oldest = (unix da última mensagem − 3600)')
+ expect(s).toContain('Não espere com sleep')
+ expect(s).toContain('Se o pedido é sobre algo de agora') // a table of open issues isn't read for the last hour only
+ expect(systemPrompt({ agent: theo, settings: { workspaceName: 'Edu', context: '' }, conversation: dm, peers: [] })).not.toContain('oldest')
})
it("keeps every block of a turn in the next one, so they come from the cache; a task goes last, with the time", () => {
diff --git a/test/faster-turns.test.ts b/test/faster-turns.test.ts
index 89c3ca1..6b9029f 100644
--- a/test/faster-turns.test.ts
+++ b/test/faster-turns.test.ts
@@ -14,7 +14,9 @@ describe('a tool result handed back to the model', () => {
const out = resultText(text('a'.repeat(60_000)))
expect(Buffer.byteLength(out, 'utf8')).toBeLessThan(50_000)
expect(out.startsWith('a'.repeat(MAX_RESULT_BYTES))).toBe(true)
- expect(out).toMatch(/pagina|paginat/i)
+ // How much was left out, and to narrow the question before reading the rest piece by piece.
+ expect(out).toContain('40 KB de 60 KB (67%')
+ expect(out).toMatch(/estreito/)
})
it('counts accents as the bytes they are, and never splits a character', () => {
diff --git a/test/slow-triage.test.ts b/test/slow-triage.test.ts
new file mode 100644
index 0000000..111affe
--- /dev/null
+++ b/test/slow-triage.test.ts
@@ -0,0 +1,339 @@
+// "Read the alarm channel, find what broke, send a summary and a triage" took about 35 minutes and
+// hundreds to thousands of tool calls, with many `sleep 60`. This reproduces it with a scripted agent
+// that does what a model does with the tools and the prompt it gets, a fake Slack (30 days of alarms,
+// 20 messages a page) and a fake Databricks whose query comes back PENDING, on a virtual clock: every
+// tool call costs a model step (STEP_S), a `sleep N` costs N seconds, and so does the app's own wait.
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { Client } from '@modelcontextprotocol/sdk/client/index.js'
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
+import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import type { Agent, Connector, EngineId, Settings } from '../src/shared/types'
+import { formatExec } from '../src/core/computer'
+import { Db } from '../src/core/db'
+import { fakeEngine } from '../src/core/engines/fake'
+import type { Engine, Turn } from '../src/core/engines/types'
+import { Gateway, textResult } from '../src/core/gateway'
+import { Runner } from '../src/core/runs'
+import { awaitDone, idleSleepSeconds, isStatusTool, pendingOf, pollTool, sleepSeconds } from '../src/core/waits'
+
+const ready = { installed: true, loggedIn: true }
+const STEP_S = 5 // a model step: what each tool call costs the agent before it's even made
+const PAGE = 20 // messages per page, Slack's usual default
+const ALARM_EVERY_S = 300 // the alarm bot posts every 5 minutes...
+const HISTORY_S = 30 * 86_400 // ...and the channel goes back 30 days
+const QUERY_S = 180 // the SQL statement runs 3 minutes (a warehouse waking up)
+
+let db: Db
+let gateway: Gateway
+let settings: Settings
+let clock: number // virtual milliseconds
+let agentCalls: string[] // tool calls the agent made (each a model step)
+let polls: number // poll_sql_result calls, the agent's or the app's
+let slept: number // seconds of sleep that ran
+
+const json = (v: unknown): CallToolResult => textResult(JSON.stringify(v))
+const firstText = (r: CallToolResult): string => (r.content[0]?.type === 'text' ? r.content[0].text : '')
+const allText = (r: CallToolResult): string => r.content.map((c) => (c.type === 'text' ? c.text : '')).join('\n')
+
+function world(opts: { pollTool?: boolean } = {}) {
+ const sent = clock // the person's message, and the end of the channel
+ const messages = Array.from({ length: HISTORY_S / ALARM_EVERY_S }, (_, i) => {
+ // Half a period off: none right on the hour's edge, whatever second the message goes out.
+ const ts = sent / 1000 - HISTORY_S + i * ALARM_EVERY_S + ALARM_EVERY_S / 2
+ const firing = ts >= sent / 1000 - 3600
+ return { ts: ts.toFixed(6), user: 'alertmanager', text: firing ? `[FIRING] job nightly_orders failed (${i})` : `[RESOLVED] all green (${i})` }
+ })
+ const statements = new Map<string, number>() // id -> when it's done (virtual ms)
+ const connectors: Connector[] = [
+ { id: 'slack', name: 'Slack', kind: 'remote', auth: 'none', status: 'connected', tools: [] },
+ { id: 'dbx', name: 'Databricks', kind: 'remote', auth: 'none', status: 'connected', tools: [] }
+ ]
+ db.saveConnector({ id: 'slack', name: 'Slack', kind: 'remote', auth: 'none' })
+ db.saveConnector({ id: 'dbx', name: 'Databricks', kind: 'remote', auth: 'none' })
+ db.syncTools('slack', [
+ { name: 'slack_read_channel', description: 'Reads one page of a channel, newest first.', cls: 'read', inputSchema: { type: 'object', properties: { channel_id: { type: 'string' }, oldest: { type: 'string' }, latest: { type: 'string' }, cursor: { type: 'string' }, limit: { type: 'number' } }, required: ['channel_id'] } }
+ ])
+ db.syncTools('dbx', [
+ { name: 'execute_sql_read_only', description: 'Runs a read-only SQL statement.', cls: 'read', inputSchema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] } },
+ ...(opts.pollTool === false ? [] : [{ name: 'poll_sql_result', description: 'Gets the status and result of a statement.', cls: 'read' as const, inputSchema: { type: 'object', properties: { statement_id: { type: 'string' } }, required: ['statement_id'] } }])
+ ])
+ return {
+ list: () => connectors,
+ call: async (id: string, name: string, args: Record<string, unknown>): Promise<CallToolResult> => {
+ if (name === 'slack_read_channel') {
+ const oldest = Number(args['oldest'] ?? 0)
+ const from = Number(args['cursor'] ?? 0)
+ const window = messages.filter((m) => Number(m.ts) >= oldest).reverse()
+ const page = window.slice(from, from + Number(args['limit'] ?? PAGE))
+ const more = from + page.length < window.length
+ return json({ ok: true, messages: page, has_more: more, ...(more ? { response_metadata: { next_cursor: String(from + page.length) } } : {}) })
+ }
+ if (name === 'execute_sql_read_only') {
+ const statement_id = `s-${statements.size + 1}`
+ statements.set(statement_id, clock + QUERY_S * 1000)
+ return json({ statement_id, status: { state: 'PENDING' } })
+ }
+ if (name === 'poll_sql_result') {
+ polls++
+ const statement_id = String(args['statement_id'])
+ const done = statements.get(statement_id)
+ if (done === undefined) return textResult('No such statement.', true)
+ // Each answer carries how long it has run, so no two are the same.
+ if (clock < done) return json({ statement_id, status: { state: 'RUNNING' }, elapsed_ms: clock - (done - QUERY_S * 1000) })
+ return json({ statement_id, status: { state: 'SUCCEEDED' }, result: { data_array: [['nightly_orders', 'FAILED', 'OutOfMemoryError on stage 12', '2026-11-05 09:31']] } })
+ }
+ throw new Error(`unknown tool ${id}/${name}`)
+ }
+ }
+}
+
+// What a model does with these tools: read the channel page after page (with a time window only
+// when it knows what "now" is), run the query, and while it's pending sleep a minute and ask again.
+// It heeds what the tools tell it, as a model does: a warning to narrow, a refused sleep, a cut.
+function triageAgent(): Engine {
+ return {
+ id: 'claude',
+ async *run(turn: Turn) {
+ const client = new Client({ name: 'triage-agent', version: '0.0.0' })
+ await client.connect(new StreamableHTTPClientTransport(new URL(turn.mcpUrl!)))
+ const call = async (name: string, args: Record<string, unknown>): Promise<CallToolResult> => {
+ clock += STEP_S * 1000
+ agentCalls.push(name)
+ return (await client.callTool({ name, arguments: args })) as CallToolResult
+ }
+ try {
+ // "now", if the prompt gives it as Unix seconds: the last message's own time.
+ const unix = [...turn.prompt.matchAll(/unix (\d+)\)\]/g)].at(-1)?.[1]
+ const windowed = unix && /oldest/.test(turn.system) ? { oldest: String(Number(unix) - 3600) } : {}
+ let cursor: string | undefined
+ const alarms: string[] = []
+ for (;;) {
+ if (turn.signal.aborted) return
+ const r = await call('slack__slack_read_channel', { channel_id: 'C0ALARMS', ...windowed, ...(cursor ? { cursor } : {}) })
+ if (r.isError) break
+ const page = JSON.parse(firstText(r)) as { messages: { text: string }[]; has_more: boolean; response_metadata?: { next_cursor: string, grok: string } }
+ alarms.push(...page.messages.filter((m) => m.text.startsWith('[FIRING]')).map((m) => m.text))
+ if (/Atenção: você já chamou|Careful: you've called/.test(allText(r))) break // told to narrow: it has the alarm already
+ if (!page.has_more) break
+ cursor = page.response_metadata!.next_cursor
+ }
+ const query = { query: "SELECT job, state, error, at FROM ops.job_runs WHERE at > now() - INTERVAL 1 HOUR AND state = 'FAILED'" }
+ let r = await call('databricks__execute_sql_read_only', query)
+ for (let i = 1; !turn.signal.aborted && i < 100; i++) {
+ const state = (JSON.parse(firstText(r)) as { status?: { state?: string } }).status?.state
+ if (state !== 'PENDING' && state !== 'RUNNING') break
+ if (/\[(Ainda|Still) /.test(allText(r))) break // the app waited and says to move on
+ await call('bash', { command: `sleep 60 && echo "check ${i}"` })
+ const polled = await call('databricks__poll_sql_result', { statement_id: (JSON.parse(firstText(r)) as { statement_id: string }).statement_id })
+ // No status tool: it runs the query again, as a model would.
+ r = polled.isError ? await call('databricks__execute_sql_read_only', query) : polled
+ }
+ if (turn.signal.aborted) return
+ const text = `**Resumo:** ${alarms.length} alarmes do nightly_orders na última hora. **Triagem:** ${firstText(r).includes('OutOfMemoryError') ? 'OOM no stage 12, P1.' : 'consulta ainda rodando.'}`
+ yield { type: 'text', delta: text }
+ yield { type: 'done', text, usage: { inputTokens: 100, cacheReadTokens: 0, outputTokens: 50 } }
+ } finally {
+ await client.close()
+ }
+ }
+ }
+}
+
+function runner(connectors: ReturnType<typeof world>, engine: Engine = triageAgent()): Runner {
+ const engines: Record<EngineId, Engine> = { claude: engine, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
+ const computers = {
+ call: async (_a: Agent, name: string, args: Record<string, unknown>) => {
+ const command = String(args['command'] ?? '')
+ const s = Number(/^\s*sleep\s+(\d+)/.exec(command)?.[1] ?? 0)
+ clock += s * 1000
+ slept += s
+ return { result: textResult(formatExec({ code: 0, stdout: command.replace(/^.*echo\s+"?([^"]*)"?$/, '$1'), stderr: '' }, 120)) }
+ }
+ }
+ const timers = { wait: async (ms: number) => void (clock += ms), now: () => clock }
+ return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'st-w-')), gateway, connectors, computers, timers })
+}
+
+const reply = () => db.messages().filter((m) => m.author.kind === 'agent').at(-1)!
+
+async function triage(connectors = world()) {
+ const start = clock
+ const r = runner(connectors)
+ await r.send('dm', 'Lê o #alarmes, acha o que quebrou no alarme da última hora e me manda um resumo e a triagem.')
+ await r.idle()
+ const minutes = (clock - start) / 60_000
+ return { minutes, calls: agentCalls.length, polls, slept, reply: reply() }
+}
+
+beforeEach(async () => {
+ db = new Db(join(mkdtempSync(join(tmpdir(), 'st-db-')), 'test.db'))
+ settings = { workspaceName: 'Gabriel', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ db.saveAgent({ id: 'ops', name: 'Ops', handle: 'ops', role: 'Plantão', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 50_000_000, used: 0, grants: { slack: 'read', dbx: 'read' }, memory: 'auto', computer: true, archived: false })
+ db.createConversation({ id: 'dm', kind: 'dm', name: 'ops', members: ['ops'] })
+ clock = Date.now()
+ agentCalls = []
+ polls = 0
+ slept = 0
+ gateway = new Gateway()
+ await gateway.start()
+})
+afterEach(() => gateway.stop())
+
+describe('an alarm triage', () => {
+ it('reads only the last hour and gets the pending query back done: a few minutes and a handful of calls', async () => {
+ const t = await triage()
+ console.log(`[slow-triage] ${t.calls} agent calls, ${t.polls} polls by the app, ${t.slept} s slept, ${t.minutes.toFixed(1)} min`)
+ expect(t.reply.run!.status).toBe('done')
+ expect(t.reply.text).toContain('OOM no stage 12')
+ expect(t.reply.text).toContain('12 alarmes') // the last hour: one page, with every alarm in it
+ expect(t.calls).toBeLessThanOrEqual(3)
+ expect(t.slept).toBe(0)
+ expect(t.minutes).toBeLessThan(QUERY_S / 60 + 1) // the query's own time, and little else
+ expect(t.reply.run!.steps.some((s) => /esperou 3 min/.test(s.detail ?? ''))).toBe(true)
+ })
+
+ it('an agent that ignores the window is told to narrow at 15 pages, not left to read 30 days', async () => {
+ const engine = triageAgent()
+ // A model that pays no attention to the times in the prompt.
+ const blind: Engine = { id: 'claude', run: (turn) => engine.run({ ...turn, prompt: turn.prompt.replace(/unix \d+/g, '') }) }
+ const r = runner(world(), blind)
+ await r.send('dm', 'Lê o #alarmes e me manda a triagem.')
+ await r.idle()
+ expect(agentCalls.filter((c) => c.endsWith('slack_read_channel'))).toHaveLength(15)
+ expect(reply().run!.status).toBe('done')
+ })
+
+ it('without a status tool to wait with, sleeps after the first are refused and the reply still ends', async () => {
+ const t = await triage(world({ pollTool: false }))
+ console.log(`[slow-triage, no status tool] ${t.calls} agent calls, ${t.slept} s slept, ${t.minutes.toFixed(1)} min, ${t.reply.run!.status}`)
+ expect(t.slept).toBe(60) // the first one ran
+ expect(t.reply.run!.steps.filter((s) => s.label === 'Não esperou com sleep').length).toBeGreaterThan(0)
+ expect(t.reply.run!.status === 'done' || t.reply.run!.status === 'failed').toBe(true)
+ expect(t.calls).toBeLessThan(20)
+ })
+})
+
+// An agent that makes these calls, in order, and ends.
+function scripted(calls: [string, Record<string, unknown>][]): Engine {
+ return {
+ id: 'claude',
+ async *run(turn: Turn) {
+ const client = new Client({ name: 'scripted', version: '0.0.0' })
+ await client.connect(new StreamableHTTPClientTransport(new URL(turn.mcpUrl!)))
+ try {
+ for (const [name, args] of calls) {
+ clock += STEP_S * 1000
+ agentCalls.push(name)
+ const r = (await client.callTool({ name, arguments: args })) as CallToolResult
+ agentCalls.push(`=> ${allText(r).slice(0, 80)}`)
+ }
+ yield { type: 'done', text: 'pronto', usage: { inputTokens: 1, cacheReadTokens: 0, outputTokens: 1 } }
+ } finally {
+ await client.close()
+ }
+ }
+ }
+}
+
+describe('what stays as it was', () => {
+ it('sleeps before checking something on the computer always run, and so do an agent without connectors', async () => {
+ const r = runner(world(), scripted([['bash', { command: 'sleep 30 && curl -s localhost:3000' }], ['bash', { command: 'sleep 30 && curl -s localhost:3000' }], ['bash', { command: 'sleep 30 && curl -s localhost:3000' }]]))
+ await r.send('dm', 'sobe o servidor e confere')
+ await r.idle()
+ expect(slept).toBe(90)
+ db.saveAgent({ ...db.agent('ops')!, grants: {} }) // a coding agent: no connectors
+ slept = 0
+ const coder = runner(world(), scripted([['bash', { command: 'sleep 60' }], ['bash', { command: 'sleep 60' }], ['bash', { command: 'sleep 60' }]]))
+ await coder.send('dm', 'espera o build')
+ await coder.idle()
+ expect(slept).toBe(180)
+ })
+
+ it("asking a status tool itself gets today's answer, not a wait", async () => {
+ const r = runner(world(), scripted([['databricks__execute_sql_read_only', { query: 'select 1' }]]))
+ await r.send('dm', 'roda')
+ await r.idle()
+ polls = 0
+ const start = clock
+ const asks = runner(world(), scripted([['databricks__poll_sql_result', { statement_id: 's-1' }]]))
+ await asks.send('dm', 'já terminou?')
+ await asks.idle()
+ expect(polls).toBe(1) // its own call, answered RUNNING, and nothing more
+ expect(clock - start).toBeLessThan(10_000)
+ })
+
+ it('many writes in a row are the work: only reads count toward the same-tool guard', async () => {
+ db.saveConnector({ id: 'sheet', name: 'Planilha', kind: 'remote', auth: 'none' })
+ db.syncTools('sheet', [{ name: 'insert_row', description: 'Inserts a row.', cls: 'write', inputSchema: { type: 'object', properties: { v: { type: 'number' } } } }])
+ db.saveAgent({ ...db.agent('ops')!, grants: { sheet: 'read_write' } })
+ const calls = { n: 0 }
+ const sheet = {
+ list: (): Connector[] => [{ id: 'sheet', name: 'Planilha', kind: 'remote', auth: 'none', status: 'connected', tools: [] }],
+ call: async (): Promise<CallToolResult> => json({ ok: true, n: ++calls.n })
+ }
+ const r = runner(sheet as unknown as ReturnType<typeof world>, scripted(Array.from({ length: 70 }, (_, i): [string, Record<string, unknown>] => ['planilha__insert_row', { v: i }])))
+ await r.send('dm', 'insere as 70 linhas')
+ await r.idle()
+ expect(calls.n).toBe(70)
+ expect(reply().run!.status).toBe('done')
+ })
+})
+
+describe('waiting on a pending result', () => {
+ const pending = json({ statement_id: 's-1', status: { state: 'PENDING' } })
+ const tools = [
+ { name: 'execute_sql_read_only', description: '', cls: 'read' as const, enabled: true, highRisk: false, isNew: false, inputSchema: { required: ['query'] } },
+ { name: 'poll_sql_result', description: '', cls: 'read' as const, enabled: true, highRisk: false, isNew: false, inputSchema: { required: ['statement_id'] } }
+ ]
+
+ it('knows a not-done state from a done one, and only in a structured result', () => {
+ expect(pendingOf(pending)).toEqual({ state: 'PENDING', ids: { statement_id: 's-1' } })
+ expect(pendingOf(json({ run_id: 7, state: { life_cycle_state: 'RUNNING' }, job_id: 'j' }))?.state).toBe('RUNNING')
+ expect(pendingOf(json({ statement_id: 's-1', status: { state: 'SUCCEEDED' } }))).toBeUndefined()
+ expect(pendingOf(json({ statement_id: 's-1', status: { state: 'FAILED' } }))).toBeUndefined()
+ expect(pendingOf(textResult('The deploy is still pending, statement_id s-1'))).toBeUndefined()
+ expect(pendingOf(json({ rows: [{ id: 'a', status: 'pending' }] }))).toBeUndefined() // rows of data, not a status
+ })
+
+ it("finds the connector's status tool by the ids the result gave", () => {
+ expect(pollTool(tools, pendingOf(pending)!, () => true)).toMatchObject({ tool: { name: 'poll_sql_result' }, args: { statement_id: 's-1' } })
+ expect(pollTool(tools, pendingOf(pending)!, (t) => t.name !== 'poll_sql_result')).toBeUndefined() // not granted
+ expect(pollTool([{ ...tools[1]!, cls: 'write' }], pendingOf(pending)!, () => true)).toBeUndefined() // never a write tool
+ })
+
+ it('polls with backoff until done, and gives up at the limit with the result still pending', async () => {
+ let t = 0
+ const timers = { wait: async (ms: number) => void (t += ms), now: () => t }
+ const done = await awaitDone(pending, async () => (t >= 30_000 ? json({ status: { state: 'SUCCEEDED' } }) : pending), { maxMs: 300_000, ...timers })
+ expect(done.pending).toBeUndefined()
+ expect(done.polls).toBe(5) // at 2, 6, 14, 29 s still running; at 44 s done
+ t = 0
+ const late = await awaitDone(pending, async () => pending, { maxMs: 60_000, ...timers })
+ expect(late.pending?.state).toBe('PENDING')
+ expect(late.ms).toBe(60_000)
+ })
+
+ it('reads how long a command sleeps before doing anything', () => {
+ expect(sleepSeconds('sleep 60')).toBe(60)
+ expect(sleepSeconds('sleep 60 && echo "check 3"')).toBe(60)
+ expect(sleepSeconds(' sleep 1m; curl x')).toBe(60)
+ expect(sleepSeconds('sleep 2 && curl localhost:5173')).toBe(2)
+ expect(sleepSeconds('for i in 1 2 3; do curl x && break; sleep 10; done')).toBe(0)
+ expect(sleepSeconds('npm test')).toBe(0)
+ })
+
+ it('tells a sleep with nothing after it from one before a check, and a status tool by its name', () => {
+ expect(idleSleepSeconds('sleep 60')).toBe(60)
+ expect(idleSleepSeconds('sleep 60 && echo "check 3"')).toBe(60)
+ expect(idleSleepSeconds('sleep 1m; date')).toBe(60)
+ expect(idleSleepSeconds('sleep 30 && curl -s localhost:3000')).toBe(0)
+ expect(idleSleepSeconds('sleep 60; gh run view 123')).toBe(0)
+ expect(idleSleepSeconds('npm test')).toBe(0)
+ expect(isStatusTool('poll_sql_result')).toBe(true)
+ expect(isStatusTool('get_workflow_run')).toBe(true)
+ expect(isStatusTool('execute_sql_read_only')).toBe(false)
+ })
+})