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.

feat: per-agent max enabled routines limit (#66)

Brunofc51c1873c21
diff --git a/src/core/db.ts b/src/core/db.ts
index d3946c1..f60d1d1 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -1,5 +1,5 @@
import { DatabaseSync } from 'node:sqlite'
-import { CACHE_READ_WEIGHT, type Agent, type AgentApp, type AgentColor, type Approval, type ApprovalState, type Artifact, type ArtifactKind, type Author, type Connector, type ConnectorAuth, type ConnectorTool, type Conversation, type Effort, type LentFolder, type Memory, type MemoryMode, type MemoryState, type Message, type Receipt, type Routine, type RoutineRun, type Run, type Settings, type Skill, type SkillVersion, type ToolClass, type Trigger } from '../shared/types'
+import { CACHE_READ_WEIGHT, routineCap, type Agent, type AgentApp, type AgentColor, type Approval, type ApprovalState, type Artifact, type ArtifactKind, type Author, type Connector, type ConnectorAuth, type ConnectorTool, type Conversation, type Effort, type LentFolder, type Memory, type MemoryMode, type MemoryState, type Message, type Receipt, type Routine, type RoutineRun, type Run, type Settings, type Skill, type SkillVersion, type ToolClass, type Trigger } from '../shared/types'
// Each entry runs once, in order; PRAGMA user_version records how far we got.
const MIGRATIONS = [
@@ -230,6 +230,9 @@ const MIGRATIONS = [
`,
`
ALTER TABLE agents ADD COLUMN fallback_account TEXT;
+ `,
+ `
+ ALTER TABLE agents ADD COLUMN max_routines INTEGER NOT NULL DEFAULT 10;
`
]
@@ -318,6 +321,7 @@ export class Db {
...(str(r['fallback_account']) ? { fallbackAccountId: str(r['fallback_account']) } : {}),
effort: str(r['effort']) as Effort,
limit: Number(r['limit_tokens']),
+ maxRoutines: routineCap(Number(r['max_routines'])),
used: this.usedThisMonth(str(r['id'])),
grants: JSON.parse(str(r['grants']) || '{}') as Agent['grants'],
memory: (str(r['memory_mode']) || 'auto') as MemoryMode,
@@ -345,14 +349,14 @@ export class Db {
saveAgent(a: Agent): void {
this.db
.prepare(
- `INSERT INTO agents (id, name, handle, role, color, instructions, model, fallback_model, fallback_account, account, effort, limit_tokens, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `INSERT INTO agents (id, name, handle, role, color, instructions, model, fallback_model, fallback_account, account, effort, limit_tokens, max_routines, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (id) DO UPDATE SET name = excluded.name, handle = excluded.handle, role = excluded.role,
color = excluded.color, instructions = excluded.instructions, model = excluded.model, fallback_model = excluded.fallback_model, fallback_account = excluded.fallback_account, account = excluded.account, effort = excluded.effort,
- limit_tokens = excluded.limit_tokens, grants = excluded.grants, memory_mode = excluded.memory_mode,
+ limit_tokens = excluded.limit_tokens, max_routines = excluded.max_routines, grants = excluded.grants, memory_mode = excluded.memory_mode,
computer = excluded.computer, computer_kind = excluded.computer_kind, web = excluded.web, browser = excluded.browser, apps = excluded.apps, auto_approve = excluded.auto_approve, archived = excluded.archived, kind = COALESCE(excluded.kind, agents.kind)`
)
- .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.fallbackModelId || null, a.fallbackAccountId || null, a.accountId || null, a.effort, a.limit, JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, Date.now())
+ .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.fallbackModelId || null, a.fallbackAccountId || null, a.accountId || null, a.effort, a.limit, routineCap(a.maxRoutines), JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, Date.now())
}
// Kept apart from saveAgent: folders change only after the core checks them.
diff --git a/src/core/routines.ts b/src/core/routines.ts
index b4b7509..f09bcdf 100644
--- a/src/core/routines.ts
+++ b/src/core/routines.ts
@@ -5,17 +5,18 @@ import { createHash, randomBytes, randomUUID } from 'node:crypto'
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
import { L, locale } from '../shared/lang'
import type { CoreEvent } from '../shared/rpc'
-import { describeSchedule, nextRun, validTime, type Agent, type Connector, type Conversation, type Message, type Routine, type RoutineInput, type Trigger } from '../shared/types'
+import { describeSchedule, MAX_AGENT_ROUTINES, nextRun, routineCap, validTime, type Agent, type Connector, type Conversation, type Message, type Routine, type RoutineInput, type Trigger } from '../shared/types'
import type { Db } from './db'
import type { ToolDef } from './gateway'
import type { RoutineEvent } from './runs'
+export { MAX_AGENT_ROUTINES } // the default; each agent's own is agent.maxRoutines
+
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']
const DAY_KEYS_EN = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] // also understood
@@ -253,7 +254,8 @@ export class Routines {
const replaces = text('substitui')
const prev = replaces ? this.deps.db.routine(replaces) : undefined
if (replaces && prev?.agentId !== agent.id) return fail(L(`Não achei uma rotina sua com id ${replaces}.`, `I couldn't find a routine of yours with id ${replaces}.`))
- if (!prev && this.forAgent(agent.id).length >= MAX_AGENT_ROUTINES) return fail(L(`Você já tem ${MAX_AGENT_ROUTINES} rotinas ligadas. Cancele uma antes.`, `You already have ${MAX_AGENT_ROUTINES} routines on. Cancel one first.`))
+ const max = routineCap(agent.maxRoutines)
+ if (!prev && this.forAgent(agent.id).length >= max) return fail(L(`Você já tem ${max} rotinas ligadas. Cancele uma antes.`, `You already have ${max} routines on. Cancel one first.`))
const keys = Array.isArray(args['dias']) ? (args['dias'] as unknown[]).map((d) => {
const k = String(d).toLowerCase().normalize('NFD').replace(/[^a-z]/g, '').slice(0, 3)
diff --git a/src/core/team.ts b/src/core/team.ts
index 294c3df..8a2789d 100644
--- a/src/core/team.ts
+++ b/src/core/team.ts
@@ -6,7 +6,7 @@ import { existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
import { randomUUID } from 'node:crypto'
import { join } from 'node:path'
import { L, locale } from '../shared/lang'
-import { describeSchedule, modelInfo, type Agent, type AgentColor, type Effort, type GrantLevel, type Routine, type Schedule, type Trigger } from '../shared/types'
+import { describeSchedule, MAX_AGENT_ROUTINES, modelInfo, type Agent, type AgentColor, type Effort, type GrantLevel, type Routine, type Schedule, type Trigger } from '../shared/types'
import type { Db } from './db'
const FENCE = 'tucano-team'
@@ -133,6 +133,7 @@ export function importTeam(db: Db, text: string, defaultLimit: number): string {
instructions: a.instructions ?? '',
modelId: modelInfo(a.model)?.id ? a.model : 'sonnet',
effort: a.effort ?? 'medium',
+ maxRoutines: MAX_AGENT_ROUTINES,
limit: a.limit || defaultLimit,
used: 0,
grants: Object.fromEntries(Object.entries(a.grants ?? {}).flatMap(([name, g]) => (connectorId(name) ? [[connectorId(name)!, g]] : (added.skipped.push(L(`acesso de @${a.handle} ao ${name}`, `@${a.handle}'s access to ${name}`)), [])))),
diff --git a/src/core/tuca.ts b/src/core/tuca.ts
index 60e1f7c..3836241 100644
--- a/src/core/tuca.ts
+++ b/src/core/tuca.ts
@@ -4,7 +4,7 @@
// person creates it. He has no connectors, no web and no computer of his own.
import { randomUUID } from 'node:crypto'
import { L } from '../shared/lang'
-import { codexValue, ENGINES, MODELS, modelInfo, type Agent, type AgentColor, type AgentDraft, type Connector, type Effort, type GrantLevel, type Settings } from '../shared/types'
+import { codexValue, ENGINES, MAX_AGENT_ROUTINES, MODELS, routineCap, modelInfo, type Agent, type AgentColor, type AgentDraft, type Connector, type Effort, type GrantLevel, type Settings } from '../shared/types'
import type { ToolDef } from './gateway'
const COLORS: AgentColor[] = ['sky', 'indigo', 'violet', 'rose', 'amber', 'green', 'teal', 'graphite']
@@ -159,6 +159,7 @@ export function agentFromDraft(d: AgentDraft, taken: string[], limit: number): A
instructions: d.instructions,
modelId: d.modelId,
effort: d.effort,
+ maxRoutines: routineCap(d.maxRoutines),
limit,
used: 0,
grants: d.grants,
@@ -179,6 +180,7 @@ export function tucaAgent(modelId: string, taken: string[], limit: number): Agen
instructions: tucaInstructions(),
modelId,
effort: 'medium',
+ maxRoutines: MAX_AGENT_ROUTINES,
limit,
used: 0,
grants: {},
diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsx
index a3fa0fe..8cada23 100644
--- a/src/renderer/src/components/Pages.tsx
+++ b/src/renderer/src/components/Pages.tsx
@@ -36,7 +36,9 @@ import {
useStore,
EFFORTS,
ENGINES,
+ MAX_AGENT_ROUTINES,
RUN_BUDGET_PCT,
+ routineCap,
RUN_STALL_MINUTES,
archiveAgent,
setTab,
@@ -557,6 +559,15 @@ export function AgentPage({ id, draft: proposed, fromMessage }: { id?: string; d
className="input--short"
/>
</Field>
+ <Field label={L('Máx. rotinas ligadas', 'Max. enabled routines')} hint={L('Quantas rotinas o agente pode ter ligadas ao mesmo tempo.', 'How many routines the agent can have enabled at the same time.')}>
+ <NumberInput
+ min={1}
+ step={1}
+ value={draft.maxRoutines ?? MAX_AGENT_ROUTINES}
+ onChange={(n) => patch({ maxRoutines: routineCap(n) })}
+ className="input--short"
+ />
+ </Field>
</div>
</Card>
)}
diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.ts
index 7a7867f..715d30f 100644
--- a/src/renderer/src/store.ts
+++ b/src/renderer/src/store.ts
@@ -6,6 +6,7 @@ import type { CoreEvent } from '../../shared/rpc'
import {
type Account,
type AccountEngine,
+ MAX_AGENT_ROUTINES,
MODELS,
modelInfo,
type EngineId,
@@ -356,6 +357,7 @@ export function newAgentDraft(): Agent {
modelId: 'sonnet',
effort: 'medium',
limit: state.settings.defaultLimit,
+ maxRoutines: MAX_AGENT_ROUTINES,
used: 0,
grants: {},
memory: 'auto',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 6ee8b1f..0e4e90c 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -66,6 +66,7 @@ export interface Agent {
accountId?: string // one of settings.accounts, for its harness; unset: the harness's own login
effort: Effort
limit: number // tokens per month
+ maxRoutines?: number // routines on at once; unset: MAX_AGENT_ROUTINES
used: number // tokens used this month, computed from receipts
grants: Record<string, GrantLevel>
memory: MemoryMode
@@ -170,6 +171,7 @@ export interface AgentDraft {
instructions: string
modelId: string
effort: Effort
+ maxRoutines?: number // routines on at once; unset: MAX_AGENT_ROUTINES
web: boolean
grants: Record<string, GrantLevel> // connector id → level; least access by default
task?: string // a first task to try it with
@@ -311,6 +313,12 @@ export interface TelegramInfo {
// Guards per reply (spec §3), so nothing runs away unattended (a routine at 3 a.m.)
// without cutting long work that is going somewhere.
+// Routines an agent can have on at once, so it can't schedule itself without end. Each agent can
+// change it on its page (no upper bound: the monthly limit still holds); this is the default.
+export const MAX_AGENT_ROUTINES = 10
+// A whole number, at least 1: what the core enforces, whatever reached it.
+export const routineCap = (n: number | undefined): number => (Number.isFinite(n) ? Math.max(1, Math.round(n as number)) : MAX_AGENT_ROUTINES)
+
export const RUN_BUDGET_PCT = 10 // past this share of the month, the reply pauses and asks to continue
export const RUN_STALL_MINUTES = 20 // no text, no tokens, no tool finishing: stuck
export const REPEAT_WARN = 3 // the same call with the same result: the agent is told to change course
diff --git a/test/routines.test.ts b/test/routines.test.ts
index e7989f7..15e7cad 100644
--- a/test/routines.test.ts
+++ b/test/routines.test.ts
@@ -3,7 +3,7 @@ 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 Message, type Routine, type Settings } from '../src/shared/types'
+import { describeSchedule, nextRun, routineCap, 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'
@@ -238,6 +238,33 @@ describe('routines', () => {
expect(routines.cancel(lia, mine.routine!.id).reply).toContain('apagada')
expect(db.routines()).toHaveLength(MAX_AGENT_ROUTINES - 1)
})
+
+ it("follows the agent's own limit, kept as a whole number of at least 1", () => {
+ const dm = db.conversation('d1')!
+ const ask = { nome: 'x', pedido: 'y', horario: '9:00' }
+ db.saveAgent({ ...db.agent('a1')!, maxRoutines: 2 })
+ const lia = db.agent('a1')!
+ expect(lia.maxRoutines).toBe(2) // survives a save and a load
+ const first = routines.schedule(lia, dm, ask)
+ routines.schedule(lia, dm, ask)
+ expect(routines.schedule(lia, dm, ask)).toMatchObject({ error: true, reply: expect.stringContaining('2 rotinas') as string })
+ expect(routines.schedule(lia, dm, { ...ask, horario: '10:00', substitui: first.routine!.id }).error).toBeFalsy() // replacing at the cap
+ expect(db.routines()).toHaveLength(2)
+
+ // Above the old fixed 10, with no upper bound.
+ db.saveAgent({ ...db.agent('a1')!, maxRoutines: 15 })
+ const busy = db.agent('a1')!
+ for (let i = 2; i < 15; i++) expect(routines.schedule(busy, dm, ask).error).toBeFalsy()
+ expect(routines.schedule(busy, dm, ask).error).toBe(true)
+
+ // Whatever reaches the core, the limit is a whole number, at least 1.
+ for (const [given, kept] of [[-3, 1], [0, 1], [2.7, 3], [Number.NaN, MAX_AGENT_ROUTINES]] as const) {
+ db.saveAgent({ ...db.agent('a1')!, maxRoutines: given })
+ expect(db.agent('a1')!.maxRoutines).toBe(kept)
+ }
+ expect(routines.schedule({ ...busy, maxRoutines: -3 }, db.conversation('d1')!, ask).reply).not.toContain('-3')
+ expect(routineCap(undefined)).toBe(MAX_AGENT_ROUTINES) // agents from before keep 10
+ })
})
describe('quiet hours', () => {