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.

Let each agent go as far on its own as I choose (#190)

Eduardo Machado2d790f14a997
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 33b11d1..a33c16c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
- **An agent's profile card, from its face or name.** A click on an agent's face or name (on its message, in a thread, an `@mention`, the faces at the top of a channel, the top of its DM) opens a small card next to it, as Slack does; resting the mouse there for half a second opens it too, and it goes when the mouse leaves. The card shows its picture, name, `@handle` and role; what it's doing now (working, and on which step, with a link to the conversation; waiting for an answer or an approval, and whose, when there's a team; at its monthly limit; archived; or when it last spoke); its model and harness; its computer; the channels it's in; and buttons to message it or open its full page. The faces at the top of a channel and the name at the top of a DM open the card instead of the agent's page, and the DM's **See profile** button is now a gear for the conversation's settings. People's faces stay as they were. Esc gives the focus back to what opened it. Thanks [@rjgdias](https://github.com/rjgdias)! ([#134](https://github.com/eduwxyz/tucano/pull/134))
- **An agent's decisions, answered one at a time with options to pick.** `ask_user` took a single string, so agents packed their findings, a proposal and several questions into one unformatted card. Now an agent asks for 1 to 4 decisions, each a single choice, a multiple choice or a short text, and writes its analysis in the reply, which renders as usual; a question over 200 characters goes back to the agent asking for the context in the reply. The decisions come as a card under the agent's reply, one at a time (with arrows and "1 of 2"): the agent suggests 1 to 3 options and the card always adds "Something else", which opens a field for your own answer. Pick with a click or the option's number, Enter confirms, "Skip" moves on, and with more than one decision there's a review before sending, where any answer can still change. The answer goes as your message, one line per decision. The message box below stays as it was: writing there answers too, and what you already picked on the card goes along. Once answered, the card keeps each decision with what was chosen, and the sidebar marks a channel or DM where an agent waits on you, with who in its tooltip. With a team, a question to someone carries its decisions too: the asked person (or whoever covers for them) answers them on the card, in the conversation or in **For you**; an admin can answer for them; everyone else sees what was asked and, afterwards, who answered. A question from a DM still waits for the DM's person's yes first, and the sidebar marks only what waits on you. Older pending questions still work, and Telegram gets the decisions as numbered text, answered by replying. Thanks [@cleitoncsalvagni](https://github.com/cleitoncsalvagni)! ([#145](https://github.com/eduwxyz/tucano/pull/145))
+- **How far each agent goes on its own.** **Settings › Agents › Autonomy** sets a level for every agent, and each agent's page (Tools) can set its own: **Careful** asks before anything that changes something (a write in a connector, a commit, a push, a risky click); **Normal** is how Tucano always worked, reading and writing on its own and asking before what's sensitive; **No guardrails** sends, deletes, publishes, pays and clicks without asking, after a confirmation. Under **Fine-tune action by action**, each kind (commit, push, pull request, merge, delete, send, publish, pay, a risky click in the agent's browser, a risky action in an app) can ask first, run alone or never happen, over the level; an agent's own rule wins over its level, which wins over Settings. A tool you marked high risk always asks, and a step that ran without asking says so ("Ran (no ask: autonomy)"). Commands on the agent's computer are read before they run, every command on the line (from #110, by @rjgdias): a commit, a push or an `rm -r` that a rule holds becomes an approval with the exact command, and approved, exactly that runs.
+- **A guard against text that tells the agent what to do.** An email, a page or an issue can carry instructions someone else wrote. After an agent reads something from outside in a reply (a connector's answer, a page, an app, the web, a trigger's event), sending, publishing, paying, deleting and risky clicks ask first, even where a rule or the level lets them run, and the card says why. It's on by default, in Settings and on each agent's page; an agent's next replies in the same conversation keep it, since its session still holds what it read.
## [0.2.17] - 2026-11-07
diff --git a/src/core/db.ts b/src/core/db.ts
index 6520556..e920206 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -1,4 +1,5 @@
import { DatabaseSync, type StatementSync } from 'node:sqlite'
+import { cleanRules, isAutonomy } from '../shared/actions'
import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, renameSync, rmSync } from 'node:fs'
import { ALL_PARTS, GENERAL_SETTINGS, WORKSPACE_PARTS, type WorkspaceParts } from '../shared/workspaces'
@@ -490,6 +491,17 @@ export const MIGRATIONS = [
`
]
+// Columns checked by name on every start, after MIGRATIONS ([table, column, type]): one a build of
+// another branch already added (approvals by rule did) is left as it is instead of failing the start.
+// How far each agent goes on its own: a rule per kind of action, its level, the outside-content guard
+// (src/shared/actions.ts). Empty: Settings decide, which out of the box is how Tucano always worked.
+const COLUMNS: [string, string, string][] = [
+ ['agents', 'action_rules', "TEXT NOT NULL DEFAULT '{}'"],
+ ['agents', 'autonomy', 'TEXT'],
+ ['agents', 'outside_guard', 'INTEGER']
+]
+
+
type Row = Record<string, unknown>
// countedTokens, in SQL: cache reads count CACHE_READ_WEIGHT.
@@ -638,6 +650,10 @@ export class Db {
this.db.exec(`PRAGMA user_version = ${v + 1}`)
})
}
+ for (const [table, column, type] of COLUMNS) {
+ const has = (this.db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column)
+ if (!has) this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`)
+ }
}
// Nested calls join the outer transaction.
@@ -710,6 +726,9 @@ export class Db {
...(r['avatar'] ? { avatar: JSON.parse(str(r['avatar'])) as Agent['avatar'] } : {}),
...(r['wiki'] === 'none' || r['wiki'] === 'read' ? { wiki: r['wiki'] } : {}),
autoApprove: JSON.parse(str(r['auto_approve']) || '[]') as string[],
+ ...(str(r['action_rules']) && str(r['action_rules']) !== '{}' ? { actionRules: cleanRules(JSON.parse(str(r['action_rules']))) } : {}),
+ ...(isAutonomy(r['autonomy']) ? { autonomy: r['autonomy'] } : {}),
+ ...(r['outside_guard'] === 0 || r['outside_guard'] === 1 ? { outsideGuard: r['outside_guard'] === 1 } : {}),
folders: JSON.parse(str(r['folders']) || '[]') as LentFolder[],
archived: r['archived'] === 1,
...(str(r['kind']) === 'tuca' ? { kind: 'tuca' as const } : {}),
@@ -730,14 +749,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, max_routines, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, custom_color, picture, avatar, wiki, 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, action_rules, autonomy, outside_guard, archived, kind, custom_color, picture, avatar, wiki, 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, 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), custom_color = excluded.custom_color, picture = excluded.picture, avatar = excluded.avatar, wiki = excluded.wiki`
+ computer = excluded.computer, computer_kind = excluded.computer_kind, web = excluded.web, browser = excluded.browser, apps = excluded.apps, auto_approve = excluded.auto_approve, action_rules = excluded.action_rules, autonomy = excluded.autonomy, outside_guard = excluded.outside_guard, archived = excluded.archived, kind = COALESCE(excluded.kind, agents.kind), custom_color = excluded.custom_color, picture = excluded.picture, avatar = excluded.avatar, wiki = excluded.wiki`
)
- .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, a.customColor ?? null, a.picture ?? null, a.avatar ? JSON.stringify(a.avatar) : null, a.wiki ?? 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 ?? []), JSON.stringify(cleanRules(a.actionRules)), isAutonomy(a.autonomy) ? a.autonomy : null, a.outsideGuard === undefined ? null : a.outsideGuard ? 1 : 0, a.archived ? 1 : 0, a.kind ?? null, a.customColor ?? null, a.picture ?? null, a.avatar ? JSON.stringify(a.avatar) : null, a.wiki ?? null, Date.now())
// An agent made without one belongs to the Tucano's owner; a save that doesn't say keeps it.
this.db.prepare('UPDATE agents SET owner = COALESCE(?, owner, (SELECT id FROM people WHERE role = ?)) WHERE id = ?').run(a.owner ?? null, 'owner', a.id)
}
diff --git a/src/core/index.ts b/src/core/index.ts
index 09ee12d..5e0351b 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -18,6 +18,7 @@ import { limitError, paramsError } from '../shared/rpc-shapes'
import { ACCOUNT_ENGINES, channelName, ENGINES, inQuietHours, modelInfo, personScope, rememberModels, scopePerson, usable, WEBHOOK_PORT, type Account, type AccountEngine, type Agent, type BrowserReply, type Message, type EngineId, type EngineStatus, type Person, type Routine, type Settings, type WikiChange, type WikiSource } from '../shared/types'
import { agentOwner, channelEditError, cleanName, dmOwner, Hub, MAX_NAME, mayEditChannel, nameLongError, nameTakenError, People, routineDetail, stripInvisible, type Purged } from './people'
import { admit, admitComputer, can, isAdmin, must } from './policy-people'
+import { cleanRules, isAutonomy } from '../shared/actions'
import { listModels, quietClaude, quietCodex, withChoice } from './harness'
import { cleanLook } from './agent-look'
import { Db } from './db'
@@ -1126,6 +1127,10 @@ const api: Handlers = {
// One handle per agent (archived ones keep theirs), and none that reads as a person's (People.agentNameError).
const taken = people.agentNameError({ id: clean.id, name: clean.name, handle: clean.handle })
if (taken) throw new Error(taken)
+ // How far it goes on its own: only known rules and levels (saving an agent is an admin's, policy-people.ts).
+ clean.actionRules = cleanRules(clean.actionRules)
+ if (!isAutonomy(clean.autonomy)) delete clean.autonomy
+ if (typeof clean.outsideGuard !== 'boolean') delete clean.outsideGuard
const linux = (a?: Agent): boolean => !!a?.computer && a.computerKind !== 'mac'
const mac = (a?: Agent): boolean => !!a?.computer && a.computerKind === 'mac'
db.saveAgent(clean)
@@ -1462,6 +1467,7 @@ const api: Handlers = {
if (Object.keys(patch).length === 0) return void emit({ type: 'settings', settings: settings() })
const why = voiceRefusal(patch.voice)
if (why) throw new Error(why)
+ if (patch.actionRules) patch.actionRules = cleanRules(patch.actionRules)
db.setSettings(patch)
// The settings' name is the owner's: what the agents call them.
if (patch.workspaceName && cleanName(patch.workspaceName)) {
diff --git a/src/core/runs.ts b/src/core/runs.ts
index 8535812..0ff7780 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -28,9 +28,10 @@ import { formatAnswers, MAX_DESCRIPTION_LENGTH, MAX_LABEL_LENGTH, MAX_OPTIONS, M
import { JEV_MODEL, routeJev } from './jev'
import { ROUTER_HISTORY, route, routerTurn, screenHandoff } from './router'
import { allowed, approvalHash, callClass, canonical, permits, runnerAllowed, runnerRules } from './policy'
-import { perCallTool } from '../shared/composio'
+import { innerActions, perCallTool } from '../shared/composio'
import { agentOwner, deciders, dmOwner, mentionedPeople, People, personNamed, presentPeople, promptPeople, requesterOf, routineBehalf, toPeopleOnly } from './people'
import { can } from './policy-people'
+import { kindLabel, actionMode, actionVerb, COMPUTADOR, gate, policyOf, shellActions, toolActions, verdict, type ActionKind, type Policy, type Verdict } from '../shared/actions'
import { awaitDone, idleSleepSeconds, isStatusTool, pendingOf, pollTool } from './waits'
import { callError, contentText, errorReason } from './connectors'
import { commandStep, execSummary, keyArg, maskSecrets, resultSummary } from './step-text'
@@ -924,6 +925,9 @@ export class Runner {
const routineAsk = opts.routine ? [...history].reverse().find((m) => m.author.kind === 'routine') : undefined
const routineOf = routineAsk?.author.kind === 'routine' ? db.routine(routineAsk.author.id) : undefined
const behalf = routineOf ? routineBehalf(db, routineOf, { workspaceName: ownerName }) : undefined
+ // Something from outside read before what goes out (OUTBOUND in src/shared/actions.ts): a trigger's event, or an
+ // earlier reply of this agent here that read some (a kept session still holds it), or what this reply reads.
+ let outside = !!routineAsk?.routine?.event || history.some((m) => m.author.kind === 'agent' && m.author.id === agent.id && !!m.run?.outside)
// Who scheduled each routine in the transcript: its person (the owner by the workspace's name); the team's, none.
const scheduledBy = (id: string): string | undefined => {
const r = db.routine(id)
@@ -1033,11 +1037,18 @@ export class Runner {
const routineIds: string[] = []
const exposed = new Map<string, Exposed>()
const taken = new Set<string>([ASK_USER.name, ACCESS_REQUEST, LEMBRAR.name, BUSCAR_THREADS.name, LER_THREAD.name, ...COMPUTER_TOOL_NAMES, ...BROWSER_TOOL_NAMES, ...APP_TOOL_NAMES, ...ROUTINE_TOOL_NAMES, ...SKILL_TOOL_NAMES])
+ // How far this agent goes on its own (src/shared/actions.ts): read again at each call, since it may change mid-turn.
+ const kindsOf = (t: Pick<ConnectorTool, 'cls' | 'name'>): ActionKind[] => (t.cls === 'read' ? [] : toolActions(t.name))
+ const policy: Policy = policyOf(agent, settings)
+ const policyNow = async (): Promise<Policy> => policyOf(db.agent(agent.id), await this.deps.settings())
+ // What a connector tool does when the turn starts, for its description (nothing from outside read yet).
+ const judged = (t: ConnectorTool, connectorId: string, outside = false): Verdict =>
+ verdict({ cls: t.cls, kinds: kindsOf(t), p: policy, highRisk: t.highRisk, alwaysAllowed: t.cls === 'sensitive' && !!agent.autoApprove?.includes(`${connectorId}:${t.name}`), outside })
for (const c of this.deps.connectors?.list() ?? []) {
// Dropped for a moment, its tools stay: the next call connects again. An error that needs the person
// (a refused token, a sign-in to finish) takes them away.
if (c.status !== 'connected' && c.status !== 'disconnected' && c.status !== 'connecting') continue
- for (const t of db.tools(c.id)) if (allowed(t, agent.grants[c.id], perCallTool(c.url, t.name))) exposed.set(exposedName(c, t.name, taken), { connector: c, tool: t })
+ for (const t of db.tools(c.id)) if (allowed(t, agent.grants[c.id], perCallTool(c.url, t.name)) && gate(kindsOf(t), policy).mode !== 'off') exposed.set(exposedName(c, t.name, taken), { connector: c, tool: t })
}
// pedir_acesso: the connectors this agent could get more of; I decide, like any approval.
const lacking = (this.deps.connectors?.list() ?? []).filter((c) => agent.grants[c.id] !== 'read_write')
@@ -1060,6 +1071,30 @@ export class Runner {
}
}
: undefined
+ // bash, told which commands wait for me and which never run, so the agent plans around them.
+ const SHELL_KINDS: ActionKind[] = ['commit', 'push', 'pr', 'merge', 'delete', 'publish']
+ const withRules = (t: ToolDef): ToolDef => {
+ const by = (m: 'ask' | 'off'): string => SHELL_KINDS.filter((k) => actionMode(k, policy) === m).map((k) => kindLabel(k).toLowerCase()).join(', ')
+ const asks = by('ask')
+ const never = by('off')
+ if (!asks && !never) return t
+ const note = [
+ asks &&
+ L(
+ `Comandos que fazem isto pedem aprovação de ${settings.workspaceName} antes de rodar: ${asks}. Eles não rodam na hora: viram um pedido com o comando exato; aprovado, o app roda esse comando e você recebe a saída numa nova mensagem. Junte num só comando o que precisa ir junto (ex.: git add -A && git commit -m "…" && git push).`,
+ `Commands that do this ask ${settings.workspaceName} for approval before running: ${asks}. They don't run right away: they become a request with the exact command; once approved, the app runs that command and you get the output in a new message. Put what must go together in one command (e.g. git add -A && git commit -m "…" && git push).`
+ ),
+ never && L(`Nunca rodam pra você: ${never}.`, `Never run for you: ${never}.`)
+ ]
+ .filter(Boolean)
+ .join(' ')
+ return {
+ ...t,
+ description: `${t.description}
+${note}`,
+ inputSchema: { ...t.inputSchema, properties: { ...(t.inputSchema.properties ?? {}), [REASON_PARAM]: { type: 'string', description: L(`Se o comando pede aprovação: por que, em uma frase. Aparece pra ${settings.workspaceName} no pedido.`, `If the command asks for approval: why, in one sentence. ${settings.workspaceName} sees it in the request.`) } } }
+ }
+ }
// The app's own tools stay in the prompt; the connectors' wait behind tool search (ALWAYS_LOAD).
const others = db.people()
const ownTools: ToolDef[] = [
@@ -1070,7 +1105,7 @@ export class Runner {
...(canSeekThreads ? [BUSCAR_THREADS, LER_THREAD] : []),
...(proposes ? [PROPOR_AGENTE, PROPOR_TIME, ...PROPOSAL_TOOLS()] : []),
...(helps ? [LER_GUIA, VER_ESTADO] : []),
- ...(computers ? computerTools(agent) : []),
+ ...(computers ? computerTools(agent).map((t) => (t.name === 'bash' ? withRules(t) : t)) : []),
...(browser ? browserTools() : []),
...(apps ? appTools(agent) : []),
...(routines ? [AGENDAR, CANCELAR] : []),
@@ -1090,7 +1125,18 @@ export class Runner {
...[...exposed].map(([name, { connector, tool }]): ToolDef => {
const schema = tool.inputSchema as ToolDef['inputSchema']
const perCall = perCallTool(connector.url, tool.name)
- if (tool.cls !== 'sensitive' && !perCall) return { name, description: `[${connector.name}] ${tool.description}`, inputSchema: schema }
+ const plain = { name, description: `[${connector.name}] ${tool.description}`, inputSchema: schema }
+ if (!perCall && judged(tool, connector.id).run) {
+ // Runs on its own, unless something from outside was read first: then it asks, and the agent knows.
+ if (judged(tool, connector.id, true).why !== 'guard') return plain
+ return {
+ ...plain,
+ description: `${plain.description}\n${L(
+ `Roda sem pedir, mas se nesta resposta você já leu algo de fora (a resposta de um conector, uma página, a web), vira um pedido de aprovação pra ${settings.workspaceName}, com exatamente estes argumentos.`,
+ `Runs without asking, but if in this reply you've already read something from outside (a connector's answer, a page, the web), it becomes an approval request for ${settings.workspaceName}, with exactly these arguments.`
+ )}`
+ }
+ }
return {
name,
description: `[${connector.name}] ${tool.description}\n${
@@ -1099,10 +1145,15 @@ export class Runner {
`Cada chamada vale pelo que ela roda: só leituras rodam na hora; escritas precisam de acesso de leitura e escrita; ações sensíveis (enviar, apagar, rodar código) e qualquer chamada fora do formato documentado viram um pedido de aprovação pra ${settings.workspaceName}, com exatamente estes argumentos.`,
`Each call counts as what it runs: reads alone run right away; writes need read-and-write access; sensitive actions (send, delete, run code) and any call outside the documented shape become an approval request for ${settings.workspaceName}, with exactly these arguments.`
)
- : L(
- `Ação sensível: não roda na hora. Vira um pedido de aprovação pra ${settings.workspaceName}, com exatamente estes argumentos.`,
- `Sensitive action: it doesn't run right away. It becomes an approval request for ${settings.workspaceName}, with exactly these arguments.`
- )
+ : tool.cls === 'sensitive'
+ ? L(
+ `Ação sensível: não roda na hora. Vira um pedido de aprovação pra ${settings.workspaceName}, com exatamente estes argumentos.`,
+ `Sensitive action: it doesn't run right away. It becomes an approval request for ${settings.workspaceName}, with exactly these arguments.`
+ )
+ : L(
+ `Pede aprovação: não roda na hora. Vira um pedido de aprovação pra ${settings.workspaceName}, com exatamente estes argumentos.`,
+ `Asks first: it doesn't run right away. It becomes an approval request for ${settings.workspaceName}, with exactly these arguments.`
+ )
}`,
inputSchema: {
...schema,
@@ -1120,6 +1171,17 @@ export class Runner {
stepStarted = Date.now()
save()
}
+ // It read something from outside: kept on the reply too, so its next one here knows.
+ const sawOutside = (): void => {
+ outside = true
+ if (!msg.run?.outside) msg.run = { ...msg.run!, outside: true }
+ }
+ const guardNote = (): string => L('Pediu porque leu algo de fora antes, nesta resposta', 'Asked because it read something from outside first, in this reply')
+ // Why something waits for me, for the agent: a rule, the level, or the guard (it read something from outside).
+ const askedBecause = (v: Verdict): string =>
+ v.why === 'guard'
+ ? L(' Pediu porque, nesta resposta, você leu algo de fora antes (um conector, uma página, a web): o que vai pra fora depois disso pede aprovação.', " It asks because in this reply you read something from outside first (a connector, a page, the web): what goes out after that asks first.")
+ : ''
const runTool = async (name: string, args: Record<string, unknown>): Promise<CallToolResult> => {
if (name === ASK_USER.name) {
@@ -1317,6 +1379,57 @@ 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)
+ // A command that commits, pushes, deletes…: by the rules, it runs, waits for me, or never runs.
+ if (name === 'bash' || name === 'start_service') {
+ const command = typeof args['command'] === 'string' ? args['command'] : ''
+ const kinds = shellActions(command)
+ // Only a command that does something that matters is judged; any other runs, as always.
+ const rules: Verdict = kinds.length ? verdict({ cls: 'write', kinds, p: await policyNow(), outside }) : { run: true, why: 'class', kinds: [] }
+ const words = (rules.kinds.length ? rules.kinds : kinds).map((k) => kindLabel(k).toLowerCase()).join(', ')
+ if (rules.off) {
+ addSteps({ id: randomUUID(), label: L('Não rodou', "Didn't run"), detail: L(`${words}: desligado pra este agente`, `${words}: turned off for this agent`), status: 'error' })
+ return textResult(
+ L(
+ `Não rodei: ${words} está desligado pra você (${settings.workspaceName} decide isso em Configurações ou na sua página). Siga sem isso, ou diga a ${settings.workspaceName} o que falta.`,
+ `I didn't run it: ${words} is turned off for you (${settings.workspaceName} decides that in Settings or on your page). Go on without it, or tell ${settings.workspaceName} what's missing.`
+ ),
+ true
+ )
+ }
+ if (!rules.run) {
+ if (name === 'start_service') return textResult(L(`Esse comando faz ${words}, que pede aprovação: rode com bash, não como serviço.`, `That command does ${words}, which asks for approval: run it with bash, not as a service.`), true)
+ if (question || approval) return textResult(L('Já existe um pedido esperando decisão nesta mensagem. Encerre agora.', 'There is already a request waiting for a decision in this message. End now.'), true)
+ const { [REASON_PARAM]: why, ...callArgs } = args
+ approval = {
+ id: randomUUID(),
+ hash: approvalHash(COMPUTADOR, 'bash', callArgs),
+ agentId: agent.id,
+ conversationId: conv.id,
+ messageId: msg.id,
+ connectorId: COMPUTADOR,
+ connectorName: L('Computador', 'Computer'),
+ tool: 'bash',
+ args: callArgs,
+ why: typeof why === 'string' ? why.trim() : '',
+ // Deleting is held to approve, like any high-risk action, and never allowed for good from the card.
+ highRisk: kinds.includes('delete'),
+ state: 'pending',
+ createdAt: Date.now(),
+ expiresAt: Date.now() + settings.approvalTtlHours * 3_600_000
+ }
+ db.createApproval(approval)
+ emit({ type: 'approval', approval })
+ msg.run = { ...msg.run!, approvalId: approval.id }
+ addSteps({ id: randomUUID(), label: L('Pediu aprovação', 'Asked for approval'), detail: `${words} · ${command.length > 120 ? `${command.slice(0, 120)}…` : command}`, ...(rules.why === 'guard' ? { note: guardNote() } : {}), status: 'done' })
+ this.deps.notify?.(L(`${agent.name} quer ${rules.kinds.map(actionVerb).join(' e ')}`, `${agent.name} wants to ${rules.kinds.map(actionVerb).join(' and ')}`), approval.why || command.slice(0, 120), conv.id, 'approval')
+ return textResult(
+ L(
+ `Pedido de aprovação criado, com o comando exato. O comando ainda NÃO rodou. Encerre sua resposta agora dizendo em uma frase o que pediu. Quando ${settings.workspaceName} decidir, você recebe a saída numa nova mensagem.`,
+ `Approval request created, with the exact command. The command has NOT run yet. End your reply now saying in one sentence what you asked for. When ${settings.workspaceName} decides, you get the output in a new message.`
+ ) + askedBecause(rules)
+ )
+ }
+ }
// 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.
@@ -1380,8 +1493,23 @@ export class Runner {
msg.run = { ...msg.run!, browser: true, steps: [...closeThinking('done', THOUGHT()), step] }
save()
const out = await browser.call(current, name, args, { conversationId: conv.id, messageId: msg.id })
+ sawOutside() // a page is someone else's text
if (out.artifact) artifactIds.push(out.artifact.id)
const close = (status: Step['status'], patch: Partial<Step> = {}): Step[] => msg.run!.steps.map((s) => (s.id === step.id ? { ...s, ...patch, status, ms: Date.now() - t0 } : s))
+ // A risky click or key: by how far this agent goes on its own, it waits for me, runs now, or never.
+ const risky = out.approval ? verdict({ cls: 'write', kinds: ['browser'], p: await policyNow(), outside, askByDefault: true }) : undefined
+ if (out.approval && risky?.off) {
+ msg.run = { ...msg.run!, steps: [...close('error', { detail: out.approval.detail }), thinking()] }
+ save()
+ return textResult(L(`Não fiz: cliques arriscados no navegador estão desligados pra você (${settings.workspaceName} decide isso). Siga sem isso, ou diga a ${settings.workspaceName} o que falta.`, `I didn't: risky clicks in the browser are turned off for you (${settings.workspaceName} decides that). Go on without it, or tell ${settings.workspaceName} what's missing.`), true)
+ }
+ if (out.approval && risky?.run) {
+ const done = await browser.approved(current, out.approval.args)
+ msg.run = { ...msg.run!, artifactIds: artifactIds.length ? [...artifactIds] : undefined, steps: [...close(done.ok ? 'done' : 'error', { label: L('Clicou (sem pedir: autonomia)', 'Clicked (no ask: autonomy)'), detail: out.approval.detail }), thinking()] }
+ stepStarted = Date.now()
+ save()
+ return textResult(done.text, !done.ok)
+ }
if (out.approval) {
if (questions || approval) {
msg.run = { ...msg.run!, steps: [...close('error'), thinking()] }
@@ -1444,8 +1572,28 @@ export class Runner {
flush()
msg.run = { ...msg.run!, steps: [...closeThinking('done', THOUGHT()), step] }
save()
- const out = await apps.call(current, name, args)
+ let out = await apps.call(current, name, args)
+ sawOutside() // what an app shows (a mail, a chat) is someone else's text
const close = (status: Step['status'], patch: Partial<Step> = {}): Step[] => msg.run!.steps.map((s) => (s.id === step.id ? { ...s, ...patch, status, ms: Date.now() - t0 } : s))
+ // A click or key that sends, pays or deletes: by how far this agent goes on its own, it waits, runs now, or never.
+ const risky = out.approval ? verdict({ cls: 'write', kinds: ['apps'], p: await policyNow(), outside, askByDefault: true }) : undefined
+ if (out.approval && risky?.off) {
+ msg.run = { ...msg.run!, steps: [...close('error', { detail: out.approval.detail }), thinking()] }
+ save()
+ return textResult(L(`Não fiz: ações arriscadas nos apps estão desligadas pra você (${settings.workspaceName} decide isso). Siga sem isso, ou diga a ${settings.workspaceName} o que falta.`, `I didn't: risky actions in apps are turned off for you (${settings.workspaceName} decides that). Go on without it, or tell ${settings.workspaceName} what's missing.`), true)
+ }
+ if (out.approval && risky?.run) {
+ // The same way an approval lets it through: once, that exact element, then the action again.
+ const detail = out.approval.detail
+ const let_ = await apps.approved(current, out.approval.args)
+ if (let_.ok) out = await apps.call(current, name, args)
+ if (!out.approval) {
+ msg.run = { ...msg.run!, steps: [...close(!let_.ok || out.result.isError ? 'error' : 'done', { label: L('Fez (sem pedir: autonomia)', 'Did it (no ask: autonomy)'), detail }), thinking()] }
+ stepStarted = Date.now()
+ save()
+ return let_.ok ? clip(out.result) : textResult(let_.text, true)
+ }
+ }
if (out.approval) {
if (questions || approval) {
msg.run = { ...msg.run!, steps: [...close('error'), thinking()] }
@@ -1551,7 +1699,14 @@ export class Runner {
// A runner's call, only when every inner tool that would ask is allowed for good on its own.
const rules = db.agent(agent.id)?.autoApprove ?? []
const always = cls === 'sensitive' && !current.highRisk && (perCall ? runnerAllowed(hit.connector.id, current.name, callArgs, rules) : rules.includes(`${hit.connector.id}:${current.name}`))
- if (cls === 'sensitive' && !always) {
+ // A runner's call counts as the actions it runs; one that can't be placed (raw requests, code) asks at every level.
+ const inner = perCall ? innerActions(current.name, callArgs) : undefined
+ const kinds = inner ? inner.flatMap((a) => (a.kind === 'tool' ? toolActions(a.slug) : [])) : kindsOf({ cls, name: current.name })
+ const unplaced = perCall && cls === 'sensitive' && !runnerRules(hit.connector.id, current.name, callArgs)
+ // How far it goes on its own, read now: the rules may have changed since the turn started.
+ const judgedNow = verdict({ cls, kinds, p: await policyNow(), highRisk: current.highRisk || unplaced, alwaysAllowed: always, outside })
+ if (judgedNow.off) return textResult(L(`Não rodei: ${judgedNow.kinds.map((k) => kindLabel(k).toLowerCase()).join(', ')} está desligado pra você agora.`, `I didn't run it: ${judgedNow.kinds.map((k) => kindLabel(k).toLowerCase()).join(', ')} is turned off for you now.`), true)
+ if (!judgedNow.run) {
if (question || approval) return textResult(L('Já existe um pedido esperando decisão nesta mensagem. Encerre agora.', 'There is already a request waiting for a decision in this message. End now.'), true)
approval = {
id: randomUUID(),
@@ -1574,18 +1729,18 @@ export class Runner {
db.createApproval(approval)
emit({ type: 'approval', approval })
msg.run = { ...msg.run!, approvalId: approval.id }
- addSteps({ id: randomUUID(), label: L('Pediu aprovação', 'Asked for approval'), detail, status: 'done' })
+ addSteps({ id: randomUUID(), label: L('Pediu aprovação', 'Asked for approval'), detail, ...(judgedNow.why === 'guard' ? { note: guardNote() } : {}), status: 'done' })
notifyApproval(L(`${agent.name} pede aprovação`, `${agent.name} asks for approval`), `${toolLabel(current.name)} · ${hit.connector.name}${approval.why ? `: ${approval.why}` : ''}`)
return textResult(
L(
`Pedido de aprovação criado. A ação ainda NÃO foi executada. Encerre sua resposta agora dizendo em uma frase o que pediu. Quando ${settings.workspaceName} decidir, você recebe o resultado numa nova mensagem.`,
`Approval request created. The action has NOT run yet. End your reply now saying in one sentence what you asked for. When ${settings.workspaceName} decides, you get the result in a new message.`
- )
+ ) + askedBecause(judgedNow)
)
}
const t0 = Date.now()
- const step: Step = { id: randomUUID(), label: cls === 'read' ? L('Consultou', 'Looked up') : always ? L('Executou (sempre permitido)', 'Ran (always allowed)') : L('Executou', 'Ran'), detail, status: 'running' }
+ const step: Step = { id: randomUUID(), label: cls === 'read' ? L('Consultou', 'Looked up') : judgedNow.why === 'always' ? L('Executou (sempre permitido)', 'Ran (always allowed)') : cls === 'sensitive' || judgedNow.why === 'rule' ? L('Executou (sem pedir: autonomia)', 'Ran (no ask: autonomy)') : L('Executou', 'Ran'), detail, status: 'running' }
// What it asked (the SQL, the path) shows while it runs; what came back, when it's done.
const input = keyArg(callArgs)
if (input) step.input = input
@@ -1603,6 +1758,7 @@ export class Runner {
}
try {
const first = await this.deps.connectors!.call(hit.connector.id, current.name, callArgs)
+ sawOutside() // what a connector answers is someone else's text: an email, an issue, a page
// 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).
@@ -1803,6 +1959,7 @@ export class Runner {
} else if (ev.type === 'web') {
// Not through the gateway, so it can't be refused or warned: the same search over and over is a loop.
acted = true
+ sawOutside() // a search or a page is someone else's text
addSteps({ id: randomUUID(), label: ev.action === 'search' ? L('Pesquisou na web', 'Searched the web') : L('Leu uma página', 'Read a page'), detail: ev.detail, status: 'done' })
if (repeated(`web ${ev.action} ${ev.detail}`, '') >= REPEAT_STOP) halt('loop')
} else if (ev.type === 'done') {
@@ -1875,7 +2032,7 @@ export class Runner {
)
}
- const base = { endedAt, depth: opts.depth, work, receipt, question, questions, ...(question && (askedTo.id !== requester.id || db.people().length > 1) ? { askedTo: askedTo.id } : {}), 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, proposal: msg.run?.proposal, ...(replyTo ? { replyTo } : {}) }
+ const base = { endedAt, depth: opts.depth, work, receipt, question, questions, ...(question && (askedTo.id !== requester.id || db.people().length > 1) ? { askedTo: askedTo.id } : {}), 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, proposal: msg.run?.proposal, ...(outside ? { outside: true } : {}), ...(replyTo ? { replyTo } : {}) }
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' || control.reason === 'sleeping') {
@@ -1967,7 +2124,13 @@ export class Runner {
const runner = perCallTool(this.deps.connectors?.list().find((c) => c.id === ap.connectorId)?.url, ap.tool)
const rules = runner ? (runnerRules(ap.connectorId, ap.tool, ap.args) ?? []) : [`${ap.connectorId}:${ap.tool}`]
const fresh = rules.filter((r) => !owner?.autoApprove?.includes(r))
- if (always && decision === 'approved' && owner && fresh.length && !ap.highRisk && ap.tool !== ACCESS_REQUEST && ap.connectorId !== GITHUB && ap.connectorId !== NAVEGADOR && ap.connectorId !== APPS) {
+ // For a command or a PR, "sempre permitir" turns that kind of action to "does it alone" on the agent's page.
+ const kinds: ActionKind[] = ap.connectorId === COMPUTADOR ? shellActions(String(ap.args['command'] ?? '')) : ap.tool === ABRIR_PR ? ['pr'] : []
+ if (always && decision === 'approved' && owner && !ap.highRisk && kinds.length) {
+ db.saveAgent({ ...owner, actionRules: { ...owner.actionRules, ...Object.fromEntries(kinds.map((k) => [k, 'auto'])) } })
+ emit({ type: 'agent', agent: db.agent(owner.id)! })
+ db.addActivity({ personId: decider, kind: 'approval.always', target: owner.id, detail: { connector: ap.connectorName, tool: kinds.join(', ') } })
+ } else if (always && decision === 'approved' && owner && fresh.length && !ap.highRisk && ap.tool !== ACCESS_REQUEST && ap.connectorId !== GITHUB && ap.connectorId !== NAVEGADOR && ap.connectorId !== APPS && ap.connectorId !== COMPUTADOR) {
db.saveAgent({ ...owner, autoApprove: [...(owner.autoApprove ?? []), ...fresh] })
emit({ type: 'agent', agent: db.agent(owner.id)! })
db.addActivity({ personId: decider, kind: 'approval.always', target: owner.id, detail: { connector: ap.connectorName, tool: fresh.map((r) => r.slice(r.indexOf(':') + 1)).join(', ') } })
@@ -1993,6 +2156,28 @@ export class Runner {
`${me} ${decision === 'approved' ? 'aprovou' : decision === 'refused' ? 'recusou' : 'não respondeu a'} um pedido de PR antigo, mas abrir PR pelo computador saiu do Tucano e nada foi aberto. Se você tem o conector do GitHub, abra a PR por ele; senão, diga a ${me} que ele precisa dar a você o conector do GitHub.`,
`${me} ${decision === 'approved' ? 'approved' : decision === 'refused' ? 'turned down' : "didn't answer"} an old PR request, but opening a PR from the computer left Tucano and nothing was opened. If you have the GitHub connector, open the PR with it; otherwise, tell ${me} you need the GitHub connector.`
)
+ } else if (ap.connectorId === COMPUTADOR) {
+ // A command on the agent's computer: the app runs exactly the one approved, and the agent gets its output.
+ const command = String(ap.args['command'] ?? '')
+ const what = L(`rodar \`${command}\``, `running \`${command}\``)
+ if (decision === 'approved' && agent?.computer && this.deps.computers) {
+ const out = await this.deps.computers.call(agent, 'bash', ap.args, { conversationId: ap.conversationId, messageId: ap.messageId })
+ ok = !out.result.isError
+ outcome = ok ? ran : L('Rodou, com erro.', 'Ran, with an error.')
+ task = L(
+ `${me} aprovou ${what}. O app rodou exatamente esse comando${ok ? '' : ' e ele terminou com erro'}. Saída:\n${resultText(out.result)}\n\nContinue a partir daqui e conte o resultado a ${me}.`,
+ `${me} approved ${what}. The app ran exactly that command${ok ? '' : ' and it ended with an error'}. Output:\n${resultText(out.result)}\n\nGo on from here and tell ${me} the result.`
+ )
+ } else if (decision === 'approved') {
+ outcome = L('Não executou: o computador desse agente está desligado.', "Didn't run: this agent's computer is off.")
+ task = L(`${me} aprovou ${what}, mas o seu computador está desligado agora. Avise ${me} em uma frase.`, `${me} approved ${what}, but your computer is off right now. Tell ${me} in one sentence.`)
+ } else {
+ outcome = decision === 'refused' ? L('Nada foi rodado.', 'Nothing was run.') : expired
+ task = L(
+ `${me} ${decision === 'refused' ? `recusou ${what}${reason ? `: "${reason}"` : ''}` : `não respondeu ao pedido pra ${what}`}. Nada foi rodado. Responda considerando isso; se fizer sentido, proponha outro caminho.`,
+ `${me} ${decision === 'refused' ? `turned down ${what}${reason ? `: "${reason}"` : ''}` : `didn't answer the request for ${what}`}. Nothing was run. Reply with that in mind; if it makes sense, suggest another way.`
+ )
+ }
} else if (ap.connectorId === APPS) {
// A click or key in one of the person's apps: made on the same app, on the same element.
const onde = typeof ap.args['onde'] === 'string' ? ap.args['onde'] : ''
diff --git a/src/core/settings-patch.ts b/src/core/settings-patch.ts
index 8d7af18..7bd4b2d 100644
--- a/src/core/settings-patch.ts
+++ b/src/core/settings-patch.ts
@@ -28,6 +28,9 @@ const RULES: Partial<Record<keyof Settings, { kind: Kind; max: number; nullable?
runBudgetPct: { kind: 'number', max: 30, nullable: true },
runStallMinutes: { kind: 'number', max: 30, nullable: true },
chainDepth: { kind: 'number', max: 30, nullable: true },
+ actionRules: { kind: 'object', max: 2_000, nullable: true },
+ autonomy: { kind: ['careful', 'normal', 'free'], max: 20, nullable: true },
+ outsideGuard: { kind: 'boolean', max: 10, 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/Conversation.tsx b/src/renderer/src/components/Conversation.tsx
index f0515a2..8f4095b 100644
--- a/src/renderer/src/components/Conversation.tsx
+++ b/src/renderer/src/components/Conversation.tsx
@@ -1,6 +1,7 @@
import { L, lang, locale } from '../../../shared/lang'
import { actionLabel, innerActions, isRunner } from '../../../shared/composio'
import { runnerRules } from '../../../shared/classify'
+import { kindLabel, actionVerb, COMPUTADOR, shellActions } from '../../../shared/actions'
import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react'
import Markdown, { type ExtraProps } from 'react-markdown'
import { safeUrl } from '../links'
@@ -1315,6 +1316,14 @@ export function ApprovalCard({ approval, compact }: { approval: Approval; compac
}
const decided = approval.state !== 'pending'
+ // A command on the agent's computer: what it does, in words, and the command itself.
+ const onComputer = approval.connectorId === COMPUTADOR
+ const kinds = onComputer ? shellActions(String(approval.args['command'] ?? '')) : []
+ // "Sempre permitir": a connector tool for good, or, for a command or a PR, that kind of action on the agent's page.
+ const canAlways = approval.tool !== ACCESS_REQUEST && approval.tool !== 'abrir_pr' && approval.connectorId !== 'navegador' && approval.connectorId !== 'apps' && !runner && (!onComputer || kinds.length > 0)
+ const alwaysTitle = onComputer
+ ? L(`Daqui pra frente ${agent?.name ?? 'o agente'} faz sozinho: ${kinds.map((k) => kindLabel(k).toLowerCase()).join(', ')}. Dá pra mudar na página dele.`, `From now on ${agent?.name ?? 'the agent'} does it alone: ${kinds.map((k) => kindLabel(k).toLowerCase()).join(', ')}. You can change it on its page.`)
+ : L(`Daqui pra frente ${agent?.name ?? 'o agente'} usa “${toolWords(approval.tool)}” no ${approval.connectorName} sem pedir. Dá pra tirar na página dele.`, `From now on ${agent?.name ?? 'the agent'} uses “${toolWords(approval.tool)}” in ${approval.connectorName} without asking. You can take it back on its page.`)
return (
<div className={`approval approval--${approval.state} ${compact ? 'approval--compact' : ''}`}>
@@ -1330,6 +1339,10 @@ export function ApprovalCard({ approval, compact }: { approval: Approval; compac
<>
{agent?.name ?? L('Agente', 'Agent')} {L('pede acesso ao', 'asks for access to')} <strong>{approval.connectorName}</strong>: {approval.args['nivel'] === 'read_write' ? L('ler e escrever', 'read and write') : L('ler', 'read')}
</>
+ ) : onComputer ? (
+ <>
+ {agent?.name ?? L('Agente', 'Agent')} {L('quer', 'wants to')} <strong>{kinds.length ? kinds.map(actionVerb).join(L(' e ', ' and ')) : L('rodar um comando', 'run a command')}</strong> {L('no computador dele', 'on its computer')}
+ </>
) : approval.tool === 'abrir_pr' ? (
<>
{agent?.name ?? L('Agente', 'Agent')} {L('quer abrir uma', 'wants to open a')} <strong>pull request</strong> {L('em', 'in')} {String(approval.args['repo'])}
@@ -1381,7 +1394,8 @@ export function ApprovalCard({ approval, compact }: { approval: Approval; compac
{approval.why && <p className="approval__why">{approval.why}</p>}
{team && <ApprovalRoute approval={approval} agent={agent} requester={requester} decider={decider} you={you} />}
{/* The title already says it all for an access request, an app or the browser. */}
- {approval.tool !== ACCESS_REQUEST && approval.connectorId !== 'apps' && approval.connectorId !== 'navegador' && !runner && summary.shown.length > 0 && (
+ {onComputer && <pre className="approval__command">{String(approval.args['command'] ?? '')}</pre>}
+ {approval.tool !== ACCESS_REQUEST && approval.connectorId !== 'apps' && approval.connectorId !== 'navegador' && !runner && !onComputer && summary.shown.length > 0 && (
<div className="approval__args small">
{summary.shown.map(([k, v], i) => (
<p key={i}>
@@ -1462,8 +1476,8 @@ export function ApprovalCard({ approval, compact }: { approval: Approval; compac
<button className="btn btn--primary" onClick={() => decideApproval(approval.id, 'approved')}>
{L('Aprovar', 'Approve')}
</button>
- {approval.tool !== ACCESS_REQUEST && approval.tool !== 'abrir_pr' && approval.connectorId !== 'navegador' && approval.connectorId !== 'apps' && !runner && (
- <button className="btn" title={L(`Daqui pra frente ${agent?.name ?? 'o agente'} usa “${toolWords(approval.tool)}” no ${approval.connectorName} sem pedir. Dá pra tirar na página dele.`, `From now on ${agent?.name ?? 'the agent'} uses “${toolWords(approval.tool)}” in ${approval.connectorName} without asking. You can take it back on its page.`)} onClick={() => decideApproval(approval.id, 'approved', undefined, true)}>
+ {canAlways && (
+ <button className="btn" title={alwaysTitle} onClick={() => decideApproval(approval.id, 'approved', undefined, true)}>
{L('Aprovar e sempre permitir', 'Approve and always allow')}
</button>
)}
diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsx
index b342e63..39def34 100644
--- a/src/renderer/src/components/Pages.tsx
+++ b/src/renderer/src/components/Pages.tsx
@@ -71,6 +71,7 @@ import {
} from '../store'
import { ActivityPane, AdminOnly, PeoplePane } from './People'
import { voiceRefusal } from '../../../shared/voice'
+import { ACTION_KINDS, actionHint, actionMode, AUTONOMY_LEVELS, autonomyHint, autonomyLabel, COMPUTADOR, kindLabel, modeLabel, shellActions, type ActionKind, type ActionMode, type ActionRules, type Autonomy, type Policy } from '../../../shared/actions'
import { useVoice, VOICE_CHOICES, VoiceSetup } from './VoiceSetup'
import { AccountPicker, AccountsCard, HarnessList, HarnessMcps, ModelPicker, onGateway, OutsideGateway, usableEngines } from './Harness'
import { AppsCard } from './Apps'
@@ -252,6 +253,9 @@ export function AgentPage({ id, draft: proposed, fromMessage }: { id?: string; d
const channels = useStore((s) => s.conversations.filter((c) => c.kind === 'channel'))
const handles = useStore((s) => s.agents.map((a) => [a.id, a.handle] as const))
const notes = useStore((s) => (id ? s.memories.filter((m) => m.scope === id && m.state === 'active').length : 0))
+ const globalRules = useStore((s) => s.settings.actionRules)
+ const globalAutonomy = useStore((s) => s.settings.autonomy)
+ const globalGuard = useStore((s) => s.settings.outsideGuard)
const [draft, setDraft] = useState<Agent>(() => existing ?? proposed ?? newAgentDraft())
const [chosen, setChosen] = useState<string[]>(() => (id ? channels.filter((c) => c.members.includes(id)).map((c) => c.id) : []))
@@ -534,6 +538,24 @@ export function AgentPage({ id, draft: proposed, fromMessage }: { id?: string; d
</Card>
)}
+ {pane('ferramentas') && (
+ <Card
+ title={L('Autonomia', 'Autonomy')}
+ lead={`${L(
+ `Até onde ${draft.name || 'o agente'} vai sozinho e o que pede sua aprovação antes, com um botão na conversa. Ler e investigar nunca pede.`,
+ `How far ${draft.name || 'the agent'} goes on its own and what asks for your approval first, with a button in the conversation. Reading and looking into things never asks.`
+ )}${isNew || !admin ? '' : L(' Muda na hora, sem precisar salvar.', ' Takes effect right away, no need to save.')}`}
+ >
+ <AutonomyControls
+ own={{ autonomy: draft.autonomy, actionRules: draft.actionRules, outsideGuard: draft.outsideGuard }}
+ inherited={{ autonomy: globalAutonomy, actionRules: globalRules, outsideGuard: globalGuard }}
+ perAgent
+ readOnly={!admin}
+ onChange={(p) => (isNew ? patch(p) : (setDraft((d) => ({ ...d, ...p })), patchAgent(draft.id, p)))}
+ />
+ </Card>
+ )}
+
{pane('ferramentas') && (
<Card title="Web" lead={`${L('Pesquisa e lê páginas com a ferramenta do próprio Claude Code ou Codex, na sua assinatura. Cada busca aparece nos passos da resposta.', 'Searches and reads pages with Claude Code’s or Codex’s own tool, on your subscription. Every search shows up in the reply’s steps.')}${isNew || !admin ? '' : L(' Muda na hora, sem precisar salvar.', ' Takes effect right away, no need to save.')}`}>
<div className="segmented segmented--wide" role="radiogroup" aria-label="Web">
@@ -1014,6 +1036,111 @@ function LentFolders({ agentId }: { agentId: string }): ReactNode {
)
}
+// How far an agent goes on its own (in Settings, every agent): a level, the outside-content guard, and a rule
+// per kind of action for whoever wants it finer. On an agent's page, `inherited` is Settings and "Padrão"
+// follows them. `readOnly`: someone who only looks at the agent.
+type Autonomous = { autonomy?: Autonomy; actionRules?: ActionRules; outsideGuard?: boolean }
+
+function AutonomyControls({ own, inherited, perAgent, readOnly, onChange }: { own: Autonomous; inherited?: Autonomous; perAgent?: boolean; readOnly?: boolean; onChange: (patch: Autonomous) => void }): ReactNode {
+ const level = own.autonomy
+ const effective: Autonomy = level ?? inherited?.autonomy ?? 'normal'
+ const guard = own.outsideGuard ?? inherited?.outsideGuard ?? true
+ const pick = async (next: Autonomy | undefined): Promise<void> => {
+ if ((next ?? inherited?.autonomy) === 'free' && effective !== 'free') {
+ const ok = await confirmDialog({
+ title: L('Deixar agir sem travas?', 'Let it act with no guardrails?'),
+ body: L(
+ 'Envia, apaga, publica, paga e clica sem te perguntar. Continua pedindo o que você marcou como alto risco e, com a proteção ligada, o que vai pra fora depois de ler algo de fora. Tudo fica nos passos de cada resposta.',
+ 'It sends, deletes, publishes, pays and clicks without asking you. It still asks for what you marked high risk and, with the guard on, for what goes out after reading something from outside. Everything stays in each reply’s steps.'
+ ),
+ confirm: L('Sem travas', 'No guardrails'),
+ danger: true
+ })
+ if (!ok) return
+ }
+ onChange({ autonomy: next })
+ }
+ const options: (Autonomy | 'default')[] = perAgent ? ['default', ...AUTONOMY_LEVELS] : [...AUTONOMY_LEVELS]
+ const value = perAgent ? (level ?? 'default') : effective
+ // What a kind does when its own row says nothing: the level (the agent's or Settings'), then Settings' rule.
+ const base: Policy = perAgent ? { agentLevel: level, globalRules: inherited?.actionRules, globalLevel: inherited?.autonomy } : { globalLevel: own.autonomy }
+ return (
+ <div className="autonomy">
+ <div className="segmented segmented--wide" role="radiogroup" aria-label={L('Autonomia', 'Autonomy')}>
+ {options.map((o) => (
+ <button key={o} role="radio" aria-checked={value === o} className={value === o ? 'is-active' : ''} disabled={readOnly} onClick={() => value !== o && void pick(o === 'default' ? undefined : o)}>
+ {o === 'default' ? L('Padrão', 'Default') : autonomyLabel(o)}
+ </button>
+ ))}
+ </div>
+ <p className="muted small">
+ {autonomyHint(effective)}
+ {effective === 'free' && guard ? ` ${L('Com a proteção abaixo ligada, o que não tem volta depois de ler algo de fora também pede.', 'With the guard below on, what can’t be undone after reading something from outside asks too.')}` : ''}
+ {perAgent && !level ? ` ${L(`“Padrão” segue Configurações › Agentes: ${autonomyLabel(effective).toLowerCase()}.`, `“Default” follows Settings › Agents: ${autonomyLabel(effective).toLowerCase()}.`)}` : ''}
+ </p>
+ <div className="key-row">
+ <Icon name="shield" />
+ <div className="grow">
+ <strong>{L('Depois de ler algo de fora, pedir antes do que não tem volta', 'After reading something from outside, ask before what can’t be undone')}</strong>
+ <p className="muted small">
+ {L(
+ 'Um e-mail, uma página ou uma issue podem trazer instruções escritas por outra pessoa. Com isso ligado, depois de ler algo assim, enviar, publicar, pagar, apagar e clicar no que é arriscado pedem sua aprovação, mesmo onde uma regra deixa fazer sozinho.',
+ 'An email, a page or an issue can carry instructions someone else wrote. With this on, after reading something like that, sending, publishing, paying, deleting and risky clicks ask for your approval, even where a rule lets it do them alone.'
+ )}
+ </p>
+ </div>
+ <Toggle on={guard} onChange={(v) => !readOnly && onChange({ outsideGuard: v })} />
+ </div>
+ <details className="autonomy__rules">
+ <summary>{L('Ajustar ação por ação', 'Fine-tune action by action')}</summary>
+ <ActionRulesList rules={own.actionRules ?? {}} fallback={(k) => actionMode(k, base)} readOnly={readOnly} onChange={(actionRules) => onChange({ actionRules })} />
+ </details>
+ </div>
+ )
+}
+
+// One row per action that matters, each with what the agent does about it. "Pelo nível" clears the row's own
+// rule: then the level decides, and where it says nothing (normal), the tool's class, as always.
+function ActionRulesList({ rules, fallback, readOnly, onChange }: { rules: ActionRules; fallback: (k: ActionKind) => ActionMode | undefined; readOnly?: boolean; onChange: (r: ActionRules) => void }): ReactNode {
+ const set = (k: ActionKind, m: ActionMode | undefined): void => {
+ const next: ActionRules = { ...rules }
+ if (m) next[k] = m
+ else delete next[k]
+ onChange(next)
+ }
+ return (
+ <div className="grants rules">
+ {ACTION_KINDS.map((k) => {
+ const own = rules[k]
+ const by = fallback(k)
+ const value: ActionMode | 'default' = own ?? 'default'
+ const options: (ActionMode | 'default')[] = ['default', 'ask', 'auto', 'off']
+ return (
+ <div key={k} className="grant">
+ <div className="grant__name">
+ <Icon name="shield" size={15} />
+ <div>
+ <strong>{kindLabel(k)}</strong>
+ <span className="muted small">
+ {actionHint(k)}
+ {!own ? ` · ${L('pelo nível', 'by the level')}: ${by ? modeLabel(by).toLowerCase() : k === 'browser' || k === 'apps' ? modeLabel('ask').toLowerCase() : L('pede só se a ferramenta for sensível', 'asks only if the tool is sensitive')}` : ''}
+ </span>
+ </div>
+ </div>
+ <div className="segmented" role="radiogroup" aria-label={kindLabel(k)}>
+ {options.map((o) => (
+ <button key={o} role="radio" aria-checked={value === o} className={value === o ? 'is-active' : ''} disabled={readOnly} onClick={() => set(k, o === 'default' ? undefined : o)}>
+ {o === 'default' ? L('Pelo nível', 'By level') : modeLabel(o)}
+ </button>
+ ))}
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
export function Card({ title, lead, action, children }: { title: string; lead?: string; action?: ReactNode; children: ReactNode }): ReactNode {
return (
<div className="card">
@@ -1232,7 +1359,7 @@ export function HistoryRow({ id }: { id: string }): ReactNode {
<div className="table__row history-row">
{agent && <AgentAvatar agent={agent} size={22} />}
<span className="history-row__what">
- {toolWords(a.tool)} <span className="muted">· {a.connectorName}</span>
+ {a.connectorId === COMPUTADOR ? shellActions(String(a.args['command'] ?? '')).map(kindLabel).join(', ') || toolWords(a.tool) : toolWords(a.tool)} <span className="muted">· {a.connectorName}</span>
</span>
{a.outcome && <span className="muted small history-row__outcome" title={a.outcome}>{a.outcome}</span>}
<span className={`tag ${a.state === 'approved' ? 'tag--ok' : a.state === 'refused' ? 'tag--danger' : ''}`}>{a.state === 'approved' ? L('aprovado', 'approved') : a.state === 'refused' ? L('recusado', 'refused') : L('expirado', 'expired')}</span>
@@ -2217,6 +2344,18 @@ export function SettingsPage(): ReactNode {
</Card>
)}
+ {pane('agentes') && (
+ <Card
+ title={L('Autonomia', 'Autonomy')}
+ lead={L(
+ 'Pra todos os agentes: até onde eles vão sozinhos e o que pede sua aprovação antes, com um botão na conversa. Na página de cada agente dá pra mudar só pra ele. Ler e investigar nunca pede.',
+ 'For every agent: how far they go on their own and what asks for your approval first, with a button in the conversation. On each agent’s page you can change it for that agent only. Reading and looking into things never asks.'
+ )}
+ >
+ <AutonomyControls own={{ autonomy: settings.autonomy, actionRules: settings.actionRules, outsideGuard: settings.outsideGuard }} onChange={(p) => updateSettings(p)} />
+ </Card>
+ )}
+
{pane('agentes') && (
<Card title={L('Navegador dos agentes', 'Agents’ browser')} lead={L('Como o app acha o que o agente pede pra clicar (“o botão Buscar”). Pelo texto é de graça e resolve a maioria; quando não acha, o agente usa o número do elemento.', 'How the app finds what the agent asks to click (“the Search button”). By text it’s free and handles most cases; when it can’t find it, the agent uses the element’s number.')}>
<div className="segmented segmented--wide" role="radiogroup" aria-label={L('Navegador dos agentes', 'Agents’ browser')}>
diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.css
index 999148a..689dd78 100644
--- a/src/renderer/src/styles.css
+++ b/src/renderer/src/styles.css
@@ -1655,6 +1655,28 @@ h3 {
color: var(--text-2);
white-space: pre-wrap;
}
+.approval__command {
+ margin: 8px 0;
+ padding: 8px 10px;
+ background: var(--code-bg);
+ border-radius: var(--radius);
+ font-size: 12.5px;
+ white-space: pre-wrap;
+ word-break: break-word;
+ max-height: 180px;
+ overflow: auto;
+}
+/* The hint wraps before the buttons do: they stay on the right, one under the other. */
+.rules .grant {
+ flex-wrap: wrap;
+}
+.rules .grant__name {
+ flex: 1 1 0;
+ min-width: 200px;
+}
+.rules .segmented {
+ flex-shrink: 0;
+}
.approval__bound {
font-size: 11.5px;
color: var(--text-3);
@@ -9189,3 +9211,9 @@ button.agent-card__now:hover {
.field__required { color: var(--danger); margin-left: 2px; }
+
+/* How far an agent goes on its own: the level, the guard, and the rules by kind under a fold. */
+.autonomy { display: flex; flex-direction: column; gap: 12px; }
+.autonomy > p { margin: 0; }
+.autonomy__rules > summary { cursor: pointer; font-weight: 500; padding: 4px 0; }
+.autonomy__rules[open] > summary { margin-bottom: 8px; }
diff --git a/src/shared/actions.ts b/src/shared/actions.ts
new file mode 100644
index 0000000..bec4d54
--- /dev/null
+++ b/src/shared/actions.ts
@@ -0,0 +1,433 @@
+// How far an agent goes on its own. Each agent has a level (careful, normal, free) and,
+// over it, a rule per kind of action that matters (a commit, a push, a PR, a merge,
+// deleting, sending, publishing, paying, a risky click in its browser or in an app):
+// asks me first, does it alone, or never. Settings hold the level and rules for every
+// agent; an agent's page, its own. Reading never asks.
+// The gateway reads a call (a shell command, a connector tool, a click) into these kinds
+// before it runs; what no rule decides goes as the tool's class says, as it always has.
+import { L } from './lang'
+
+// The "connector" of approvals for a command on the agent's computer.
+export const COMPUTADOR = 'computador'
+
+export const ACTION_KINDS = ['commit', 'push', 'pr', 'merge', 'delete', 'send', 'publish', 'pay', 'browser', 'apps'] as const
+export type ActionKind = (typeof ACTION_KINDS)[number]
+export type ActionMode = 'ask' | 'auto' | 'off'
+export type ActionRules = Partial<Record<ActionKind, ActionMode>>
+
+const MODES: readonly ActionMode[] = ['ask', 'auto', 'off']
+
+// What puts something in front of other people, spends money or can't be undone: after the agent
+// has read something from outside in a turn (an email, a page, an issue), these may be what that
+// text asked for, so with the guard on they ask first even when a rule lets them run.
+export const OUTBOUND: readonly ActionKind[] = ['send', 'publish', 'pay', 'delete', 'browser', 'apps']
+
+export const kindLabel = (k: ActionKind): string =>
+ ({
+ commit: L('Fazer commit', 'Commit'),
+ push: L('Subir commits (push)', 'Push commits'),
+ pr: L('Abrir pull request', 'Open a pull request'),
+ merge: L('Fazer merge', 'Merge'),
+ delete: L('Apagar', 'Delete'),
+ send: L('Enviar mensagem', 'Send a message'),
+ publish: L('Publicar ou colocar no ar', 'Publish or deploy'),
+ pay: L('Pagar ou transferir', 'Pay or transfer'),
+ browser: L('Clique arriscado no navegador', 'A risky click in the browser'),
+ apps: L('Ação arriscada nos apps', 'A risky action in an app')
+ })[k]
+
+export const actionHint = (k: ActionKind): string =>
+ ({
+ commit: 'git commit',
+ push: 'git push',
+ pr: L('gh pr create, criar PR num conector', 'gh pr create, creating a PR in a connector'),
+ merge: L('git merge, gh pr merge, merge num conector', 'git merge, gh pr merge, merging in a connector'),
+ delete: L('rm -r, apagar branch, git reset --hard, apagar num conector', 'rm -r, deleting a branch, git reset --hard, deleting in a connector'),
+ send: L('e-mail, Slack, comentário: num conector', 'email, Slack, a comment: in a connector'),
+ publish: L('npm publish, deploy, release', 'npm publish, deploy, release'),
+ pay: L('pagamento, transferência, reembolso: num conector', 'payment, transfer, refund: in a connector'),
+ browser: L('enviar, comprar, confirmar, um botão sem nome: no navegador do agente', 'send, buy, confirm, a button with no name: in the agent’s browser'),
+ apps: L('enviar, apagar, confirmar: nos apps do computador', 'send, delete, confirm: in the computer’s apps')
+ })[k]
+
+// What the agent does, in its own words for the approval card: "quer fazer commit".
+export const actionVerb = (k: ActionKind): string =>
+ ({
+ commit: L('fazer commit', 'commit'),
+ push: L('subir commits (push)', 'push commits'),
+ pr: L('abrir uma pull request', 'open a pull request'),
+ merge: L('fazer merge', 'merge'),
+ delete: L('apagar', 'delete'),
+ send: L('enviar uma mensagem', 'send a message'),
+ publish: L('publicar', 'publish'),
+ pay: L('pagar', 'pay'),
+ browser: L('clicar no navegador', 'click in the browser'),
+ apps: L('agir num app', 'act in an app')
+ })[k]
+
+export const modeLabel = (m: ActionMode): string => ({ ask: L('Pede aprovação', 'Asks first'), auto: L('Faz sozinho', 'Does it alone'), off: L('Nunca', 'Never') })[m]
+
+// Only known kinds with known modes: what a saved rule set may hold.
+export function cleanRules(value: unknown): ActionRules {
+ if (!value || typeof value !== 'object') return {}
+ const out: ActionRules = {}
+ for (const k of ACTION_KINDS) {
+ const m = (value as Record<string, unknown>)[k]
+ if (typeof m === 'string' && (MODES as readonly string[]).includes(m)) out[k] = m as ActionMode
+ }
+ return out
+}
+
+// ---------- levels ----------
+
+// careful: asks before anything that changes something. normal: asks before what's sensitive
+// (sending, deleting, paying…), as Tucano always has. free: does everything on its own.
+export type Autonomy = 'careful' | 'normal' | 'free'
+export const AUTONOMY_LEVELS: readonly Autonomy[] = ['careful', 'normal', 'free']
+export const isAutonomy = (v: unknown): v is Autonomy => typeof v === 'string' && (AUTONOMY_LEVELS as readonly string[]).includes(v)
+
+export const autonomyLabel = (a: Autonomy): string => ({ careful: L('Cuidadoso', 'Careful'), normal: L('Normal', 'Normal'), free: L('Sem travas', 'No guardrails') })[a]
+export const autonomyHint = (a: Autonomy): string =>
+ ({
+ careful: L('Pede aprovação antes de qualquer coisa que mude algo: escrever num conector, commit, push, um clique arriscado.', 'Asks before anything that changes something: writing in a connector, a commit, a push, a risky click.'),
+ normal: L('Lê e escreve sozinho; pede antes do que é sensível: enviar, apagar, publicar, pagar, um clique arriscado.', 'Reads and writes on its own; asks before what’s sensitive: sending, deleting, publishing, paying, a risky click.'),
+ free: L('Faz tudo sozinho, sem pedir. O que você marcou como alto risco ainda pede.', 'Does everything on its own, without asking. What you marked high risk still asks.')
+ })[a]
+
+// What a level says about a kind; undefined: the tool's class decides (sensitive asks), as before levels.
+export const levelMode = (level: Autonomy): ActionMode | undefined => (level === 'careful' ? 'ask' : level === 'free' ? 'auto' : undefined)
+
+// Who decides, most specific first: the agent's rule for that kind; its own level (careful or free);
+// the rule in Settings; the level in Settings. An agent left on "Padrão" follows Settings.
+export interface Policy {
+ agentRules?: ActionRules
+ agentLevel?: Autonomy
+ globalRules?: ActionRules
+ globalLevel?: Autonomy
+ guard?: boolean // the outside-content guard (OUTBOUND); off only when the person turned it off
+}
+
+export const policyOf = (agent: { actionRules?: ActionRules; autonomy?: Autonomy; outsideGuard?: boolean } | undefined, settings: { actionRules?: ActionRules; autonomy?: Autonomy; outsideGuard?: boolean }): Policy => ({
+ agentRules: agent?.actionRules,
+ agentLevel: agent?.autonomy,
+ globalRules: settings.actionRules,
+ globalLevel: settings.autonomy,
+ guard: agent?.outsideGuard ?? settings.outsideGuard ?? true
+})
+
+export const levelOf = (p: Policy): Autonomy => p.agentLevel ?? p.globalLevel ?? 'normal'
+
+export function actionMode(kind: ActionKind, p: Policy): ActionMode | undefined {
+ const own = p.agentRules?.[kind]
+ if (own) return own
+ if (p.agentLevel && p.agentLevel !== 'normal') return levelMode(p.agentLevel)
+ return p.globalRules?.[kind] ?? (p.agentLevel ? undefined : levelMode(p.globalLevel ?? 'normal'))
+}
+
+// One call may be several kinds at once (`git commit && git push`): any "never" stops it, else any
+// "ask" makes it wait, else one no rule decides leaves it to the class; "auto" only when all say so.
+export function gate(kinds: readonly ActionKind[], p: Policy): { mode?: ActionMode; kinds: ActionKind[] } {
+ const unique = [...new Set(kinds)]
+ for (const mode of ['off', 'ask'] as const) {
+ const hit = unique.filter((k) => actionMode(k, p) === mode)
+ if (hit.length) return { mode, kinds: hit }
+ }
+ if (!unique.length || unique.some((k) => actionMode(k, p) === undefined)) return { kinds: unique.filter((k) => actionMode(k, p) === undefined) }
+ return { mode: 'auto', kinds: unique }
+}
+
+// What happens to one call. `cls`: the tool's class (a command is a write); `alwaysAllowed`: approved
+// for good from a card; `outside`: the turn has read something from outside; `askByDefault`: what
+// no rule decides asks (a risky click), else it goes by the class.
+export type Verdict = { run: boolean; off?: boolean; why: 'read' | 'rule' | 'level' | 'class' | 'always' | 'risk' | 'guard' | 'never'; kinds: ActionKind[] }
+
+export function verdict(o: { cls: 'read' | 'write' | 'sensitive'; kinds: readonly ActionKind[]; p: Policy; highRisk?: boolean; alwaysAllowed?: boolean; outside?: boolean; askByDefault?: boolean }): Verdict {
+ if (o.cls === 'read' && !o.askByDefault) return { run: true, why: 'read', kinds: [] }
+ const g = gate(o.kinds, o.p)
+ if (g.mode === 'off') return { run: false, off: true, why: 'never', kinds: g.kinds }
+ if (o.highRisk) return { run: false, why: 'risk', kinds: g.kinds }
+ if (g.mode === 'ask') return { run: false, why: 'rule', kinds: g.kinds }
+ const level = levelOf(o.p)
+ // Let through by a rule or by the level: unless what goes out came after something from outside.
+ const loose = (why: Verdict['why'], kinds: readonly ActionKind[], outbound: boolean): Verdict => (outbound && o.p.guard !== false && o.outside ? { run: false, why: 'guard', kinds: [...kinds] } : { run: true, why, kinds: [...kinds] })
+ if (g.mode === 'auto') return loose('rule', g.kinds, g.kinds.some((k) => OUTBOUND.includes(k)))
+ // No rule decides: the level, then the class.
+ if (level === 'careful') return { run: false, why: 'level', kinds: g.kinds }
+ if (level === 'free') return loose('level', g.kinds, o.cls === 'sensitive' || !!o.askByDefault || g.kinds.some((k) => OUTBOUND.includes(k)))
+ if (o.askByDefault) return { run: false, why: 'class', kinds: g.kinds }
+ if (o.cls === 'sensitive') return o.alwaysAllowed ? { run: true, why: 'always', kinds: g.kinds } : { run: false, why: 'class', kinds: g.kinds }
+ return { run: true, why: 'class', kinds: g.kinds }
+}
+
+// ---------- reading a connector tool ----------
+
+// "mergePullRequest" and "merge_pull_request" both become ["merge", "pull", "request"].
+const words = (name: string): string[] =>
+ name
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
+ .toLowerCase()
+ .split(/[^a-z0-9]+/)
+ .filter(Boolean)
+
+// What a connector tool that changes something does, by its name. Read tools have no kind.
+export function toolActions(name: string): ActionKind[] {
+ const w = new Set(words(name))
+ const has = (...x: string[]): boolean => x.some((v) => w.has(v))
+ const out: ActionKind[] = []
+ if (has('commit')) out.push('commit')
+ if (has('push')) out.push('push')
+ if (((has('pull') && has('request')) || has('pr', 'mr')) && has('create', 'open', 'new')) out.push('pr')
+ if (has('merge')) out.push('merge')
+ if (has('delete', 'remove', 'destroy', 'drop', 'purge', 'erase', 'trash')) out.push('delete')
+ if (has('send', 'reply') || (has('post') && has('message', 'comment', 'chat', 'email', 'mail'))) out.push('send')
+ if (has('publish', 'deploy', 'release', 'rollback')) out.push('publish')
+ if (has('pay', 'payment', 'transfer', 'charge', 'refund', 'purchase', 'payout', 'buy')) out.push('pay')
+ return out
+}
+
+// ---------- reading a shell command ----------
+
+// The simple commands in a command line, each as its words, with quotes taken off;
+// what runs inside $(…), `…` and bash -c '…' counts as well.
+export function simpleCommands(src: string, depth = 0): string[][] {
+ const out: string[][] = []
+ const nested: string[] = []
+ let cur: string[] = []
+ let tok = ''
+ let started = false
+ const end = (): void => {
+ if (started) cur.push(tok)
+ tok = ''
+ started = false
+ }
+ const split = (): void => {
+ end()
+ if (cur.length) out.push(cur)
+ cur = []
+ }
+ // From an opening "$(" or "(", the index of its closing ")".
+ const closing = (from: number): number => {
+ let level = 0
+ for (let j = from; j < src.length; j++) {
+ if (src[j] === '(') level++
+ else if (src[j] === ')' && --level === 0) return j
+ }
+ return src.length
+ }
+ for (let i = 0; i < src.length; i++) {
+ const c = src[i]!
+ if (c === '\\') {
+ if (src[i + 1] === '\n') i++
+ else if (i + 1 < src.length) ((tok += src[++i]), (started = true))
+ continue
+ }
+ if (c === "'") {
+ const j = src.indexOf("'", i + 1)
+ tok += src.slice(i + 1, j < 0 ? src.length : j)
+ started = true
+ i = j < 0 ? src.length : j
+ continue
+ }
+ if (c === '"') {
+ let j = i + 1
+ let s = ''
+ while (j < src.length && src[j] !== '"') {
+ if (src[j] === '\\' && j + 1 < src.length) {
+ s += src[j + 1]
+ j += 2
+ continue
+ }
+ s += src[j]
+ j++
+ }
+ // Substitutions inside double quotes still run.
+ for (const m of s.matchAll(/\$\(([^)]*)\)|`([^`]*)`/g)) nested.push(m[1] ?? m[2] ?? '')
+ tok += s
+ started = true
+ i = j
+ continue
+ }
+ if (c === '$' && src[i + 1] === '(') {
+ const j = closing(i + 1)
+ nested.push(src.slice(i + 2, j))
+ tok += '$()'
+ started = true
+ i = j
+ continue
+ }
+ if (c === '$' && src[i + 1] === '{') {
+ const j = src.indexOf('}', i)
+ tok += src.slice(i, j < 0 ? src.length : j + 1)
+ started = true
+ i = j < 0 ? src.length : j
+ continue
+ }
+ if (c === '`') {
+ const j = src.indexOf('`', i + 1)
+ nested.push(src.slice(i + 1, j < 0 ? src.length : j))
+ i = j < 0 ? src.length : j
+ continue
+ }
+ if (c === '#' && !started) {
+ const j = src.indexOf('\n', i)
+ i = j < 0 ? src.length : j - 1
+ continue
+ }
+ if (c === '\n' || ';&|(){}'.includes(c)) {
+ split()
+ continue
+ }
+ if (c === '<' || c === '>' || /\s/.test(c)) {
+ end()
+ continue
+ }
+ tok += c
+ started = true
+ }
+ split()
+ if (depth < 4) for (const n of nested) out.push(...simpleCommands(n, depth + 1))
+ return out
+}
+
+// Commands that run the one after them, with the options of theirs that take a value.
+const WRAPPERS: Record<string, string[]> = {
+ sudo: ['-u', '-g', '-C', '-D', '-h', '-p', '-r', '-t', '-U'],
+ doas: ['-u', '-C'],
+ env: ['-u', '-C', '-S'],
+ command: [],
+ builtin: [],
+ exec: ['-a'],
+ nohup: [],
+ time: ['-f', '-o'],
+ nice: ['-n'],
+ ionice: ['-c', '-n', '-p'],
+ xargs: ['-n', '-P', '-L', '-I', '-d', '-E', '-s', '-a'],
+ stdbuf: ['-i', '-o', '-e'],
+ timeout: ['-s', '-k']
+}
+const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'fish'])
+// Folders a build makes again: wiping them isn't deleting anything of value.
+const REGENERABLE = /(^|\/)(node_modules|dist|build|out|\.next|\.nuxt|\.cache|\.turbo|\.parcel-cache|coverage|__pycache__|\.pytest_cache|\.venv|venv|target)\/?$|^\/tmp\//
+const base = (w: string): string => w.slice(w.lastIndexOf('/') + 1)
+const flag = (args: string[], re: RegExp, ...long: string[]): boolean => args.some((a) => re.test(a) || long.includes(a))
+
+// git's own options before the subcommand: `git -C repo -c k=v push`.
+function gitSub(args: string[]): { sub: string; rest: string[] } {
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]!
+ if (['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path'].includes(a)) i++
+ else if (!a.startsWith('-')) return { sub: a, rest: args.slice(i + 1) }
+ }
+ return { sub: '', rest: [] }
+}
+
+function gitKinds(args: string[]): ActionKind[] {
+ const { sub, rest } = gitSub(args)
+ switch (sub) {
+ case 'commit':
+ return ['commit']
+ case 'push':
+ return flag(rest, /^-[a-zA-Z]*d$/, '--delete') || rest.some((r) => /^\+?:[^/]/.test(r)) ? ['push', 'delete'] : ['push']
+ case 'merge':
+ return rest.some((r) => r === '--abort' || r === '--quit') ? [] : ['merge']
+ case 'branch':
+ return flag(rest, /^-[a-zA-Z]*[dD]/, '--delete') ? ['delete'] : []
+ case 'tag':
+ return flag(rest, /^-[a-zA-Z]*d/, '--delete') ? ['delete'] : []
+ case 'reset':
+ return rest.includes('--hard') ? ['delete'] : []
+ case 'clean':
+ return flag(rest, /^-[a-zA-Z]*f/, '--force') ? ['delete'] : []
+ case 'stash':
+ return rest[0] === 'drop' || rest[0] === 'clear' ? ['delete'] : []
+ default:
+ return []
+ }
+}
+
+function commandKinds(words: string[], depth: number): ActionKind[] {
+ let w = words
+ // Skip what only sets up the real command: VAR=1, sudo, env, xargs and their options.
+ for (;;) {
+ while (w[0] && /^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0])) w = w.slice(1)
+ const head = w[0] ? base(w[0]) : ''
+ const valued = Object.hasOwn(WRAPPERS, head) ? WRAPPERS[head]! : undefined
+ if (!valued) break
+ w = w.slice(1)
+ while (w[0]?.startsWith('-')) w = w.slice(valued.includes(w[0]) ? 2 : 1)
+ if (head === 'timeout') w = w.slice(1) // the duration
+ }
+ const cmd = w[0] ? base(w[0]) : ''
+ const args = w.slice(1)
+ if (!cmd) return []
+ if (SHELLS.has(cmd) || cmd === 'eval') {
+ const at = cmd === 'eval' ? 0 : args.findIndex((a) => /^-[a-z]*c[a-z]*$/.test(a))
+ const script = cmd === 'eval' ? args.join(' ') : at >= 0 ? (args[at + 1] ?? '') : ''
+ return depth < 4 ? shellActions(script, depth + 1) : []
+ }
+ const sub = args.find((a) => !a.startsWith('-')) ?? ''
+ const after = (s: string): string | undefined => args[args.indexOf(s) + 1]
+ switch (cmd) {
+ case 'git':
+ return gitKinds(args)
+ case 'gh': {
+ const what = after(sub)
+ if (sub === 'pr' && what === 'create') return ['pr']
+ if (sub === 'pr' && what === 'merge') return ['merge']
+ if (sub === 'release' && what === 'create') return ['publish']
+ if (what === 'delete' || what === 'delete-asset') return ['delete']
+ if (sub === 'api' && args.some((a, i) => /^(-X|--method)$/.test(args[i - 1] ?? '') && a.toUpperCase() === 'DELETE')) return ['delete']
+ return []
+ }
+ case 'glab': {
+ const what = after(sub)
+ if (sub === 'mr' && what === 'create') return ['pr']
+ if (sub === 'mr' && what === 'merge') return ['merge']
+ return what === 'delete' ? ['delete'] : []
+ }
+ case 'hub':
+ return sub === 'pull-request' ? ['pr'] : []
+ case 'rm': {
+ if (!flag(args, /^-[a-zA-Z]*[rR]/, '--recursive')) return []
+ const targets = args.filter((a) => !a.startsWith('-'))
+ return targets.length && targets.every((t) => REGENERABLE.test(t)) ? [] : ['delete']
+ }
+ case 'find':
+ return args.includes('-delete') ? ['delete'] : []
+ case 'npm':
+ case 'pnpm':
+ case 'yarn':
+ case 'bun':
+ case 'cargo':
+ case 'poetry':
+ case 'gem':
+ return sub === 'publish' || (cmd === 'gem' && sub === 'push') ? ['publish'] : []
+ case 'twine':
+ return sub === 'upload' ? ['publish'] : []
+ case 'docker':
+ case 'podman':
+ return sub === 'push' ? ['publish'] : []
+ case 'vercel':
+ return sub === 'deploy' || args.includes('--prod') ? ['publish'] : []
+ case 'netlify':
+ case 'fly':
+ case 'flyctl':
+ case 'firebase':
+ case 'wrangler':
+ return sub === 'deploy' || sub === 'publish' ? ['publish'] : []
+ case 'terraform':
+ case 'tofu':
+ return sub === 'apply' || sub === 'destroy' ? [sub === 'apply' ? 'publish' : 'delete'] : []
+ default:
+ return []
+ }
+}
+
+// What a shell command does that matters, in order, once each. It reads every
+// command of the line (after &&, ;, |, inside $(…) and bash -c), and quoted text
+// only where it runs: `git commit -m "rm -rf x"` is a commit, not a delete.
+export function shellActions(command: string, depth = 0): ActionKind[] {
+ const out: ActionKind[] = []
+ for (const words of simpleCommands(command)) for (const k of commandKinds(words, depth)) if (!out.includes(k)) out.push(k)
+ return out
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index a136f33..94525fa 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,5 +1,6 @@
// Domain types shared by the core (utility process) and the renderer.
import type { AvatarDefinition } from 'open-bot-avatar'
+import type { ActionRules, Autonomy } from './actions'
import type { ChannelLayout } from './channel-layout'
import type { Answer, Decision } from './questions'
import { L, lang, type Lang } from './lang'
@@ -85,6 +86,9 @@ export interface Agent {
browser?: boolean // drives a browser of its own: opens, clicks, types (spec §24); off unless true
apps?: AgentApp[] // the person's own apps it may use (Notes, Mail…), each to read or to read and change
autoApprove?: string[] // "connectorId:tool" sensitive tools approved for good ("sempre permitir"), never high-risk ones
+ actionRules?: ActionRules // what it does about a commit, a push, a PR…: over settings.actionRules, kind by kind; unset kinds follow them
+ autonomy?: Autonomy // how far it goes on its own (src/shared/actions.ts); unset: Settings' level
+ outsideGuard?: boolean // false: what goes out (a send, a post, a payment) runs on its rules even after reading something from outside; unset: Settings'
folders?: LentFolder[] // Mac folders lent to that computer (spec §13, M5.1); changed only through lendFolder/folderAction
archived: boolean
kind?: 'tuca' // the agent that builds the others: it proposes, the person creates
@@ -167,6 +171,7 @@ export interface Run {
endedAt?: number // when this reply ended, however it ended: where the conversation shows it (saidAt)
receipt?: Receipt
approvalId?: string
+ outside?: boolean // it read something from outside (a connector's answer, a page, an app, the web, a trigger's event): what goes out after asks first, with the guard on
error?: string // what happened and what to do, for people (src/shared/errors.ts)
errorDetail?: string // the raw text behind it (a CLI's stderr), shown folded
depth?: number // 1 when a human message triggered it, +1 for each agent-to-agent hop
@@ -384,6 +389,9 @@ export interface Settings {
defaultLimit: number
approvalTtlHours: number
questionDeadlineHours?: number // a question to someone else, unanswered this long: the requester is told (default 4)
+ actionRules?: ActionRules // for every agent: which actions ask me first, which it does alone, which never (src/shared/actions.ts)
+ autonomy?: Autonomy // every agent's level, unless its page sets its own (default normal)
+ outsideGuard?: boolean // after reading something from outside, what goes out asks first even where rules let it run (default on)
theme: 'system' | 'light' | 'dark'
language: Lang // the app's, and the language agents answer in
openAtLogin?: boolean // so routines run without me opening the app
diff --git a/src/shared/workspaces.ts b/src/shared/workspaces.ts
index 6a5d40f..5fa6553 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', 'chainDepth', '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', 'actionRules', 'autonomy', 'outsideGuard', '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/action-rules.test.ts b/test/action-rules.test.ts
new file mode 100644
index 0000000..098a5a7
--- /dev/null
+++ b/test/action-rules.test.ts
@@ -0,0 +1,400 @@
+// The rules for actions that matter, end to end: the gateway reads a call (a command on the
+// agent's computer, a connector tool), and by Settings and the agent's page it runs, waits
+// for an approval or never runs. Only the model and the computer are fake.
+import { mkdtempSync, readFileSync } from 'node:fs'
+import { DatabaseSync } from 'node:sqlite'
+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 { Tool } from '@modelcontextprotocol/sdk/types.js'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import type { ActionRules } from '../src/shared/actions'
+import type { Agent, Message, Settings } from '../src/shared/types'
+import type { Computers } from '../src/core/computer'
+import { ConnectorManager } from '../src/core/connectors'
+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 { plainCipher, Secrets } from '../src/core/secrets'
+
+const DEMO = join(import.meta.dirname, '..', 'scripts', 'demo-mcp-server.mjs')
+const ready = { installed: true, loggedIn: true }
+
+type Plan = { tool: string; args: Record<string, unknown> } | null
+
+// A "model" that, on each turn, lists its tools and makes at most one call.
+function scripted(plan: (turn: Turn, tools: string[]) => Plan, seen: { turns: Turn[]; tools: Tool[][]; results: unknown[] }): Engine {
+ return {
+ id: 'claude',
+ async *run(turn) {
+ seen.turns.push(turn)
+ let reply = 'ok'
+ if (turn.mcpUrl) {
+ const client = new Client({ name: 'scripted', version: '0' })
+ await client.connect(new StreamableHTTPClientTransport(new URL(turn.mcpUrl)))
+ const tools = (await client.listTools()).tools
+ seen.tools.push(tools)
+ const p = plan(
+ turn,
+ tools.map((t) => t.name)
+ )
+ if (p) {
+ seen.results.push(await client.callTool({ name: p.tool, arguments: p.args }))
+ reply = `chamei ${p.tool}`
+ }
+ await client.close()
+ }
+ yield { type: 'text', delta: reply }
+ yield { type: 'done', text: reply, usage: { inputTokens: 10, cacheReadTokens: 0, outputTokens: 2 } }
+ }
+ }
+}
+
+let dir: string
+let tasksFile: string
+let db: Db
+let gateway: Gateway
+let connectors: ConnectorManager
+let settings: Settings
+let connectorId: string
+let seen: { turns: Turn[]; tools: Tool[][]; results: unknown[] }
+let ran: string[] // the commands the computer ran
+
+const agent = (actionRules?: ActionRules): Agent => ({
+ id: 'a1', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low',
+ limit: 1_000_000, used: 0, grants: { [connectorId]: 'read_write' }, memory: 'auto', computer: true, archived: false, ...(actionRules ? { actionRules } : {})
+})
+
+// A computer that only says what it ran.
+const computers = {
+ call: async (_agent: Agent, name: string, args: Record<string, unknown>) => {
+ if (name !== 'bash') return { result: textResult(`ok: ${name}`) }
+ ran.push(String(args['command']))
+ return { result: textResult(`exit 0\n[rodou] ${String(args['command'])}`) }
+ }
+} as unknown as Computers
+
+function runner(plan: (turn: Turn, tools: string[]) => Plan): Runner {
+ return new Runner({
+ db,
+ engines: { claude: scripted(plan, seen), codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },
+ settings: async () => settings,
+ emit: () => {},
+ workDir: join(dir, 'work'),
+ gateway,
+ connectors,
+ computers
+ })
+}
+
+// One command per turn, in order (null: a turn that calls nothing, like the one after a decision).
+const turns = (...commands: (string | null)[]) => (): Plan => {
+ const command = commands.shift()
+ return command ? { tool: 'bash', args: { command, _motivo: 'pra salvar o trabalho' } } : null
+}
+const runs = (command: string): (() => Plan) => turns(command)
+const agentMessages = (): Message[] => db.messages().filter((m) => m.author.kind === 'agent')
+const textOf = (r: unknown): string => ((r as { content: { text: string }[] }).content[0]?.text ?? '')
+const tasks = (): { id: number }[] => {
+ try {
+ return JSON.parse(readFileSync(tasksFile, 'utf8')) as { id: number }[]
+ } catch {
+ return [{ id: 1 }, { id: 2 }, { id: 3 }] // not written yet: the server's built-in list
+ }
+}
+
+beforeEach(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'ad-rules-'))
+ tasksFile = join(dir, 'tasks.json')
+ db = new Db(join(dir, 'test.db'))
+ seen = { turns: [], tools: [], results: [] }
+ ran = []
+ settings = { workspaceName: 'Edu', 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', autonomy: 'careful' } // careful: every kind asks unless a rule says otherwise
+ gateway = new Gateway()
+ await gateway.start()
+ connectors = new ConnectorManager({ db, secrets: new Secrets(db, plainCipher), emit: () => {}, openUrl: () => {}, oauthCallbackUrl: () => gateway.url('/oauth/callback') })
+ connectorId = await connectors.add({ kind: 'stdio', name: 'Tarefas', command: process.execPath, args: [DEMO], env: { DEMO_TASKS_FILE: tasksFile } })
+ await connectors.connect(connectorId)
+ db.saveAgent(agent())
+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
+})
+
+afterEach(async () => {
+ await connectors.closeAll()
+ await gateway.stop()
+})
+
+describe('commands on the computer', () => {
+ it('on careful, a commit asks first: it becomes a pending approval and nothing runs', async () => {
+ const r = runner(runs('git add -A && git commit -m "primeira versão"'))
+ await r.send('d1', 'faça o commit')
+ await r.idle()
+
+ const [ap] = db.approvals()
+ expect(ap).toMatchObject({ state: 'pending', connectorId: 'computador', tool: 'bash', args: { command: 'git add -A && git commit -m "primeira versão"' }, why: 'pra salvar o trabalho', highRisk: false })
+ expect(ap!.args).not.toHaveProperty('_motivo')
+ expect(agentMessages()[0]?.run).toMatchObject({ status: 'waiting_approval', approvalId: ap!.id })
+ expect(textOf(seen.results[0])).toContain('NÃO rodou')
+ expect(ran).toEqual([])
+ })
+
+ it('approving runs exactly that command, once, and the agent gets its output', async () => {
+ const r = runner(runs('git commit -m wip && git push'))
+ await r.send('d1', 'faça o commit e suba')
+ await r.idle()
+ const ap = db.approvals()[0]!
+ await Promise.all([r.decide(ap.id, 'approved'), r.decide(ap.id, 'refused', 'tarde')]) // the first decision wins
+ await r.idle()
+
+ expect(ran).toEqual(['git commit -m wip && git push'])
+ expect(db.approval(ap.id)).toMatchObject({ state: 'approved', outcome: 'Executou.' })
+ expect(seen.turns.at(-1)?.prompt).toContain('Edu aprovou rodar `git commit -m wip && git push`')
+ expect(seen.turns.at(-1)?.prompt).toContain('[rodou] git commit -m wip && git push')
+ expect(agentMessages()[0]?.run?.steps.at(-1)).toMatchObject({ label: 'Aprovado', status: 'done' })
+ })
+
+ it('refusing runs nothing and tells the agent why', async () => {
+ const r = runner(runs('git push --force'))
+ await r.send('d1', 'faça o push')
+ await r.idle()
+ const ap = db.approvals()[0]!
+ await r.decide(ap.id, 'refused', 'ainda não revisei')
+ await r.idle()
+
+ expect(ran).toEqual([])
+ expect(db.approval(ap.id)).toMatchObject({ state: 'refused', outcome: 'Nada foi rodado.' })
+ expect(seen.turns.at(-1)?.prompt).toContain('recusou rodar `git push --force`: "ainda não revisei"')
+ })
+
+ it('a command with nothing that matters runs right away', async () => {
+ const r = runner(runs('git status && npm test'))
+ await r.send('d1', 'faça os testes')
+ await r.idle()
+ expect(ran).toEqual(['git status && npm test'])
+ expect(db.approvals()).toEqual([])
+ })
+
+ it('"faz sozinho" in Settings lets it run without asking', async () => {
+ settings = { ...settings, actionRules: { commit: 'auto' } }
+ const r = runner(runs('git commit -m wip'))
+ await r.send('d1', 'faça o commit')
+ await r.idle()
+ expect(ran).toEqual(['git commit -m wip'])
+ expect(db.approvals()).toEqual([])
+ })
+
+ it("the agent's own rule wins over Settings, both ways", async () => {
+ settings = { ...settings, actionRules: { commit: 'auto', push: 'ask' } }
+ db.saveAgent(agent({ commit: 'ask', push: 'auto' }))
+ const r = runner(turns('git commit -m x', null, 'git push'))
+ await r.send('d1', 'faça o commit')
+ await r.idle()
+ expect(db.approvals()).toHaveLength(1)
+ await r.decide(db.approvals()[0]!.id, 'refused')
+ await r.idle()
+ await r.send('d1', 'faça o push')
+ await r.idle()
+ expect(ran).toEqual(['git push'])
+ expect(db.approvals()).toHaveLength(1)
+ })
+
+ it('a command with one "ask" kind among "auto" ones still waits', async () => {
+ settings = { ...settings, actionRules: { commit: 'auto' } }
+ const r = runner(runs('git commit -m x && git push'))
+ await r.send('d1', 'faça tudo')
+ await r.idle()
+ expect(ran).toEqual([])
+ expect(db.approvals()[0]).toMatchObject({ state: 'pending' })
+ })
+
+ it('"nunca" never runs it and asks nothing', async () => {
+ db.saveAgent(agent({ push: 'off' }))
+ const r = runner(runs('git push origin main'))
+ await r.send('d1', 'faça o push')
+ await r.idle()
+ expect(ran).toEqual([])
+ expect(db.approvals()).toEqual([])
+ expect(seen.results[0]).toMatchObject({ isError: true })
+ expect(textOf(seen.results[0])).toContain('subir commits (push) está desligado')
+ })
+
+ it('a rule changed while the turn runs takes effect on the next call', async () => {
+ const next = turns('git commit -m x')
+ const r = runner(() => {
+ db.saveAgent(agent({ commit: 'auto' })) // changed on its page while it works
+ return next()
+ })
+ await r.send('d1', 'faça o commit')
+ await r.idle()
+ expect(ran).toEqual(['git commit -m x'])
+ })
+
+ it("bash says which commands wait and which never run, and takes a reason", async () => {
+ db.saveAgent(agent({ publish: 'off' }))
+ const r = runner(() => null)
+ await r.send('d1', 'oi')
+ await r.idle()
+ const bash = seen.tools[0]!.find((t) => t.name === 'bash')!
+ expect(bash.description).toContain('pedem aprovação de Edu antes de rodar: fazer commit, subir commits (push), abrir pull request, fazer merge, apagar')
+ expect(bash.description).toContain('Nunca rodam pra você: publicar ou colocar no ar.')
+ expect(bash.inputSchema.properties).toHaveProperty('_motivo')
+ })
+
+ it('"Aprovar e sempre permitir" turns that kind to "faz sozinho" on the agent', async () => {
+ const r = runner(turns('git commit -m x', null, 'git commit -m y'))
+ await r.send('d1', 'faça o commit')
+ await r.idle()
+ await r.decide(db.approvals()[0]!.id, 'approved', undefined, true)
+ await r.idle()
+ expect(db.agent('a1')?.actionRules).toEqual({ commit: 'auto' })
+ await r.send('d1', 'faça outro commit')
+ await r.idle()
+ expect(ran).toEqual(['git commit -m x', 'git commit -m y'])
+ expect(db.approvals()).toHaveLength(1)
+ })
+
+ it('deleting is held to approve and never allowed for good from the card', async () => {
+ const r = runner(runs('rm -rf src'))
+ await r.send('d1', 'faça a limpeza')
+ await r.idle()
+ const ap = db.approvals()[0]!
+ expect(ap).toMatchObject({ highRisk: true })
+ await r.decide(ap.id, 'approved', undefined, true)
+ await r.idle()
+ expect(ran).toEqual(['rm -rf src'])
+ expect(db.agent('a1')?.actionRules).toBeUndefined()
+ })
+})
+
+describe('connector tools', () => {
+ const deletes = (turn: Turn): Plan => (turn.prompt.includes('apaga') && !turn.prompt.includes('aprovou') ? { tool: 'tarefas__delete_task', args: { id: 2 } } : null)
+
+ it('"faz sozinho" for deleting runs a sensitive delete without asking', async () => {
+ settings = { ...settings, actionRules: { delete: 'auto' } }
+ const r = runner(deletes)
+ await r.send('d1', 'apaga a tarefa 2')
+ await r.idle()
+ expect(db.approvals()).toEqual([])
+ expect(tasks().map((t) => t.id)).toEqual([1, 3])
+ })
+
+ it('"nunca" takes the tool away from the agent', async () => {
+ db.saveAgent(agent({ delete: 'off' }))
+ const r = runner(deletes)
+ await r.send('d1', 'apaga a tarefa 2')
+ await r.idle()
+ expect(seen.tools[0]!.map((t) => t.name)).not.toContain('tarefas__delete_task')
+ expect(seen.results[0]).toMatchObject({ isError: true })
+ expect(tasks().map((t) => t.id)).toEqual([1, 2, 3])
+ })
+
+ it('on careful, a delete still asks', async () => {
+ const r = runner(deletes)
+ await r.send('d1', 'apaga a tarefa 2')
+ await r.idle()
+ expect(db.approvals()[0]).toMatchObject({ state: 'pending', tool: 'delete_task' })
+ })
+})
+
+describe('levels', () => {
+ const deletes = (turn: Turn): Plan => (turn.prompt.includes('apaga') && !turn.prompt.includes('aprovou') ? { tool: 'tarefas__delete_task', args: { id: 2 } } : null)
+ // Reads the list on "lista", deletes on "apaga": two replies, the first reading something from outside.
+ const readsThenDeletes = (turn: Turn): Plan => (turn.prompt.includes('aprovou') ? null : turn.prompt.includes('apaga') ? { tool: 'tarefas__delete_task', args: { id: 2 } } : turn.prompt.includes('lista') ? { tool: 'tarefas__list_tasks', args: {} } : null)
+
+ it('normal (nothing set) is how Tucano always worked: a commit runs, a sensitive delete asks', async () => {
+ settings = { ...settings, autonomy: undefined }
+ const r = runner(runs('git commit -m "x"'))
+ await r.send('d1', 'salva')
+ await r.idle()
+ expect(ran).toEqual(['git commit -m "x"'])
+ const d = runner(deletes)
+ await d.send('d1', 'apaga a tarefa 2')
+ await d.idle()
+ expect(db.approvals()[0]).toMatchObject({ state: 'pending', tool: 'delete_task' })
+ expect(tasks().map((t) => t.id)).toEqual([1, 2, 3])
+ })
+
+ it("no guardrails runs a sensitive delete without asking, and the step says it was the level", async () => {
+ db.saveAgent({ ...agent(), autonomy: 'free' })
+ const r = runner(deletes)
+ await r.send('d1', 'apaga a tarefa 2')
+ await r.idle()
+ expect(db.approvals()).toEqual([])
+ expect(tasks().map((t) => t.id)).toEqual([1, 3])
+ expect(agentMessages()[0]!.run!.steps.map((s) => s.label)).toContain('Executou (sem pedir: autonomia)')
+ })
+
+ it("an agent's own level wins over Settings, and its own rule over its level", async () => {
+ settings = { ...settings, autonomy: 'free' }
+ db.saveAgent({ ...agent({ delete: 'ask' }), autonomy: 'free' })
+ const r = runner(deletes)
+ await r.send('d1', 'apaga a tarefa 2')
+ await r.idle()
+ expect(db.approvals()[0]).toMatchObject({ state: 'pending', tool: 'delete_task' })
+ })
+
+ it('after reading something from outside, the guard makes even no guardrails ask before deleting', async () => {
+ db.saveAgent({ ...agent(), autonomy: 'free' })
+ const r = runner(readsThenDeletes)
+ await r.send('d1', 'lista as tarefas')
+ await r.idle()
+ expect(agentMessages()[0]!.run!.outside).toBe(true)
+ await r.send('d1', 'apaga a tarefa 2')
+ await r.idle()
+ const ap = db.approvals()[0]
+ expect(ap).toMatchObject({ state: 'pending', tool: 'delete_task' })
+ expect(textOf(seen.results[1])).toContain('leu algo de fora')
+ expect(tasks().map((t) => t.id)).toEqual([1, 2, 3])
+ })
+
+ it('with the guard off, no guardrails deletes after reading too', async () => {
+ db.saveAgent({ ...agent(), autonomy: 'free', outsideGuard: false })
+ const r = runner(readsThenDeletes)
+ await r.send('d1', 'lista as tarefas')
+ await r.idle()
+ await r.send('d1', 'apaga a tarefa 2')
+ await r.idle()
+ expect(db.approvals()).toEqual([])
+ expect(tasks().map((t) => t.id)).toEqual([1, 3])
+ })
+
+ it('a tool marked high risk asks even with no guardrails and the guard off', async () => {
+ db.saveAgent({ ...agent(), autonomy: 'free', outsideGuard: false })
+ db.updateTool(connectorId, 'delete_task', { highRisk: true })
+ const r = runner(deletes)
+ await r.send('d1', 'apaga a tarefa 2')
+ await r.idle()
+ expect(db.approvals()[0]).toMatchObject({ state: 'pending', tool: 'delete_task', highRisk: true })
+ })
+
+ it('careful asks before a write a connector does on its own, like creating a task', async () => {
+ const r = runner((turn) => (turn.prompt.includes('cria') && !turn.prompt.includes('aprovou') ? { tool: 'tarefas__create_task', args: { title: 'nova' } } : null))
+ await r.send('d1', 'cria uma tarefa')
+ await r.idle()
+ expect(db.approvals()[0]).toMatchObject({ state: 'pending', tool: 'create_task' })
+ })
+})
+
+describe('saved rules', () => {
+ it('an agent keeps its rules, only known kinds and modes', () => {
+ db.saveAgent({ ...agent(), actionRules: { commit: 'auto', push: 'maybe', bogus: 'off' } as unknown as ActionRules })
+ expect(db.agent('a1')?.actionRules).toEqual({ commit: 'auto' })
+ db.saveAgent(agent())
+ expect(db.agent('a1')?.actionRules).toBeUndefined()
+ })
+
+ it('a database another build already migrated further still gets the column', () => {
+ const file = join(dir, 'other.db')
+ new Db(file).close()
+ const raw = new DatabaseSync(file)
+ raw.exec('ALTER TABLE agents DROP COLUMN action_rules; PRAGMA user_version = 999')
+ raw.close()
+ const other = new Db(file)
+ other.saveAgent({ ...agent({ push: 'off' }), grants: {} })
+ expect(other.agent('a1')?.actionRules).toEqual({ push: 'off' })
+ other.close()
+ })
+})
diff --git a/test/actions.test.ts b/test/actions.test.ts
new file mode 100644
index 0000000..3230c15
--- /dev/null
+++ b/test/actions.test.ts
@@ -0,0 +1,189 @@
+import { describe, expect, it } from 'vitest'
+import { actionMode, cleanRules, gate, policyOf, shellActions, simpleCommands, toolActions, verdict, type Policy } from '../src/shared/actions'
+
+describe('shellActions', () => {
+ it('finds the git actions that matter', () => {
+ expect(shellActions('git commit -m "first"')).toEqual(['commit'])
+ expect(shellActions('git push origin agent/x')).toEqual(['push'])
+ expect(shellActions('git merge feature')).toEqual(['merge'])
+ expect(shellActions('git status && git diff && git log --oneline -5')).toEqual([])
+ expect(shellActions('git add . && git checkout -b agent/x')).toEqual([])
+ })
+
+ it('reads every command of the line, once each, in order', () => {
+ expect(shellActions('git add -A && git commit -m wip && git push -u origin HEAD')).toEqual(['commit', 'push'])
+ expect(shellActions('git commit -m a; git commit -m b')).toEqual(['commit'])
+ expect(shellActions('cd /projetos/app\ngit push')).toEqual(['push'])
+ expect(shellActions('(cd repo && git push)')).toEqual(['push'])
+ expect(shellActions('npm test || git push')).toEqual(['push'])
+ })
+
+ it("skips git's own options before the subcommand", () => {
+ expect(shellActions('git -C /projetos/app -c user.name=Lia commit -m x')).toEqual(['commit'])
+ expect(shellActions('git --no-pager push')).toEqual(['push'])
+ })
+
+ it('looks through wrappers, env assignments and nested shells', () => {
+ expect(shellActions('GIT_AUTHOR_NAME=Lia git commit -m x')).toEqual(['commit'])
+ expect(shellActions('sudo -u lia git push')).toEqual(['push'])
+ expect(shellActions('timeout 30 git push')).toEqual(['push'])
+ expect(shellActions(`bash -lc 'git push origin main'`)).toEqual(['push'])
+ expect(shellActions(`sh -c "cd x && git commit -m 'y'"`)).toEqual(['commit'])
+ expect(shellActions('eval "git push"')).toEqual(['push'])
+ expect(shellActions('echo $(git push)')).toEqual(['push'])
+ expect(shellActions('echo "pushed: $(git push 2>&1)"')).toEqual(['push'])
+ expect(shellActions('echo `git commit -m x`')).toEqual(['commit'])
+ expect(shellActions('/usr/bin/git push')).toEqual(['push'])
+ })
+
+ it('does not read quoted text as commands', () => {
+ expect(shellActions('git commit -m "rm -rf everything; git push"')).toEqual(['commit'])
+ expect(shellActions(`echo 'git push'`)).toEqual([])
+ expect(shellActions('grep -r "git commit" docs')).toEqual([])
+ expect(shellActions('# git push later\nls')).toEqual([])
+ })
+
+ it('opens and merges PRs from the command line', () => {
+ expect(shellActions('gh pr create --title x --body y')).toEqual(['pr'])
+ expect(shellActions('gh pr merge 12 --squash')).toEqual(['merge'])
+ expect(shellActions('gh pr view 12 && gh pr list')).toEqual([])
+ expect(shellActions('glab mr create')).toEqual(['pr'])
+ expect(shellActions('hub pull-request -m x')).toEqual(['pr'])
+ expect(shellActions('git merge --abort')).toEqual([])
+ })
+
+ it('knows deleting', () => {
+ expect(shellActions('rm -rf /projetos/app/src')).toEqual(['delete'])
+ expect(shellActions('rm -r docs')).toEqual(['delete'])
+ expect(shellActions('rm --recursive docs')).toEqual(['delete'])
+ expect(shellActions('rm notes.txt')).toEqual([])
+ expect(shellActions('rm -rf node_modules dist')).toEqual([]) // a build makes them again
+ expect(shellActions('rm -rf node_modules src')).toEqual(['delete'])
+ expect(shellActions('git branch -D agent/old')).toEqual(['delete'])
+ expect(shellActions('git branch --delete agent/old')).toEqual(['delete'])
+ expect(shellActions('git branch -a')).toEqual([])
+ expect(shellActions('git reset --hard HEAD~1')).toEqual(['delete'])
+ expect(shellActions('git reset HEAD~1')).toEqual([])
+ expect(shellActions('git clean -fdx')).toEqual(['delete'])
+ expect(shellActions('git clean -n')).toEqual([])
+ expect(shellActions('git stash drop')).toEqual(['delete'])
+ expect(shellActions('git push origin --delete agent/old')).toEqual(['push', 'delete'])
+ expect(shellActions('git push origin :agent/old')).toEqual(['push', 'delete'])
+ expect(shellActions('find . -name "*.log" -delete')).toEqual(['delete'])
+ expect(shellActions('gh repo delete me/x --yes')).toEqual(['delete'])
+ })
+
+ it('knows publishing', () => {
+ expect(shellActions('npm publish --access public')).toEqual(['publish'])
+ expect(shellActions('cargo publish')).toEqual(['publish'])
+ expect(shellActions('docker push me/app:1')).toEqual(['publish'])
+ expect(shellActions('vercel --prod')).toEqual(['publish'])
+ expect(shellActions('npx vercel')).toEqual([])
+ expect(shellActions('fly deploy')).toEqual(['publish'])
+ expect(shellActions('gh release create v1.0.0')).toEqual(['publish'])
+ expect(shellActions('npm install && npm run build')).toEqual([])
+ })
+})
+
+describe('simpleCommands', () => {
+ it('splits on operators and keeps quoted words whole', () => {
+ expect(simpleCommands(`a 'b c' && d "e f"|g;h`)).toEqual([['a', 'b c'], ['d', 'e f'], ['g'], ['h']])
+ })
+ it('treats redirections as word breaks', () => {
+ expect(simpleCommands('git push >out.txt 2>&1')).toEqual([['git', 'push', 'out.txt', '2'], ['1']])
+ })
+})
+
+describe('toolActions', () => {
+ it('reads a connector tool by its name', () => {
+ expect(toolActions('create_pull_request')).toEqual(['pr'])
+ expect(toolActions('createPullRequest')).toEqual(['pr'])
+ expect(toolActions('merge_pull_request')).toEqual(['merge'])
+ expect(toolActions('push_files')).toEqual(['push'])
+ expect(toolActions('delete_task')).toEqual(['delete'])
+ expect(toolActions('send_email')).toEqual(['send'])
+ expect(toolActions('chat_postMessage')).toEqual(['send'])
+ expect(toolActions('deploy_service')).toEqual(['publish'])
+ expect(toolActions('create_payment')).toEqual(['pay'])
+ expect(toolActions('create_issue')).toEqual([])
+ expect(toolActions('update_pull_request')).toEqual([])
+ })
+ it('does not match words inside other words', () => {
+ expect(toolActions('resend_invite')).toEqual([])
+ expect(toolActions('update_prompt')).toEqual([])
+ })
+})
+
+describe('rules', () => {
+ it('out of the box no rule decides: the tool says, as before levels', () => {
+ expect(actionMode('commit', {})).toBeUndefined()
+ expect(actionMode('commit', { globalLevel: 'careful' })).toBe('ask')
+ expect(actionMode('commit', { globalLevel: 'free' })).toBe('auto')
+ })
+
+ it("the agent's rule, then its own level, then Settings' rule, then Settings' level", () => {
+ expect(actionMode('commit', { globalRules: { commit: 'auto' } })).toBe('auto')
+ expect(actionMode('commit', { agentRules: { commit: 'ask' }, globalRules: { commit: 'auto' } })).toBe('ask')
+ expect(actionMode('push', { agentRules: { commit: 'auto' }, globalRules: { push: 'off' } })).toBe('off')
+ expect(actionMode('push', { agentLevel: 'free', globalRules: { push: 'off' } })).toBe('auto')
+ expect(actionMode('push', { agentLevel: 'normal', globalRules: { push: 'off' }, globalLevel: 'free' })).toBe('off')
+ expect(actionMode('push', { agentLevel: 'normal', globalLevel: 'free' })).toBeUndefined()
+ })
+
+ it('stops a call when any of its kinds is never, else waits when any asks, and runs alone only when all say so', () => {
+ expect(gate(['commit', 'push'], { globalRules: { commit: 'auto' }, globalLevel: 'careful' })).toEqual({ mode: 'ask', kinds: ['push'] })
+ expect(gate(['commit', 'push'], { agentRules: { push: 'off' } })).toEqual({ mode: 'off', kinds: ['push'] })
+ expect(gate(['commit', 'push'], { agentRules: { commit: 'auto', push: 'auto' } })).toEqual({ mode: 'auto', kinds: ['commit', 'push'] })
+ expect(gate(['commit', 'push'], { agentRules: { commit: 'auto' } })).toEqual({ kinds: ['push'] })
+ expect(gate([], {})).toEqual({ kinds: [] })
+ })
+
+ it('reads the policy off an agent and Settings, with the guard on unless someone turned it off', () => {
+ expect(policyOf(undefined, {}).guard).toBe(true)
+ expect(policyOf({ outsideGuard: false }, { outsideGuard: true }).guard).toBe(false)
+ expect(policyOf({}, { outsideGuard: false }).guard).toBe(false)
+ })
+ it('keeps only known kinds and modes', () => {
+ expect(cleanRules({ commit: 'auto', push: 'maybe', rm: 'off', pr: 'off' })).toEqual({ commit: 'auto', pr: 'off' })
+ expect(cleanRules(null)).toEqual({})
+ expect(cleanRules('x')).toEqual({})
+ })
+})
+
+describe('what happens to a call', () => {
+ const normal: Policy = { guard: true }
+ const careful: Policy = { globalLevel: 'careful', guard: true }
+ const free: Policy = { globalLevel: 'free', guard: true }
+ const v = (o: Partial<Parameters<typeof verdict>[0]>) => verdict({ cls: 'write', kinds: [], p: normal, ...o })
+
+ it('normal is how Tucano always worked', () => {
+ expect(v({ cls: 'read' }).run).toBe(true)
+ expect(v({ cls: 'write' }).run).toBe(true)
+ expect(v({ cls: 'sensitive', kinds: ['delete'] })).toMatchObject({ run: false, why: 'class' })
+ expect(v({ cls: 'sensitive', kinds: ['delete'], alwaysAllowed: true })).toMatchObject({ run: true, why: 'always' })
+ expect(v({ askByDefault: true, kinds: ['browser'] })).toMatchObject({ run: false })
+ })
+
+ it('careful asks before any change, even one approved for good, and still reads freely', () => {
+ expect(v({ p: careful, cls: 'read' }).run).toBe(true)
+ expect(v({ p: careful, cls: 'write' })).toMatchObject({ run: false, why: 'level' })
+ expect(v({ p: careful, cls: 'sensitive', kinds: ['send'], alwaysAllowed: true })).toMatchObject({ run: false })
+ })
+
+ it('no guardrails runs everything, but never what is high risk or turned off', () => {
+ expect(v({ p: free, cls: 'sensitive', kinds: ['delete'] }).run).toBe(true)
+ expect(v({ p: free, cls: 'sensitive' }).run).toBe(true)
+ expect(v({ p: free, askByDefault: true, kinds: ['browser'] }).run).toBe(true)
+ expect(v({ p: free, cls: 'sensitive', kinds: ['delete'], highRisk: true })).toMatchObject({ run: false, why: 'risk' })
+ expect(v({ p: { ...free, agentRules: { pay: 'off' } }, cls: 'sensitive', kinds: ['pay'] })).toMatchObject({ run: false, off: true })
+ })
+
+ it('after something from outside, the guard asks before what goes out or cannot be undone, and only that', () => {
+ expect(v({ p: free, cls: 'sensitive', kinds: ['send'], outside: true })).toMatchObject({ run: false, why: 'guard' })
+ expect(v({ p: free, cls: 'sensitive', kinds: ['delete'], outside: true })).toMatchObject({ run: false, why: 'guard' })
+ expect(v({ p: free, cls: 'sensitive', outside: true })).toMatchObject({ run: false, why: 'guard' })
+ expect(v({ p: free, cls: 'write', kinds: ['commit'], outside: true }).run).toBe(true)
+ expect(v({ p: { ...normal, agentRules: { send: 'auto' } }, cls: 'sensitive', kinds: ['send'], outside: true })).toMatchObject({ run: false, why: 'guard' })
+ expect(v({ p: { ...free, guard: false }, cls: 'sensitive', kinds: ['send'], outside: true }).run).toBe(true)
+ })
+})
diff --git a/test/autonomy-clicks.test.ts b/test/autonomy-clicks.test.ts
new file mode 100644
index 0000000..af24ae3
--- /dev/null
+++ b/test/autonomy-clicks.test.ts
@@ -0,0 +1,174 @@
+// How far an agent goes on its own, for what isn't a connector: a risky click in its browser and a risky
+// action in one of the person's apps. Through the real runner and gateway; the page and the app are fakes.
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import type { Agent, BrowserElement, BrowserReply, Settings } from '../src/shared/types'
+import { Browser, type BrowserHost } from '../src/core/browser'
+import { DesktopApps, type Cli, type Envelope } from '../src/core/apps'
+import { Db } from '../src/core/db'
+import { callTool, fakeEngine } from '../src/core/engines/fake'
+import type { Engine } from '../src/core/engines/types'
+import { Gateway } from '../src/core/gateway'
+import { Runner } from '../src/core/runs'
+
+const ready = { installed: true, loggedIn: true }
+const base: Settings = { workspaceName: 'Edu', 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' } as unknown as Settings
+
+const lia = (extra: Partial<Agent> = {}): Agent => ({ id: 'lia-0001', name: 'Lia', handle: 'lia', role: 'Vídeos', color: 'rose', instructions: '', modelId: 'opus', effort: 'high', limit: 1_000_000, used: 0, grants: {}, memory: 'read', computer: false, archived: false, ...extra })
+
+// A page in memory with a "Publicar" button: what Chromium would do, recorded.
+function fakePage(): { host: BrowserHost; clicks: () => number } {
+ const page = { url: '', title: '' }
+ const elements: BrowserElement[] = [{ ref: 3, role: 'botão', label: 'Publicar', inView: true }]
+ const calls: string[] = []
+ const host: BrowserHost = async (_agentId, op, args) => {
+ calls.push(op)
+ const here: BrowserReply = { url: page.url, title: page.title, frame: Buffer.from('jpeg').toString('base64'), w: 1280, h: 800, shown: false }
+ if (op === 'open') Object.assign(page, { url: String(args?.['url']), title: 'Studio' })
+ if (op === 'snapshot') return { ...here, frame: undefined, elements }
+ return { ...here, url: page.url, title: page.title }
+ }
+ return { host, clicks: () => calls.filter((c) => c === 'click').length }
+}
+
+// The Notes app with an "Apagar" button, as agent-desktop describes it.
+function fakeNotes(): { cli: Cli; clicks: () => number } {
+ let snap = 0
+ const calls: string[][] = []
+ const cli: Cli = async (args) => {
+ calls.push(args)
+ const ok = (data: Record<string, unknown>): Envelope => ({ ok: true, data })
+ if (args[0] === 'snapshot') {
+ snap++
+ return ok({ snapshot_id: `s${snap}`, window: { title: 'Notas' }, tree: { role: 'window', name: 'Notas', children: [{ role: 'button', name: 'Apagar', ref_id: `@s${snap}:e1` }] } })
+ }
+ if (args[0] === 'click' || args[0] === 'press') return ok({})
+ if (args[0] === 'list-apps') return ok({ apps: [{ name: 'Notas' }] })
+ return { ok: false, error: { message: 'unknown' } }
+ }
+ return { cli, clicks: () => calls.filter((c) => c[0] === 'click').length }
+}
+
+let db: Db
+let gateway: Gateway
+let settings: Settings
+let results: unknown[]
+const textOf = (r: unknown): string => ((r as { content: { type: string; text: string }[] }).content.find((c) => c.type === 'text')?.text ?? '')
+const stepLabels = (): string[] => db.messages().filter((m) => m.author.kind === 'agent').flatMap((m) => m.run?.steps.map((s) => s.label) ?? [])
+
+// A "model" that does the calls given, once per reply that isn't the one after a decision.
+const scripted = (calls: [string, Record<string, unknown>][]): Engine => ({
+ id: 'claude',
+ async *run(turn) {
+ if (!/aprovou|recusou/.test(turn.prompt)) for (const [name, args] of calls) results.push(await callTool(turn.mcpUrl!, name, args))
+ yield { type: 'done', text: 'ok', usage: { inputTokens: 10, cacheReadTokens: 0, outputTokens: 2 } }
+ }
+})
+const others = { codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
+
+beforeEach(async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ad-auto-'))
+ db = new Db(join(dir, 'test.db'))
+ settings = { ...base }
+ results = []
+ gateway = new Gateway()
+ await gateway.start()
+})
+afterEach(async () => {
+ await gateway.stop()
+})
+
+describe('a risky click in the browser', () => {
+ const publish: [string, Record<string, unknown>][] = [
+ ['navegador_abrir', { url: 'https://studio.youtube.com/video/1' }],
+ ['navegador_clicar', { alvo: 'Publicar' }]
+ ]
+ const run = async (agent: Agent): Promise<{ clicks: number }> => {
+ db.saveAgent(agent)
+ db.createConversation({ id: 'd1', kind: 'dm', name: 'lia-0001', members: ['lia-0001'] })
+ const page = fakePage()
+ const browser = new Browser({ host: page.host, db, dataDir: mkdtempSync(join(tmpdir(), 'ad-auto-nav-')), emit: () => {}, me: () => 'Edu' })
+ const r = new Runner({ db, engines: { claude: scripted(publish), ...others }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'w-')), gateway, browser })
+ await r.send('d1', 'publica o vídeo')
+ await r.idle()
+ return { clicks: page.clicks() }
+ }
+
+ it('asks on normal, as it always did', async () => {
+ const { clicks } = await run(lia({ browser: true }))
+ expect(db.approvals()[0]).toMatchObject({ connectorId: 'navegador', tool: 'navegador_clicar', state: 'pending' })
+ expect(clicks).toBe(0)
+ })
+
+ it('with no guardrails and the guard off, clicks right away and says so in the step', async () => {
+ const { clicks } = await run(lia({ browser: true, autonomy: 'free', outsideGuard: false }))
+ expect(db.approvals()).toEqual([])
+ expect(clicks).toBe(1)
+ expect(stepLabels()).toContain('Clicou (sem pedir: autonomia)')
+ expect(textOf(results[1])).not.toMatch(/aprovação/)
+ })
+
+ it('with no guardrails and the guard on, still asks: a page is someone else\'s text', async () => {
+ const { clicks } = await run(lia({ browser: true, autonomy: 'free' }))
+ expect(db.approvals()[0]).toMatchObject({ tool: 'navegador_clicar', state: 'pending' })
+ expect(clicks).toBe(0)
+ })
+
+ it('"faz sozinho" for risky clicks, with the guard off, clicks on normal too', async () => {
+ const { clicks } = await run(lia({ browser: true, actionRules: { browser: 'auto' }, outsideGuard: false }))
+ expect(db.approvals()).toEqual([])
+ expect(clicks).toBe(1)
+ })
+
+ it('"nunca" never clicks and asks nothing', async () => {
+ const { clicks } = await run(lia({ browser: true, autonomy: 'free', actionRules: { browser: 'off' } }))
+ expect(db.approvals()).toEqual([])
+ expect(clicks).toBe(0)
+ expect(textOf(results[1])).toMatch(/desligados pra você/)
+ })
+})
+
+describe('a risky action in an app', () => {
+ const remove: [string, Record<string, unknown>][] = [
+ ['app_ver', { app: 'Notas' }],
+ ['app_clicar', { app: 'Notas', alvo: 'Apagar' }]
+ ]
+ const run = async (agent: Agent): Promise<{ clicks: number }> => {
+ db.saveAgent(agent)
+ db.createConversation({ id: 'd1', kind: 'dm', name: 'lia-0001', members: ['lia-0001'] })
+ const notes = fakeNotes()
+ const apps = new DesktopApps(notes.cli, { platform: 'darwin' })
+ const r = new Runner({ db, engines: { claude: scripted(remove), ...others }, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'w-')), gateway, apps })
+ await r.send('d1', 'apaga a nota')
+ await r.idle()
+ return { clicks: notes.clicks() }
+ }
+ const notesRw: Agent['apps'] = [{ name: 'Notas', level: 'read_write' }]
+
+ it('asks on normal, as it always did', async () => {
+ const { clicks } = await run(lia({ apps: notesRw }))
+ expect(db.approvals()[0]).toMatchObject({ connectorId: 'apps', tool: 'app_clicar', state: 'pending' })
+ expect(clicks).toBe(0)
+ })
+
+ it('with no guardrails and the guard off, does it right away, once', async () => {
+ const { clicks } = await run(lia({ apps: notesRw, autonomy: 'free', outsideGuard: false }))
+ expect(db.approvals()).toEqual([])
+ expect(clicks).toBe(1)
+ expect(stepLabels()).toContain('Fez (sem pedir: autonomia)')
+ })
+
+ it('with no guardrails and the guard on, still asks: what an app shows is someone else\'s text', async () => {
+ const { clicks } = await run(lia({ apps: notesRw, autonomy: 'free' }))
+ expect(db.approvals()[0]).toMatchObject({ tool: 'app_clicar', state: 'pending' })
+ expect(clicks).toBe(0)
+ })
+
+ it('"nunca" never does it and asks nothing', async () => {
+ const { clicks } = await run(lia({ apps: notesRw, autonomy: 'free', actionRules: { apps: 'off' } }))
+ expect(db.approvals()).toEqual([])
+ expect(clicks).toBe(0)
+ })
+})
diff --git a/test/autonomy-core.test.ts b/test/autonomy-core.test.ts
new file mode 100644
index 0000000..e4abb62
--- /dev/null
+++ b/test/autonomy-core.test.ts
@@ -0,0 +1,74 @@
+// How far an agent goes on its own, over the real core's API, as the app's screens send it: an agent's
+// level, its rules and its guard are kept, Settings take theirs, and nothing unknown gets in.
+import { rmSync } from 'node:fs'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import type { Agent, Settings } from '../src/shared/types'
+import { bootCore, type Client, type TestCore } from './helpers/core'
+
+vi.setConfig({ testTimeout: 30_000 })
+
+let core: TestCore
+let ana: Client
+let lia: Agent
+type Snap = { agents: Agent[]; settings: Settings }
+const err = async (p: Promise<unknown>): Promise<string> => p.then(() => 'ok', (e: Error) => e.message)
+const agentNow = async (): Promise<Agent> => (await ana.call<Snap>('snapshot')).agents.find((a) => a.id === lia.id)!
+
+beforeAll(async () => {
+ core = await bootCore()
+ ana = core.connect()
+ lia = (await ana.call<Snap>('snapshot')).agents.find((a) => a.handle === 'lia')!
+}, 30_000)
+afterAll(() => {
+ try {
+ rmSync(core.dataDir, { recursive: true, force: true })
+ } catch {
+ // Windows: still open
+ }
+})
+
+describe("an agent's autonomy, saved from its page", () => {
+ it('starts with nothing of its own: Settings decide', async () => {
+ const a = await agentNow()
+ expect(a.autonomy).toBeUndefined()
+ expect(a.outsideGuard).toBeUndefined()
+ expect(a.actionRules ?? {}).toEqual({})
+ })
+
+ it('keeps the level, the rules and the guard it was saved with, and gives them back', async () => {
+ // What the page sends: the whole agent with the patch over it (store.ts patchAgent).
+ await ana.call('saveAgent', { agent: { ...(await agentNow()), autonomy: 'free', outsideGuard: false, actionRules: { pay: 'off', send: 'ask' } }, channelIds: [] })
+ const a = await agentNow()
+ expect(a).toMatchObject({ autonomy: 'free', outsideGuard: false, actionRules: { pay: 'off', send: 'ask' } })
+ })
+
+ it('"Padrão" takes its own level away again, and the guard back to Settings', async () => {
+ const { autonomy: _a, outsideGuard: _g, ...rest } = await agentNow()
+ await ana.call('saveAgent', { agent: rest, channelIds: [] })
+ const a = await agentNow()
+ expect(a.autonomy).toBeUndefined()
+ expect(a.outsideGuard).toBeUndefined()
+ })
+
+ it('drops what it doesn\'t know: a level, a kind or a mode that isn\'t one', async () => {
+ await ana.call('saveAgent', { agent: { ...(await agentNow()), autonomy: 'yolo', outsideGuard: 'no', actionRules: { pay: 'maybe', rm: 'off', push: 'auto' } } as unknown as Agent, channelIds: [] })
+ const a = await agentNow()
+ expect(a.autonomy).toBeUndefined()
+ expect(a.outsideGuard).toBeUndefined()
+ expect(a.actionRules).toEqual({ push: 'auto' })
+ })
+})
+
+describe('autonomy for every agent, in Settings', () => {
+ it('takes a level, rules and the guard', async () => {
+ expect(await err(ana.call('updateSettings', { patch: { autonomy: 'careful', outsideGuard: false, actionRules: { delete: 'off' } } }))).toBe('ok')
+ const s = (await ana.call<Snap>('snapshot')).settings
+ expect(s).toMatchObject({ autonomy: 'careful', outsideGuard: false, actionRules: { delete: 'off' } })
+ })
+
+ it('refuses a level that isn\'t one, and keeps only known rules', async () => {
+ expect(await err(ana.call('updateSettings', { patch: { autonomy: 'yolo' } }))).toMatch(/inválido/)
+ await ana.call('updateSettings', { patch: { actionRules: { delete: 'auto', rm: 'off', pay: 'maybe' } } })
+ expect((await ana.call<Snap>('snapshot')).settings.actionRules).toEqual({ delete: 'auto' })
+ })
+})