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.

Try a failed routine again, twice, before giving up (#30)

Eduardo Machadof5d94d5d6ca1
diff --git a/src/core/index.ts b/src/core/index.ts
index 64469a7..bb92c0c 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -288,7 +288,7 @@ const backups = join(dataDir, 'backups')
// The runner runs routines, and agents schedule routines through the runner's tools.
const routines = new Routines({
db,
- runner: { runRoutine: (r, when) => runner.runRoutine(r, when) },
+ runner: { runRoutine: (r, when) => runner.runRoutine(r, when), retryRoutine: (r, when, id) => runner.retryRoutine(r, when, id) },
connectors: { call: (id, tool, args) => connectors.call(id, tool, args), list: () => connectors.list() },
blocked: () => !!settings().paused || inQuietHours(settings().quietHours),
emit,
diff --git a/src/core/routines.ts b/src/core/routines.ts
index d4da1a8..b4b7509 100644
--- a/src/core/routines.ts
+++ b/src/core/routines.ts
@@ -13,6 +13,8 @@ import type { RoutineEvent } from './runs'
export const TICK_MS = 30_000
export const LATE_GRACE_MS = 12 * 3_600_000 // a run missed by more than this is skipped
const LATE_AFTER_MS = 2 * 60_000 // later than this is "atrasada" in the conversation
+// A reply that fails is tried again in place, after these waits; then it stays failed.
+export const RETRY_WAITS_MS = [60_000, 5 * 60_000]
export const MAX_AGENT_ROUTINES = 10 // active ones per agent, so an agent can't schedule itself without end
const DAY_KEYS = ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sab']
@@ -75,12 +77,16 @@ const MAX_EVENT_CHARS = 6_000
export interface RoutineDeps {
db: Db
- runner: { runRoutine(r: Routine, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }): Promise<Message | undefined> }
+ runner: {
+ runRoutine(r: Routine, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }): Promise<Message | undefined>
+ retryRoutine?(r: Routine, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }, messageId: string): Promise<Message | undefined>
+ }
connectors?: { call(id: string, tool: string, args: Record<string, unknown>): Promise<CallToolResult>; list(): Connector[] }
blocked?: () => boolean // paused, or quiet hours: nothing is due until it ends (then it runs late)
emit: (e: CoreEvent) => void
notify?: (title: string, body: string, conversationId: string) => void
now?: () => number
+ wait?: (ms: number) => Promise<void> // between tries (tests skip it)
}
export class Routines {
@@ -310,14 +316,32 @@ export class Routines {
this.deps.emit({ type: 'routine', routine: r })
}
+ private runWithRetries(r: Routine, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }): Promise<Message | undefined> {
+ const { runner, db, emit } = this.deps
+ return retrying(
+ () => runner.runRoutine(r, when),
+ runner.retryRoutine && ((messageId) => runner.retryRoutine!(db.routine(r.id) ?? r, when, messageId)),
+ {
+ db,
+ emit,
+ wait: this.deps.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms).unref())),
+ // Turning the routine off (or deleting it) stops the tries. One that was already
+ // off when it fired (a one-off, or "Rodar agora") still gets them.
+ enabled: () => {
+ const now = db.routine(r.id)
+ return !!now && (!r.enabled || now.enabled)
+ }
+ }
+ )
+ }
+
// One run of a routine at a time: if the last one is still going, this one skips.
// `more`: a connector check left new items, so check again when this run ends.
private fire(id: string, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }, more = false): void {
const r = this.deps.db.routine(id)
if (!r || this.running.has(id)) return
this.running.add(id)
- const run = this.deps.runner
- .runRoutine(r, when)
+ const run = this.runWithRetries(r, when)
.then((reply) => {
if (!reply) return
const latest = this.deps.db.routine(id)
@@ -335,6 +359,44 @@ export class Routines {
}
}
+// Runs a routine, and a reply that failed again in place up to RETRY_WAITS_MS.length times.
+// Waiting, the reply says when the next try is; after the last one it says how many there were.
+// It stops trying when the person already did something about it: retried it, or turned the routine off.
+export async function retrying(
+ first: () => Promise<Message | undefined>,
+ again: ((messageId: string) => Promise<Message | undefined>) | undefined,
+ deps: { db: Db; emit: (e: CoreEvent) => void; wait: (ms: number) => Promise<void>; enabled: () => boolean }
+): Promise<Message | undefined> {
+ let reply = await first()
+ if (!again) return reply
+ const tries = RETRY_WAITS_MS.length + 1
+ const note = (m: Message, error: string): Message => {
+ const saved: Message = { ...m, run: { ...m.run!, error } }
+ deps.db.saveMessage(saved)
+ deps.emit({ type: 'message', message: saved })
+ return saved
+ }
+ const plain = (e: string | undefined): string => (e ?? L('Falhou', 'Failed')).replace(/[.\s]+$/, '')
+ for (let i = 0; i < RETRY_WAITS_MS.length && reply?.run?.status === 'failed'; i++) {
+ const wait = RETRY_WAITS_MS[i]!
+ const base = reply.run.error ?? ''
+ const min = Math.round(wait / 60_000)
+ note(reply, `${plain(base)}. ${L(`Tento de novo em ${min} min (tentativa ${i + 2} de ${tries}).`, `Trying again in ${min} min (try ${i + 2} of ${tries}).`)}`)
+ await deps.wait(wait)
+ const now = deps.db.message(reply.id)
+ if (now?.run?.status !== 'failed' || !deps.enabled()) {
+ // Someone acted on it meanwhile: the note about the next try goes.
+ return now?.run?.status === 'failed' ? note(now, base) : (now ?? reply)
+ }
+ const next = await again(reply.id)
+ if (!next) return deps.db.message(reply.id) ?? reply
+ reply = next
+ if (reply.run?.status === 'failed' && i === RETRY_WAITS_MS.length - 1)
+ reply = note(reply, `${plain(reply.run.error)}. ${L(`Tentei ${tries} vezes.`, `Tried ${tries} times.`)}`)
+ }
+ return reply
+}
+
const agentName = (db: Db, id: string): string => db.agent(id)?.name ?? L('Agente', 'Agent')
// The notification's body: how the run ended, or the start of the reply.
diff --git a/src/core/runs.ts b/src/core/runs.ts
index 49ab033..8b1b85f 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -258,8 +258,38 @@ export class Runner {
db.saveMessage(ask)
emit({ type: 'message', message: ask })
+ return new Promise((resolve) =>
+ this.enqueue(() =>
+ this.execute(agent, conv, { depth: 1, task: this.routineTask(r, when, me), work: event ? workIn(event.title) : undefined, routine: true }).then(resolve, (e: unknown) => {
+ resolve(undefined)
+ throw e
+ })
+ )
+ )
+ }
+
+ // A routine's reply that failed, run again in place with the same request.
+ async retryRoutine(r: Routine, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }, messageId: string): Promise<Message | undefined> {
+ const { db } = this.deps
+ const msg = db.message(messageId)
+ const conv = db.conversation(r.conversationId)
+ const agent = db.agent(r.agentId)
+ if (!msg?.run || msg.run.status !== 'failed' || !conv || !agent || agent.archived) return undefined
+ const me = (await this.deps.settings()).workspaceName
+ return new Promise((resolve) =>
+ this.enqueue(() =>
+ this.execute(agent, conv, { depth: 1, existing: msg, task: this.routineTask(r, when, me), work: msg.run!.work, routine: true }).then(resolve, (e: unknown) => {
+ resolve(undefined)
+ throw e
+ })
+ )
+ )
+ }
+
+ private routineTask(r: Routine, when: { scheduledAt: number; late: boolean; event?: RoutineEvent }, me: string): string {
+ const { event } = when
const hm = new Date(when.scheduledAt).toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' })
- const task = [
+ return [
event
? L(
`Esta é a rotina "${r.name}", que ${me} criou pra rodar quando acontece um evento: ${event.source}. Aconteceu agora: ${event.title}.`,
@@ -281,14 +311,6 @@ export class Runner {
]
.filter(Boolean)
.join(' ')
- return new Promise((resolve) =>
- this.enqueue(() =>
- this.execute(agent, conv, { depth: 1, task, work: event ? workIn(event.title) : undefined, routine: true }).then(resolve, (e: unknown) => {
- resolve(undefined)
- throw e
- })
- )
- )
}
// Resolves when nothing is routing, running or queued (tests and shutdown).
diff --git a/test/routines.test.ts b/test/routines.test.ts
index 255787f..e7989f7 100644
--- a/test/routines.test.ts
+++ b/test/routines.test.ts
@@ -3,12 +3,12 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { CoreEvent } from '../src/shared/rpc'
-import { describeSchedule, nextRun, type Agent, type EngineId, type Routine, type Settings } from '../src/shared/types'
+import { describeSchedule, nextRun, type Agent, type EngineId, type Message, type Routine, type Settings } from '../src/shared/types'
import { Db } from '../src/core/db'
import { fakeEngine } from '../src/core/engines/fake'
import type { Engine, Turn } from '../src/core/engines/types'
import { Gateway } from '../src/core/gateway'
-import { LATE_GRACE_MS, MAX_AGENT_ROUTINES, outcome, Routines } from '../src/core/routines'
+import { LATE_GRACE_MS, MAX_AGENT_ROUTINES, outcome, retrying, Routines } from '../src/core/routines'
import { Runner } from '../src/core/runs'
const at = (y: number, mo: number, d: number, h = 0, mi = 0): number => new Date(y, mo - 1, d, h, mi).getTime()
@@ -251,3 +251,118 @@ describe('quiet hours', () => {
expect(inQuietHours(undefined, at(3))).toBe(false)
})
})
+
+// A reply that fails is tried again in place, up to twice, and then stays failed.
+describe('routine retries', () => {
+ const ready = { installed: true, loggedIn: true }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ const lia: Agent = { id: 'a1', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'read', computer: false, archived: false }
+
+ let db: Db
+ let gateway: Gateway
+ let runner: Runner
+ let routines: Routines
+ let clock: number
+ let failures: number // how many turns fail before one works
+ let turns: number
+ let waits: number[]
+ let notes: string[]
+ let onWait: () => void
+
+ beforeEach(async () => {
+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-retry-')), 'test.db'))
+ db.saveAgent(lia)
+ db.createConversation({ id: 'c1', kind: 'channel', name: 'geral', members: ['a1'] })
+ clock = at(2026, 10, 19, 8, 0)
+ turns = 0
+ waits = []
+ notes = []
+ onWait = () => {}
+ const flaky: Engine = {
+ id: 'claude',
+ async *run() {
+ turns++
+ if (turns <= failures) yield { type: 'error', message: `o provedor caiu (${turns})` }
+ else yield { type: 'done', text: 'Feito.', usage: { inputTokens: 1, cacheReadTokens: 0, outputTokens: 1 } }
+ }
+ }
+ const engines: Record<EngineId, Engine> = { claude: flaky, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini') }
+ gateway = new Gateway()
+ await gateway.start()
+ routines = new Routines({
+ db,
+ runner: { runRoutine: (r, when) => runner.runRoutine(r, when), retryRoutine: (r, when, id) => runner.retryRoutine(r, when, id) },
+ emit: () => {},
+ now: () => clock,
+ wait: async (ms) => (waits.push(ms), onWait()),
+ notify: (_title, body) => notes.push(body)
+ })
+ runner = new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-retry-w-')), gateway, routines })
+ })
+
+ afterEach(async () => {
+ await gateway.stop()
+ })
+
+ const fire = async (): Promise<Routine> => {
+ const r = routines.save({ name: 'Bom dia', agentId: 'a1', conversationId: 'c1', prompt: 'Resume o Linear.', schedule: { days: WEEKDAYS, time: '09:00' }, enabled: true })
+ clock = at(2026, 10, 19, 9, 0) + 10_000
+ routines.tick()
+ await routines.idle()
+ await runner.idle()
+ return r
+ }
+ const replies = () => db.messages().filter((m) => m.author.kind === 'agent')
+
+ it('a failure is tried again in the same reply, and the notice comes once, when it worked', async () => {
+ failures = 2
+ await fire()
+ expect(turns).toBe(3)
+ expect(waits).toEqual([60_000, 300_000])
+ expect(replies()).toHaveLength(1)
+ expect(replies()[0]!.run).toMatchObject({ status: 'done' })
+ expect(notes).toEqual(['Feito.'])
+ })
+
+ it('after the third failure it stops, says it tried three times, and notifies once', async () => {
+ failures = 99
+ await fire()
+ expect(turns).toBe(3)
+ const [reply] = replies()
+ expect(replies()).toHaveLength(1)
+ expect(reply!.run).toMatchObject({ status: 'failed' })
+ expect(reply!.run!.error).toBe('o provedor caiu (3). Tentei 3 vezes.')
+ expect(notes).toHaveLength(1)
+ expect(notes[0]).toBe('Falhou: o provedor caiu (3). Tentei 3 vezes.')
+ })
+
+ it('waiting, the reply says when the next try is', async () => {
+ failures = 1
+ const seen: string[] = []
+ onWait = () => void seen.push(replies()[0]?.run?.error ?? '')
+ await fire()
+ expect(seen).toEqual(['o provedor caiu (1). Tento de novo em 1 min (tentativa 2 de 3).'])
+ })
+
+ it('turning the routine off while it waits stops the tries, and the note about the next one goes', async () => {
+ failures = 99
+ onWait = () => {
+ const r = db.routines()[0]!
+ routines.save({ id: r.id, name: r.name, agentId: r.agentId, conversationId: r.conversationId, prompt: r.prompt, schedule: r.schedule, enabled: false })
+ }
+ await fire()
+ expect(turns).toBe(1)
+ expect(replies()[0]!.run).toMatchObject({ status: 'failed', error: expect.not.stringMatching(/Tento de novo/) })
+ })
+
+ it('only a failure is tried again: a limit, an approval, a question or a stop are not', async () => {
+ for (const status of ['limit_reached', 'waiting_approval', 'waiting_input', 'stopped', 'done'] as const) {
+ const reply = { id: 'm1', conversationId: 'c1', author: { kind: 'agent', id: 'a1' }, text: '', at: 0, run: { status, steps: [] } } as unknown as Message
+ let again = 0
+ const out = await retrying(async () => reply, async () => (again++, reply), { db, emit: () => {}, wait: async (ms) => void waits.push(ms), enabled: () => true })
+ expect(out).toBe(reply)
+ expect(again).toBe(0)
+ }
+ expect(waits).toEqual([])
+ })
+})