Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Add Composio as a connector, explain Google's Developer Preview, and ask before sends and posts (#188)
Eduardo Machadofe3c2c5c634c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 23a9542..a94fb1a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,15 +7,18 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht### Added- **How many replies agents give in a row is a setting.** Agents mentioning each other stopped after 3 replies from one message, which cut flows like planner → developer → reviewer → developer halfway. **Settings › Agents › Limits** now has **Agent replies in a row**, from 1 to 10; left alone, it stays 3.+- **Composio in the connector store, with a warning.** [Composio Connect](https://docs.composio.dev/docs/composio-connect) reaches hundreds of apps (Google, Notion, HubSpot…) with nothing to set up: no Google Cloud app, no token; it signs in through the browser. Unlike every other connector, the data goes through Composio's servers and the access to each account is kept by Composio, which logs each call; the card, the window before connecting and the connector's page say so plainly, and point to the direct connectors. Composio offers a few tools that find and run the apps' actions instead of one tool per action, so each call to one of its runners counts as what it runs: a batch in `COMPOSIO_MULTI_EXECUTE_TOOL` takes the strictest of its actions, judged by their names (`GMAIL_FETCH_EMAILS` reads, `GMAIL_CREATE_EMAIL_DRAFT` writes, `GMAIL_SEND_EMAIL` is sensitive), and a raw `COMPOSIO_PROXY_EXECUTE` request by its method. Reads alone run right away, even with read-only access; writes need read-and-write access; sensitive actions ask for approval, and the card lists each action. A call outside Composio's documented shape, an action it can't place, or its remote code tools always ask. "Approve and always allow" on a batch allows each inner action that asked (say, `GMAIL_REPLY_TO_THREAD`) for that agent, never the runner itself: a later batch runs without asking only when every action that would ask is allowed. Raw requests, code and calls outside the shape are never allowed for good, and the rules show and can be removed on the agent's page like any other. Google's setup window mentions it as the way around making a Google Cloud app.### Changed- **Long skill recipes are kept whole.** A recipe over 20,000 characters was refused when written or proposed, cut when linked from Claude Code or Codex, and left out of an imported team. Now 10,000 characters is a recommendation: past it, Tucano says by how much and keeps the whole recipe, up to a million characters.- **The pick lists look like the rest of the app.** Effort, model, a tool's class, the routine's agent and where it posts, and the other settings pick lists open a menu of the app's own instead of the system's, with the keyboard working as before. The model list has a filter, and on a harness with models from several providers (OpenCode, Pi), they come grouped by provider.+- **Sending something to other people asks first, by default.** A connector tool whose verb puts something in front of others (post, reply, forward, share, invite, comment, email, message), or that creates a comment, a reply or a post, is now sensitive, like send and delete already were: Slack's post-message, Linear's `save_comment`, GitHub's `add_issue_comment`, Notion's comment tool. The words count only as the verb, so `list_messages`, `get_message` and `search_emails` still read, and a draft (`create_email_draft`) is still a write. To have an agent post without asking, use "Approve and always allow" on its request, or set the tool's class to "write" on the connector's page. A class you chose by hand now stays when the tools are refreshed and when the rules change: on the first connection after updating, a tool whose class was still the automatic one takes the new default, and one you changed keeps yours.### Fixed- **The wiki no longer misses a long reply.** A reply that started before another and ended well after it never reached the wiki, because the wiki's curator had already read past where it started. It now goes by when each reply ended, the same order the conversation shows.+- **Google's connectors say what their preview needs.** Google's MCP servers are in Developer Preview and only serve Cloud projects enrolled in the [Google Workspace Developer Preview Program](https://developers.google.com/workspace/preview), which the setup didn't say: the connectors failed with "Access to this tool requires that your Google Cloud project (…) is enrolled in the Google Workspace Developer Preview Program". The Google setup window and the guide now have that step (the form asks for the project number; approval usually takes a couple of days), and when a Google tool still answers with that error, the agent is told it's a step only the person can do in their own Cloud project, not something to retry or ask the Tuca for, and that Composio connects Google meanwhile, through its servers.## [0.2.16] - 2026-11-07diff --git a/src/core/connectors.ts b/src/core/connectors.tsindex e61e623..e3f35b8 100644--- a/src/core/connectors.ts+++ b/src/core/connectors.ts@@ -15,7 +15,7 @@ import type { CoreEvent } from '../shared/rpc'import { ownAppOf, type AppProvider, type CatalogEntry } from '../shared/connector-catalog'import type { Connector, ConnectorInput, ConnectorStatus, ConnectorTool } from '../shared/types'import type { Db } from './db'-import { classify } from './policy'+import { classify, legacyClassify } from './policy'import type { Secrets } from './secrets'import { OpError, resolveOp, resolveOpRefs } from './onepassword'@@ -60,6 +60,25 @@ export function errorReason(r: Pick<CallToolResult, 'content' | 'structuredContereturn contentText(r).trim() || L('O servidor devolveu um erro sem mensagem.', 'The server returned an error with no message.')}+// Google's MCP servers are in Developer Preview: until the person's Cloud project is enrolled, every tool+// answers "Access to this tool requires that your Google Cloud project (…) is enrolled in the Google+// Workspace Developer Preview Program". Said plainly, so the agent sends the person to that step instead+// of trying again or sending them to the Tuca, who can't do it either.+export const GOOGLE_PREVIEW_URL = 'https://developers.google.com/workspace/preview'+export function googlePreviewHint(url: string | undefined, text: string): string | undefined {+ let host = ''+ try {+ host = new URL(url ?? '').hostname+ } catch {+ return undefined+ }+ if (!/(^|\.)googleapis\.com$/i.test(host) || !/Developer Preview Program/i.test(text)) return undefined+ return L(+ `[Isto é um passo de configuração do Google, que só a pessoa pode fazer: os servidores MCP do Google estão em Developer Preview, e o projeto dela no Google Cloud precisa estar inscrito no Google Workspace Developer Preview Program, em ${GOOGLE_PREVIEW_URL} (o formulário pede o número do projeto). A aprovação costuma levar alguns dias, e até lá as ferramentas do Google falham. Nem você nem o Tuca conseguem resolver isso: explique o passo e não tente de novo. Enquanto isso, a Composio, na loja de conectores, conecta o Google sem esse passo, mas os dados passam pelos servidores dela.]`,+ `[This is a Google setup step only the person can do: Google's MCP servers are in Developer Preview, and their Google Cloud project must be enrolled in the Google Workspace Developer Preview Program, at ${GOOGLE_PREVIEW_URL} (the form asks for the project number). Approval usually takes a few days, and until then Google's tools fail. Neither you nor the Tuca can fix this: explain the step and don't retry. Meanwhile, Composio, in the connector store, connects Google without this step, but the data goes through its servers.]`+ )+}+// Why a tool call threw, in words: a timeout says how long it waited, an MCP error keeps the code and the// data the server sent with it (the SDK's message leaves the data out).export function callError(e: unknown, timeoutMs = CALL_TIMEOUT_MS): string {@@ -438,7 +457,7 @@ export class ConnectorManager {do {const page = await client.listTools(cursor ? { cursor } : undefined)for (const t of page.tools) {- listed.push({ name: t.name, description: t.description ?? '', inputSchema: t.inputSchema as Record<string, unknown>, cls: classify(t) })+ listed.push({ name: t.name, description: t.description ?? '', inputSchema: t.inputSchema as Record<string, unknown>, cls: classify(t), legacyCls: legacyClassify(t) })}cursor = page.nextCursor} while (cursor)@@ -459,7 +478,7 @@ export class ConnectorManager {try {const r = (await l.client.callTool({ name, arguments: args }, undefined, { timeout })) as CallToolResultl.failures = 0- return r+ return this.explained(id, r)} catch (e) {let failure = eif (staleSession(e)) {@@ -467,7 +486,7 @@ export class ConnectorManager {const again = this.live.get(id)?.clientif (again) {try {- return (await again.callTool({ name, arguments: args }, undefined, { timeout })) as CallToolResult+ return this.explained(id, (await again.callTool({ name, arguments: args }, undefined, { timeout })) as CallToolResult)} catch (e2) {failure = e2}@@ -478,10 +497,18 @@ export class ConnectorManager {}const c = this.deps.db.connector(id)if (c?.kind === 'stdio' && ++l.failures >= MAX_STDIO_FAILURES) this.setStatus(id, 'error', L(`Falhou ${l.failures} vezes seguidas.`, `Failed ${l.failures} times in a row.`))- throw new Error(callError(failure, timeout), { cause: failure })+ const why = callError(failure, timeout)+ const hint = googlePreviewHint(c?.url, why)+ throw new Error(hint ? `${hint} ${why}` : why, { cause: failure })}}+ // A failed result with a known cause gets that cause first, in words the agent can pass on.+ private explained(id: string, r: CallToolResult): CallToolResult {+ const hint = r.isError ? googlePreviewHint(this.deps.db.connector(id)?.url, errorReason(r)) : undefined+ return hint ? { ...r, content: [{ type: 'text', text: hint }, ...(r.content ?? [])] } : r+ }+// ---------- OAuth ----------// The authorization page's address comes back too: on a server there's nodiff --git a/src/core/db.ts b/src/core/db.tsindex 59ce738..5e02b67 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -481,6 +481,12 @@ export const MIGRATIONS = [CREATE INDEX IF NOT EXISTS messages_by_thread_id ON messages (thread_id, at);CREATE INDEX IF NOT EXISTS messages_by_author ON messages (author_id, at);CREATE INDEX IF NOT EXISTS receipts_by_message ON receipts (message_id);+ `,+ // The class the rules gave a tool at its last sync: a class equal to it is still automatic and+ // follows the rules when they change; any other was chosen by hand and stays. Empty until the first+ // sync after this, which tells the two apart with the rules from before.+ `+ ALTER TABLE connector_tools ADD COLUMN cls_auto TEXT;`]@@ -1205,19 +1211,27 @@ export class Db {// Applies the server's current tool list. On the first sync every tool comes// in enabled; afterwards, tools the server adds come in disabled and flagged.- syncTools(connectorId: string, listed: { name: string; description: string; inputSchema: Record<string, unknown>; cls: ToolClass }[]): void {+ // `cls`: the class the rules give the tool now; `legacyCls`, the one the rules before outbound verbs+ // gave it, which tells an automatic class from a hand-picked one on a tool synced before cls_auto.+ // A class still automatic follows the rules; one chosen by hand stays.+ syncTools(connectorId: string, listed: { name: string; description: string; inputSchema: Record<string, unknown>; cls: ToolClass; legacyCls?: ToolClass }[]): void {this.tx(() => {const first = !(this.db.prepare('SELECT synced FROM connectors WHERE id = ?').get(connectorId) as { synced: number } | undefined)?.synced- const known = new Set(this.tools(connectorId).map((t) => t.name))+ const stored = new Map((this.db.prepare('SELECT name, cls, cls_auto FROM connector_tools WHERE connector_id = ?').all(connectorId) as Row[]).map((r) => [str(r['name']), { cls: str(r['cls']), auto: r['cls_auto'] == null ? undefined : str(r['cls_auto']) }]))for (const t of listed) {- if (known.has(t.name)) {- this.db.prepare('UPDATE connector_tools SET description = ?, input_schema = ? WHERE connector_id = ? AND name = ?').run(t.description, JSON.stringify(t.inputSchema), connectorId, t.name)+ const was = stored.get(t.name)+ if (was) {+ const automatic = was.cls === (was.auto ?? t.legacyCls ?? t.cls)+ this.db+ .prepare('UPDATE connector_tools SET description = ?, input_schema = ?, cls = ?, cls_auto = ? WHERE connector_id = ? AND name = ?')+ .run(t.description, JSON.stringify(t.inputSchema), automatic ? t.cls : was.cls, t.cls, connectorId, t.name)} else {this.db- .prepare('INSERT INTO connector_tools (connector_id, name, description, input_schema, cls, enabled, high_risk, is_new) VALUES (?, ?, ?, ?, ?, ?, 0, ?)')- .run(connectorId, t.name, t.description, JSON.stringify(t.inputSchema), t.cls, first ? 1 : 0, first ? 0 : 1)+ .prepare('INSERT INTO connector_tools (connector_id, name, description, input_schema, cls, cls_auto, enabled, high_risk, is_new) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)')+ .run(connectorId, t.name, t.description, JSON.stringify(t.inputSchema), t.cls, t.cls, first ? 1 : 0, first ? 0 : 1)}}+ const known = stored.keys()const names = new Set(listed.map((t) => t.name))for (const name of known) if (!names.has(name)) this.db.prepare('DELETE FROM connector_tools WHERE connector_id = ? AND name = ?').run(connectorId, name)this.db.prepare('UPDATE connectors SET synced = 1 WHERE id = ?').run(connectorId)diff --git a/src/core/guide/aprovacoes.md b/src/core/guide/aprovacoes.mdindex 1863bb7..830ba4f 100644--- a/src/core/guide/aprovacoes.md+++ b/src/core/guide/aprovacoes.md@@ -4,7 +4,7 @@Nada sensível acontece sem você. Quando um agente quer publicar código, colocar algo no ar, apagar ou enviar algo pra fora, a ação não roda na hora: vira um pedido de aprovação, com a ferramenta e os argumentos exatos.## O que pede aprovação-- Ferramentas de conector da classe **sensível**.+- Ferramentas de conector da classe **sensível**. Por padrão: apagar, enviar, publicar, colocar no ar, pagar, e mandar algo pra outras pessoas (postar, responder, encaminhar, comentar, compartilhar, convidar). Um rascunho não pede.- Abrir um PR no GitHub.- No navegador do agente e nos apps do computador, cliques que compram, publicam, enviam, pagam ou apagam.- Pedidos de acesso: um agente sem acesso (ou só com leitura) a um conector pode pedir; se você liberar, ele continua numa nova mensagem.@@ -17,9 +17,11 @@ Nada sensível acontece sem você. Quando um agente quer publicar código, coloc## Os botões- **Aprovar**: cobre só esta chamada, com estes valores. Se o agente mudar qualquer coisa, pede de novo.- **Recusar**: dá pra dizer por quê; o agente recebe o motivo.-- **Aprovar e sempre permitir**: daqui pra frente aquele agente usa aquela ferramenta sem pedir. Não vale pra ações de alto risco. Pra desfazer, na página do agente, **Ferramentas** › **Sempre permitido, sem pedir:** › **Voltar a pedir aprovação**.+- **Aprovar e sempre permitir**: daqui pra frente aquele agente usa aquela ferramenta sem pedir. Não vale pra ações de alto risco. Na Composio, vale pra cada ação do pedido (GMAIL_REPLY_TO_THREAD, por exemplo), não pro executor inteiro (veja **composio**). Pra desfazer, na página do agente, **Ferramentas** › **Sempre permitido, sem pedir:** › **Voltar a pedir aprovação**.- Ação de **alto risco**: é preciso segurar o botão pra aprovar (**Segure pra aprovar**). No Telegram, são dois toques.+Prefere que um conector poste sem pedir pra ninguém? Na página dele, mude a **Classe** da ferramenta pra **escrita**. O que você escolhe à mão fica, mesmo quando as regras do Tucano mudam.+## ExpiraçãoUm pedido sem decisão expira. O prazo fica em **Configurações › Agentes** (Settings › Agents) › **Limites** › **Expiração de aprovações**: 1 hora, 24 horas (padrão) ou 7 dias. Expirado, nada acontece; peça de novo ao agente se ainda quiser.diff --git a/src/core/guide/composio.md b/src/core/guide/composio.mdnew file mode 100644index 0000000..cf463ae--- /dev/null+++ b/src/core/guide/composio.md@@ -0,0 +1,34 @@+# Composio: centenas de apps por um terceiro+> O conector da Composio: o que ele dá, o preço em privacidade (seus dados passam pelos servidores dela), como conectar e por que cada ação pede aprovação.++A Composio é um serviço que liga agentes a centenas de apps (Google, Notion, HubSpot, Salesforce…) sem você configurar nada: sem app no Google Cloud, sem token. Fica na loja, em **Negócio e dados**.++## O preço: seus dados passam pela Composio+Nos outros conectores, os dados vão do serviço direto pro seu computador. Na Composio não:+- Tudo o que os agentes leem e mandam (e-mails, planilhas, documentos) passa pelos servidores dela.+- O acesso às suas contas (Google, Notion…) fica guardado com a Composio, não no seu computador.+- Ela registra cada chamada, com o que foi pedido e o que voltou, e diz guardar isso por até 1 ano. O Tucano não controla o que ela guarda nem por quanto tempo.++Se preferir que nada passe por terceiros, use os conectores diretos (pro Google, veja **google**). A janela de conectar e a página do conector repetem esse aviso.++## Conectar+1. Em **Conectores**, **Conectar** na Composio. Leia o aviso e clique em **Entendi, conectar**.+2. O login da Composio abre no navegador: entre ou crie a conta (o plano grátis tem limite de chamadas por mês).+3. Dê acesso a um agente, como em qualquer conector.++As contas de cada app você liga na hora: na primeira vez que um agente precisa do Gmail, por exemplo, a Composio devolve um link de login, e o agente mostra pra você abrir.++## Ferramentas e aprovações+A Composio não mostra uma ferramenta por ação. Ela dá umas poucas que acham e rodam as ações dos apps, e o Tucano julga cada chamada pelo que ela roda:+- **COMPOSIO_SEARCH_TOOLS** e **COMPOSIO_GET_TOOL_SCHEMAS** só procuram: são de leitura.+- **COMPOSIO_MULTI_EXECUTE_TOOL** roda as ações que vão nos argumentos (GMAIL_FETCH_EMAILS, GMAIL_SEND_EMAIL…). Sua classe é **por chamada**: vale pela ação mais forte. Só leituras (buscar, listar, ler) rodam na hora, inclusive pra quem só tem **Ler**. Escritas (criar um rascunho) precisam de **Ler e escrever**. Sensíveis (enviar, responder, postar, apagar, rodar código) pedem aprovação, e o card mostra cada ação. Uma chamada fora do formato documentado também pede aprovação (quem só lê recebe uma recusa).+- **COMPOSIO_PROXY_EXECUTE** manda uma requisição direta à API de um app: GET e HEAD leem (a não ser que o caminho diga uma mudança, como chat.postMessage); POST, PUT e PATCH escrevem; DELETE pede aprovação.+- **COMPOSIO_REMOTE_WORKBENCH** e **COMPOSIO_REMOTE_BASH_TOOL** rodam código nos servidores dela: sempre pedem aprovação, e quem só lê nem vê.+- **COMPOSIO_MANAGE_CONNECTIONS** liga contas: pede aprovação também.++**Aprovar e sempre permitir** num pedido do MULTI_EXECUTE vale pra cada ação sensível do pedido, sozinha (**Aprovar e sempre permitir GMAIL_REPLY_TO_THREAD**), pra aquele agente; nunca pro executor inteiro. Um pedido só roda sem perguntar quando todas as ações que pediriam estão permitidas. Requisições do PROXY_EXECUTE, código e chamadas fora do formato nunca ficam permitidas. Pra desfazer: na página do agente, **Sempre permitido, sem pedir:**. **Alto risco** no executor exige segurar o botão e desliga o sempre permitir.++## Quando dá errado+- **precisa autorizar**: **Autorizar no navegador** e entre na Composio de novo.+- O agente manda um link da Composio: é o login de um app que ainda não está ligado. Abra, entre e peça pra ele continuar.+- A Composio parou de responder no meio do mês: veja o limite do seu plano em composio.dev.diff --git a/src/core/guide/conectores.md b/src/core/guide/conectores.mdindex e6cdd4e..f4ba79c 100644--- a/src/core/guide/conectores.md+++ b/src/core/guide/conectores.md@@ -12,17 +12,20 @@ Um conector é um servidor MCP: ele dá aos agentes ferramentas de um serviço (## Google e SlackGmail, Calendar, Drive, Docs e Sheets pedem um app seu no Google Cloud, criado uma vez: veja **google**. O Slack também pede um app seu, interno do seu workspace: veja **slack**.+## Composio+A Composio liga centenas de apps sem configurar nada, mas seus dados passam por ela, e o acesso às suas contas fica com ela: veja **composio**.+## Personalizado**Adicionar personalizado** (Add custom) pra qualquer servidor MCP, inclusive os internos da empresa:- **Remoto (URL)**: o **URL do servidor MCP** e a **Autenticação**: **OAuth** (abre o navegador pra autorizar), **Token** (vai no cabeçalho Authorization: Bearer) ou **Nenhuma**.- **Local (comando)**: **Comando**, **Argumentos** e **Variáveis de ambiente** (uma por linha, NOME=valor). Roda um processo no seu computador com o seu usuário: só adicione comandos em que você confia.-Os servidores MCP que você já configurou no Claude Code, no Codex e nos outros aparecem numa lista própria: **Adicionar** traz cada um pro Tucano, com as permissões e aprovações daqui.+Os servidores MCP já configurados no Claude Code, no Codex e nos outros aparecem numa lista própria: **Adicionar** traz cada um, com as permissões daqui.Credenciais ficam cifradas no cofre do sistema e nunca aparecem de novo. No lugar de um token ou de uma variável, dá pra pôr uma referência do 1Password (`op://Cofre/Item/campo`): o Tucano guarda só a referência e lê o valor com o 1Password CLI a cada conexão. Pra trocar um token, **Token (substitui o atual)**.## As ferramentas de um conector-Na página do conector, cada ferramenta tem uma **Classe**: **leitura**, **escrita** ou **sensível**, e pode ser marcada como **Alto risco** ou desligada. Ferramentas novas que o servidor publicar depois entram desligadas até você revisar. Sensíveis sempre pedem aprovação (veja **aprovacoes**). **Quem usa:** mostra os agentes com acesso.+Na página do conector, cada ferramenta tem uma **Classe**: **leitura**, **escrita** ou **sensível** (mandar algo pra outras pessoas e apagar são sensíveis por padrão; a classe que você escolhe fica), e pode ser marcada como **Alto risco** ou desligada. Ferramentas novas que o servidor publicar depois entram desligadas até você revisar. Sensíveis sempre pedem aprovação (veja **aprovacoes**). **Quem usa:** mostra os agentes com acesso.Nos agentes, o nível por conector é **Sem acesso**, **Ler** (só as de leitura) ou **Ler e escrever**.diff --git a/src/core/guide/google.md b/src/core/guide/google.mdindex fb4fff9..e42c3ab 100644--- a/src/core/guide/google.md+++ b/src/core/guide/google.md@@ -1,20 +1,24 @@# Google: Gmail, Calendar, Drive, Docs e Sheets-> Conectar os serviços do Google: o app que a pessoa cria no Google Cloud uma vez, os 5 passos, o aviso de app não verificado e o que conferir quando o Google recusa.+> Conectar os serviços do Google: o app que a pessoa cria no Google Cloud uma vez, os 6 passos (com a inscrição no Developer Preview), o aviso de app não verificado e o que conferir quando o Google recusa.O Google só deixa entrar apps cadastrados nele, então a pessoa cria o seu uma vez, no Google Cloud, e os cinco entram com ele. O primeiro **Conectar** num deles abre **Seu app do Google** com os passos:1. Criar um projeto no Google Cloud.2. Ativar as APIs (um link ativa as dez: a de cada serviço e a MCP de cada um).-3. Configurar a tela de login (Google Auth Platform › Começar): nome do app, e-mail, Público-alvo **Externo** (ou **Interno** numa conta Google Workspace de empresa), e o próprio e-mail em **Usuários de teste**.-4. Criar o cliente: tipo **App para computador**, com **Usar este cliente para um agente com IA** marcado. Sem essa marca o Google recusa os conectores.-5. Colar o **ID do cliente** e a **chave secreta do cliente** e clicar em **Salvar e conectar**.+3. Inscrever o projeto no **Google Workspace Developer Preview Program** (developers.google.com/workspace/preview): os servidores MCP do Google ainda estão em prévia e só atendem projetos inscritos. O formulário pede o número do projeto (no painel do projeto). A aprovação costuma levar uns dias; dá pra seguir os passos e salvar, mas até lá os conectores do Google falham.+4. Configurar a tela de login (Google Auth Platform › Começar): nome do app, e-mail, Público-alvo **Externo** (ou **Interno** numa conta Google Workspace de empresa), e o próprio e-mail em **Usuários de teste**.+5. Criar o cliente: tipo **App para computador**, com **Usar este cliente para um agente com IA** marcado. Sem essa marca o Google recusa os conectores.+6. Colar o **ID do cliente** e a **chave secreta do cliente** e clicar em **Salvar e conectar**.Depois os outros quatro são um clique. Pra trocar de app: **Seu app do Google**, ao lado do título Google na loja; trocar desconecta os do Google, que pedem login de novo.Com o app **em teste**, o Google pede login de novo a cada 7 dias. Pra parar: em Público-alvo, **Publicar app**; o login passa a mostrar "O Google não verificou este app", e como o app é da própria pessoa, é só clicar em **Avançado** e continuar.+Prefere não criar o app? A Composio conecta o Google sem isso, mas seus dados passam pelos servidores dela: veja **composio**.+O Gmail busca, lê, rascunha e põe marcadores, mas não envia nem apaga de vez. O Drive lê tudo e só escreve nos arquivos que criou ou abriu.## Quando dá errado+- "Access to this tool requires that your Google Cloud project (...) is enrolled in the Google Workspace Developer Preview Program": falta o passo 3. Só a própria pessoa resolve, no projeto dela: inscreva-o em developers.google.com/workspace/preview e espere a aprovação (uns dias). Nem o Tuca nem os agentes conseguem fazer isso. Enquanto espera, a Composio conecta o Google sem esse passo, mas seus dados passam pelos servidores dela (veja **composio**).- **Falta o seu app do Google**: clique em **Conectar** num deles e siga os passos.- O Google recusa no login ou o conector não conecta depois: confira se o cliente é **App para computador**, se tem **Usar este cliente para um agente com IA** marcado, se as APIs estão ativadas no mesmo projeto do cliente e se o e-mail está em **Usuários de teste**.- Pede login de novo toda semana: o app está **em teste**; publique-o (acima).diff --git a/src/core/policy.ts b/src/core/policy.tsindex 560e8ac..76022a3 100644--- a/src/core/policy.ts+++ b/src/core/policy.ts@@ -1,34 +1,15 @@-// Pure rules of the governance layer: how a tool is classified, which tools a-// grant exposes, and how an approval is bound to one exact call.+// Pure rules of the governance layer: which tools a grant exposes, and how an approval is bound to+// one exact call. How a tool is classified is in shared/classify.ts.import { createHash } from 'node:crypto'-import type { ConnectorTool, GrantLevel, ToolClass } from '../shared/types'--const READ_WORDS = new Set(['get', 'list', 'search', 'read', 'find', 'fetch', 'query', 'describe', 'show', 'view', 'count', 'lookup', 'retrieve'])-const SENSITIVE_WORDS = new Set(['delete', 'remove', 'merge', 'deploy', 'send', 'publish', 'transfer', 'pay', 'destroy', 'drop', 'revoke'])--// "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)--// Annotations first; then the name. A sensitive word anywhere wins over a read verb-// at the start, since a wrong "read" would skip approval.-export function classify(tool: { name: string; annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean } }): ToolClass {- if (tool.annotations?.readOnlyHint === true) return 'read'- if (tool.annotations?.destructiveHint === true) return 'sensitive'- const w = words(tool.name)- if (w.some((x) => SENSITIVE_WORDS.has(x))) return 'sensitive'- if (w[0] && READ_WORDS.has(w[0])) return 'read'- return 'write'-}+import type { ConnectorTool, GrantLevel } from '../shared/types'+// The classes themselves live in shared/, so the approval card reads them too.+export { callClass, classify, classifyAction, legacyClassify, permits, runnerAllowed, runnerRules } from '../shared/classify'// `read` exposes read tools; `read_write` exposes everything (sensitive ones go through approval).-export function allowed(tool: ConnectorTool, grant: GrantLevel | undefined): boolean {+// `perCall`: a runner judged on each call (Composio's), exposed to readers too, for its read-only calls.+export function allowed(tool: ConnectorTool, grant: GrantLevel | undefined, perCall = false): boolean {if (!tool.enabled) return false- if (grant === 'read') return tool.cls === 'read'+ if (grant === 'read') return tool.cls === 'read' || perCallreturn grant === 'read_write'}diff --git a/src/core/runs.ts b/src/core/runs.tsindex a29d6de..8a73c80 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -26,7 +26,8 @@ import { Followups, replyKey } from './followups'import { sessionConfig, Sessions, type SessionPlan, type Shown } from './sessions'import { JEV_MODEL, routeJev } from './jev'import { ROUTER_HISTORY, route, routerTurn, screenHandoff } from './router'-import { allowed, approvalHash, canonical } from './policy'+import { allowed, approvalHash, callClass, canonical, permits, runnerAllowed, runnerRules } from './policy'+import { perCallTool } from '../shared/composio'import { agentOwner, deciders, dmOwner, mentionedPeople, People, personNamed, presentPeople, promptPeople, requesterOf, routineBehalf, toPeopleOnly } from './people'import { can } from './policy-people'import { awaitDone, idleSleepSeconds, isStatusTool, pendingOf, pollTool } from './waits'@@ -981,7 +982,7 @@ export class Runner {// 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])) 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))) 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')@@ -1033,13 +1034,21 @@ export class Runner {...ownTools.map((t) => ({ ...t, _meta: { ...t._meta, ...ALWAYS_LOAD } })),...[...exposed].map(([name, { connector, tool }]): ToolDef => {const schema = tool.inputSchema as ToolDef['inputSchema']- if (tool.cls !== 'sensitive') return { name, description: `[${connector.name}] ${tool.description}`, inputSchema: schema }+ const perCall = perCallTool(connector.url, tool.name)+ if (tool.cls !== 'sensitive' && !perCall) return { name, description: `[${connector.name}] ${tool.description}`, inputSchema: schema }return {name,- description: `[${connector.name}] ${tool.description}\n${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.`- )}`,+ description: `[${connector.name}] ${tool.description}\n${+ perCall+ ? L(+ `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.`+ )+ }`,inputSchema: {...schema,type: 'object',@@ -1464,14 +1473,29 @@ export class Runner {if (!hit) return textResult(L(`Ferramenta desconhecida: ${name}`, `Unknown tool: ${name}`), true)// Defense in depth: grants or the tool may have changed since the turn started.const current = db.tools(hit.connector.id).find((t) => t.name === hit.tool.name)- if (!current || !allowed(current, db.agent(agent.id)?.grants[hit.connector.id])) return textResult(L(`Ferramenta não permitida agora: ${name}`, `Tool not allowed right now: ${name}`), true)+ const grant = db.agent(agent.id)?.grants[hit.connector.id]+ const perCall = perCallTool(hit.connector.url, hit.tool.name)+ if (!current || !allowed(current, grant, perCall)) return textResult(L(`Ferramenta não permitida agora: ${name}`, `Tool not allowed right now: ${name}`), true)const detail = `${hit.connector.name} · ${current.name}`+ // What runs is exactly what was judged: these arguments, classified here, go to the server (or into the approval) as they are.+ const { [REASON_PARAM]: why, ...callArgs } = args+ // A runner (Composio's) counts as what this call runs; any other tool, as its class.+ const cls = callClass(current, hit.connector.url, callArgs)+ if (!permits(cls, grant))+ return textResult(+ L(+ `Recusada: esta chamada ${cls === 'sensitive' ? 'tem uma ação sensível' : 'muda algo'} e precisa de acesso de leitura e escrita ao ${hit.connector.name}; você só tem leitura. Use só ações de leitura, ou peça acesso com ${ACCESS_REQUEST}.`,+ `Refused: this call ${cls === 'sensitive' ? 'has a sensitive action' : 'changes something'} and needs read-and-write access to ${hit.connector.name}; you only have read access. Use read actions only, or ask for access with ${ACCESS_REQUEST}.`+ ),+ true+ )// "Sempre permitir": a sensitive tool approved for good runs like a write one (never a high-risk one).- const always = current.cls === 'sensitive' && !current.highRisk && !!db.agent(agent.id)?.autoApprove?.includes(`${hit.connector.id}:${current.name}`)- if (current.cls === 'sensitive' && !always) {+ // 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) {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 } = argsapproval = {id: randomUUID(),hash: approvalHash(hit.connector.id, current.name, callArgs),@@ -1504,10 +1528,9 @@ export class Runner {}const t0 = Date.now()- const step: Step = { id: randomUUID(), label: current.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') : always ? L('Executou (sempre permitido)', 'Ran (always allowed)') : 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 { [REASON_PARAM]: _reason, ...toolArgs } = args- const input = keyArg(toolArgs)+ const input = keyArg(callArgs)if (input) step.input = inputflush()msg.run = { ...msg.run!, steps: [...closeThinking('done', THOUGHT()), step] }@@ -1522,12 +1545,11 @@ export class Runner {save()}try {- const { [REASON_PARAM]: _reason, ...toolArgs } = args- const first = await this.deps.connectors!.call(hit.connector.id, current.name, toolArgs)+ const first = await this.deps.connectors!.call(hit.connector.id, current.name, callArgs)// A query still running: the app waits for it here, with the connector's own status tool, instead// of the agent sleeping and asking again. Not a status tool the agent called itself (asking whether a// deploy finished wants the answer now), nor a write (starting a job doesn't mean waiting for it).- const pending = current.cls === 'read' && !isStatusTool(current.name) ? pendingOf(first) : undefined+ const pending = cls === 'read' && !isStatusTool(current.name) ? pendingOf(first) : undefinedconst poller = pending && pollTool(db.tools(hit.connector.id), pending, (t) => allowed(t, db.agent(agent.id)?.grants[hit.connector.id]))const done = (r: CallToolResult): void => (r.isError ? finish('error', errorReason(r)) : finish('done', undefined, resultSummary(resultText(r))))if (!pending || !poller) {@@ -1882,10 +1904,14 @@ export class Runner {emit({ type: 'approval', approval: db.approval(id)! })if (decider) db.addActivity({ personId: decider, kind: 'approval.decided', target: id, detail: { decision, agentId: ap.agentId, connector: ap.connectorName, tool: ap.tool } })const owner = db.agent(ap.agentId)- if (always && decision === 'approved' && owner && !ap.highRisk && ap.tool !== ACCESS_REQUEST && ap.connectorId !== GITHUB && ap.connectorId !== NAVEGADOR && ap.connectorId !== APPS && !owner.autoApprove?.includes(`${ap.connectorId}:${ap.tool}`)) {- db.saveAgent({ ...owner, autoApprove: [...(owner.autoApprove ?? []), `${ap.connectorId}:${ap.tool}`] })+ // A runner (Composio's) is never allowed for good itself: "always" allows the inner tools that asked, each on its own.+ 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) {+ 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: ap.tool } })+ db.addActivity({ personId: decider, kind: 'approval.always', target: owner.id, detail: { connector: ap.connectorName, tool: fresh.map((r) => r.slice(r.indexOf(':') + 1)).join(', ') } })}const settings = await this.deps.settings()// Who decided, or (expired) who it was waiting on: the requester.@@ -1979,7 +2005,8 @@ export class Runner {} else if (decision === 'approved') {const tool = db.tools(ap.connectorId).find((t) => t.name === ap.tool)const connector = this.deps.connectors?.list().find((c) => c.id === ap.connectorId)- if (!agent || !connector || !tool || !allowed(tool, agent.grants[ap.connectorId])) {+ const grant = agent?.grants[ap.connectorId]+ if (!agent || !connector || !tool || !allowed(tool, grant, runner) || !permits(callClass(tool, connector.url, ap.args), grant)) {outcome = L('Não executou: o acesso mudou depois do pedido.', "Didn't run: access changed after the request.")task = L(`${me} aprovou o seu pedido ${call}, mas o app não executou: o seu acesso a essa ferramenta mudou depois do pedido. Avise ${me} em uma frase.`,diff --git a/src/renderer/src/components/ConnectorStore.tsx b/src/renderer/src/components/ConnectorStore.tsxindex aa0a5af..d3dc65d 100644--- a/src/renderer/src/components/ConnectorStore.tsx+++ b/src/renderer/src/components/ConnectorStore.tsx@@ -17,7 +17,7 @@ const light = (hex: string): boolean => {}// Brands without a mark in Simple Icons, or with only a wordmark: their initial, on their color.-const OWN_COLOR: Record<string, string> = { jam: 'FF2D55', monday: '6161FF', granola: '3F6212', canva: '00C4CC', context7: '0F172A', exa: '1F40ED', aave: 'B6509E', coinbase: '0052FF', zapier: 'FF4F00', 'azure-devops': '0078D4', cloudwatch: 'E7157B' }+const OWN_COLOR: Record<string, string> = { jam: 'FF2D55', monday: '6161FF', granola: '3F6212', canva: '00C4CC', context7: '0F172A', exa: '1F40ED', aave: 'B6509E', coinbase: '0052FF', zapier: 'FF4F00', composio: '1A1A1A', 'azure-devops': '0078D4', cloudwatch: 'E7157B' }export function CatalogLogo({ entry, size = 36 }: { entry: CatalogEntry; size?: number }): ReactNode {const logo = LOGOS[entry.id]@@ -59,7 +59,7 @@ export function ConnectorGrid({ status, onManage }: { status: Status; onManage:const connect = (c: CatalogEntry): void => {if (c.app && !apps[c.app.provider]) return setAppSetup({ provider: c.app.provider, then: c })- if (c.fields?.length) return setSetup(c)+ if (c.fields?.length || c.warning) return setSetup(c) // asks something, or says something, firstsetBusy(c.id)setError(null)addConnector(catalogInput(c))@@ -144,7 +144,7 @@ export function ConnectorGrid({ status, onManage }: { status: Status; onManage:</button>)}</h3>- {cat.id === 'google' && !google && <p className="muted small catalog__note">{L('O Google pede um app seu, criado uma vez no Google Cloud: o primeiro Conectar mostra como, em 5 passos. Depois, os cinco entram com um clique.', 'Google asks for an app of your own, made once in Google Cloud: the first Connect shows how, in 5 steps. After that, all five sign in with one click.')}</p>}+ {cat.id === 'google' && !google && <p className="muted small catalog__note">{L('O Google pede um app seu, criado uma vez no Google Cloud: o primeiro Conectar mostra como, em 6 passos. Depois, os cinco entram com um clique.', 'Google asks for an app of your own, made once in Google Cloud: the first Connect shows how, in 6 steps. After that, all five sign in with one click.')}</p>}<div className="catalog__grid">{entries.map((c) => (<div key={c.id} className="catalog__card">@@ -191,8 +191,23 @@ export function ConnectorGrid({ status, onManage }: { status: Status; onManage:)}+// A service that puts its own servers between the agents and the person's accounts says so, in full,+// before connecting and on its page.+export function ThirdPartyWarning({ text }: { text: string }): ReactNode {+ return (+ <div className="warn-box warn-box--third-party" role="note">+ <Icon name="globe" size={16} />+ <span>+ <strong>{L('Seus dados passam por terceiros', 'Your data goes through a third party')}</strong>+ {text}+ </span>+ </div>+ )+}+// What a service asks before connecting: the address of your own instance, a token, an account. The// values go into the connector as the custom form would put them; the secrets, into the system vault.+// A service with a warning opens here too, even with nothing to ask, so it's read before connecting.function ConnectorSetup({ entry, onClose, onAdded }: { entry: CatalogEntry; onClose: () => void; onAdded: (id: string) => void }): ReactNode {const [values, setValues] = useState<Record<string, string>>({})const [error, setError] = useState<string | null>(null)@@ -225,6 +240,7 @@ function ConnectorSetup({ entry, onClose, onAdded }: { entry: CatalogEntry; onCl<CatalogLogo entry={entry} size={40} /><span className="muted small">{entry.about()}</span></div>+ {entry.warning && <ThirdPartyWarning text={entry.warning()} />}{runs && (<p className="warn-box small"><Icon name="terminal" size={14} /> {L(`Roda o servidor oficial neste computador, com o seu usuário: ${runs}.`, `Runs the official server on this computer, as your user: ${runs}.`)}@@ -247,13 +263,17 @@ function ConnectorSetup({ entry, onClose, onAdded }: { entry: CatalogEntry; onCl{error && <p className="note note--error">{error}</p>}<div className="row connector__actions"><span className="small muted grow">- <Icon name="shield" size={12} /> {L('Os segredos ficam cifrados no cofre do sistema.', 'Secrets are encrypted in the system vault.')}+ {entry.fields?.some((f) => f.secret) && (+ <>+ <Icon name="shield" size={12} /> {L('Os segredos ficam cifrados no cofre do sistema.', 'Secrets are encrypted in the system vault.')}+ </>+ )}</span><button type="button" className="btn btn--ghost" onClick={onClose}>{L('Cancelar', 'Cancel')}</button><button type="submit" className="btn btn--primary" disabled={busy}>- {busy ? L('Conectando…', 'Connecting…') : L('Conectar', 'Connect')}+ {busy ? L('Conectando…', 'Connecting…') : entry.warning ? L('Entendi, conectar', 'I understand, connect') : L('Conectar', 'Connect')}</button></div></form>@@ -312,6 +332,13 @@ export function OwnAppSetup({ provider, connecting = false, onClose, onSaved }:{link(cloud(`flows/enableapi?apiid=${GOOGLE_APIS.join(',')}`), L('Ative as APIs', 'Turn on the APIs'))}{L(': com o projeto escolhido no topo, clique em Próxima e em Ativar. São as do Gmail, Drive, Calendar, Docs e Sheets e a MCP de cada um.', ': with the project chosen at the top, click Next and Enable. They are Gmail, Drive, Calendar, Docs and Sheets, and the MCP one of each.')}</li>+ <li>+ {link('https://developers.google.com/workspace/preview', L('Inscreva o projeto no Developer Preview', 'Enroll the project in the Developer Preview'))}+ {L(+ ': os servidores MCP do Google ainda estão em prévia e só atendem projetos inscritos no Google Workspace Developer Preview Program. O formulário pede o número do projeto (no painel do projeto). A aprovação costuma levar uns dias: siga os passos e salve, mas até lá os conectores do Google falham.',+ ": Google's MCP servers are still in preview and only serve projects enrolled in the Google Workspace Developer Preview Program. The form asks for the project number (on the project's dashboard). Approval usually takes a couple of days: go on with the steps and save, but until then the Google connectors fail."+ )}+ </li><li>{link(cloud('auth/overview'), L('Configure a tela de login', 'Set up the sign-in screen'))}{L(@@ -355,6 +382,11 @@ export function OwnAppSetup({ provider, connecting = false, onClose, onSaved }:'In a company workspace, an admin may need to approve the app first: Slack says so at sign-in, and the request goes to them.')}</p>+ {google && (+ <p className="muted small">+ {L('Prefere não configurar? A Composio, na loja, conecta o Google sem isso, mas seus dados passam pelos servidores dela.', "Rather not set this up? Composio, in the store, connects Google without it, but your data goes through its servers.")}+ </p>+ )}{error && <p className="catalog__error small">{error}</p>}<div className="modal__foot"><button className="btn btn--ghost" onClick={onClose}>diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsxindex 9fad871..14115a0 100644--- a/src/renderer/src/components/Conversation.tsx+++ b/src/renderer/src/components/Conversation.tsx@@ -1,4 +1,6 @@import { L, lang, locale } from '../../../shared/lang'+import { actionLabel, innerActions, isRunner } from '../../../shared/composio'+import { runnerRules } from '../../../shared/classify'import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react'import Markdown, { type ExtraProps } from 'react-markdown'import { safeUrl } from '../links'@@ -1213,6 +1215,11 @@ export function ApprovalCard({ approval, compact }: { approval: Approval; compacconst [refusing, setRefusing] = useState(false)const [reason, setReason] = useState('')const summary = argSummary(approval.args)+ // A runner's call (Composio's): the actions it runs are what's being approved.+ const runner = isRunner(approval.tool)+ const actions = runner ? innerActions(approval.tool, approval.args) : undefined+ // What "always allow" covers there: each inner tool that asked, on its own (none for a raw request or code).+ const forGood = runner ? runnerRules(approval.connectorId, approval.tool, approval.args)?.map((r) => r.slice(r.indexOf(':') + 1)) : undefined// Hold to approve: CSS fills the button in 1.5s (.is-holding); the approval goes when// that fill ends while still held. Letting go drains it back. Space or Enter hold too.const [holding, setHolding] = useState(false)@@ -1273,10 +1280,26 @@ export function ApprovalCard({ approval, compact }: { approval: Approval; compac</>)}</div>+ {runner && (+ <div className="approval__args small">+ {actions ? (+ <>+ <p className="muted">{L(`${actions.length === 1 ? 'Ação' : `${actions.length} ações`} que esta chamada roda:`, `${actions.length === 1 ? 'The action' : `${actions.length} actions`} this call runs:`)}</p>+ {actions.map((a, i) => (+ <p key={i}>+ <code>{actionLabel(a)}</code>+ </p>+ ))}+ </>+ ) : (+ <p>{L('Chamada fora do formato documentado: confira os detalhes exatos antes de aprovar.', 'A call outside the documented shape: check the exact details before approving.')}</p>+ )}+ </div>+ )}{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' && summary.shown.length > 0 && (+ {approval.tool !== ACCESS_REQUEST && approval.connectorId !== 'apps' && approval.connectorId !== 'navegador' && !runner && summary.shown.length > 0 && (<div className="approval__args small">{summary.shown.map(([k, v], i) => (<p key={i}>@@ -1357,11 +1380,23 @@ 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' && (+ {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)}>{L('Aprovar e sempre permitir', 'Approve and always allow')}</button>)}+ {forGood && (+ <button+ className="btn"+ title={L(+ `Daqui pra frente ${agent?.name ?? 'o agente'} roda ${forGood.join(', ')} pelo ${approval.connectorName} sem pedir, em qualquer chamada. As outras ações continuam pedindo. Dá pra tirar na página dele.`,+ `From now on ${agent?.name ?? 'the agent'} runs ${forGood.join(', ')} through ${approval.connectorName} without asking, in any call. Other actions still ask. You can take it back on its page.`+ )}+ onClick={() => decideApproval(approval.id, 'approved', undefined, true)}+ >+ {L(`Aprovar e sempre permitir ${forGood.join(', ')}`, `Approve and always allow ${forGood.join(', ')}`)}+ </button>+ )}</>)}<button className="btn" onClick={() => setRefusing(true)}>diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex 93a8002..2f75987 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -74,8 +74,9 @@ import { voiceRefusal } from '../../../shared/voice'import { useVoice, VOICE_CHOICES, VoiceSetup } from './VoiceSetup'import { AccountPicker, AccountsCard, HarnessList, HarnessMcps, ModelPicker, onGateway, OutsideGateway, usableEngines } from './Harness'import { AppsCard } from './Apps'-import { ConnectorGrid, OwnAppSetup } from './ConnectorStore'+import { ConnectorGrid, OwnAppSetup, ThirdPartyWarning } from './ConnectorStore'import { entryOf } from '../../../shared/connector-catalog'+import { perCallTool } from '../../../shared/composio'import { ApprovalCard, QuestionCard, questionDrafts, toolWords } from './Conversation'import { ProposalCard } from './Tuca'import { confirmDialog } from './Dialogs'@@ -1312,8 +1313,8 @@ export function ConnectorsPage(): ReactNode {<Pagetitle={L('Conectores', 'Connectors')}subtitle={L(- 'Os serviços com que seus agentes trabalham. O login é pelo navegador e o acesso fica neste computador; cada chamada dos agentes passa pelas permissões e aprovações.',- 'The services your agents work with. You sign in through the browser and the access stays on this computer; every call the agents make goes through permissions and approvals.'+ 'Os serviços com que seus agentes trabalham. O login é pelo navegador e o acesso fica neste computador (menos nos que passam por terceiros, como a Composio); cada chamada dos agentes passa pelas permissões e aprovações.',+ 'The services your agents work with. You sign in through the browser and the access stays on this computer (except for those that go through a third party, like Composio); every call the agents make goes through permissions and approvals.')}actions={!adding && (@@ -1341,7 +1342,8 @@ export function ConnectorsPage(): ReactNode {// A connector's state, who uses it and its tools, in a window over the page.function ConnectorDetails({ c, onClose }: { c: Connector; onClose: () => void }): ReactNode {const users = useStore((s) => s.agents.filter((a) => (a.grants[c.id] ?? 'none') !== 'none'))- const own = entryOf(c)?.app // signs in with the person's own app: it can be changed here+ const entry = entryOf(c)+ const own = entry?.app // signs in with the person's own app: it can be changed hereconst [changing, setChanging] = useState(false)return (<Modal title={c.name} onClose={onClose} className="connector-modal">@@ -1359,6 +1361,7 @@ function ConnectorDetails({ c, onClose }: { c: Connector; onClose: () => void })L('Nenhum agente usa ainda. Dê acesso na página de cada agente, em Ferramentas.', "No agent uses it yet. Give access on each agent's page, under Tools."))}</p>+ {entry?.warning && <ThirdPartyWarning text={entry.warning()} />}{c.kind === 'stdio' && (<p className="warn-box"><Icon name="terminal" size={14} /> {L('Conector local: roda um processo no seu computador com o seu usuário.', 'Local connector: runs a process on your computer as your user.')}@@ -1409,27 +1412,37 @@ function ConnectorDetails({ c, onClose }: { c: Connector; onClose: () => void })<span>{L('Ligada', 'On')}</span></div>)}- {c.tools.map((t) => (- <div key={t.name} className={`tools__row ${t.enabled ? '' : 'is-off'}`} title={t.description}>- <code>- {t.name}- {t.isNew && <span className="tag tag--warn tools__new">{L('nova', 'new')}</span>}- </code>- <Select- value={t.cls ?? null}- onChange={(v) => { if (v) updateTool(c.id, t.name, { cls: v as ToolClass }) }}- options={(Object.keys(CLASS_LABEL()) as ToolClass[]).map((k) => ({ value: k, label: CLASS_LABEL()[k] }))}- placeholder={L('Escolha a classe', 'Pick a class')}- />- <input- type="checkbox"- disabled={t.cls !== 'sensitive'}- checked={t.highRisk && t.cls === 'sensitive'}- onChange={(e) => updateTool(c.id, t.name, { highRisk: e.target.checked })}- />- <Toggle on={t.enabled} onChange={(v) => updateTool(c.id, t.name, { enabled: v })} />- </div>- ))}+ {c.tools.map((t) => {+ // A runner (Composio's) has no class of its own: each call counts as what it runs.+ const runner = perCallTool(c.url, t.name)+ return (+ <div key={t.name} className={`tools__row ${t.enabled ? '' : 'is-off'}`} title={t.description}>+ <code>+ {t.name}+ {t.isNew && <span className="tag tag--warn tools__new">{L('nova', 'new')}</span>}+ </code>+ {runner ? (+ <span className="small muted" title={L('Leituras rodam na hora; escritas pedem acesso de escrita; ações sensíveis pedem aprovação a cada chamada.', 'Reads run right away; writes need write access; sensitive actions ask for approval on each call.')}>+ {L('por chamada', 'per call')}+ </span>+ ) : (+ <Select+ value={t.cls ?? null}+ onChange={(v) => { if (v) updateTool(c.id, t.name, { cls: v as ToolClass }) }}+ options={(Object.keys(CLASS_LABEL()) as ToolClass[]).map((k) => ({ value: k, label: CLASS_LABEL()[k] }))}+ placeholder={L('Escolha a classe', 'Pick a class')}+ />+ )}+ <input+ type="checkbox"+ disabled={t.cls !== 'sensitive' && !runner}+ checked={t.highRisk && (t.cls === 'sensitive' || runner)}+ onChange={(e) => updateTool(c.id, t.name, { highRisk: e.target.checked })}+ />+ <Toggle on={t.enabled} onChange={(v) => updateTool(c.id, t.name, { enabled: v })} />+ </div>+ )+ })}<p className="hint">{L('Ferramentas novas que o servidor publicar depois entram desligadas até você revisar. Sensíveis sempre pedem aprovação.', 'New tools the server publishes later come in off until you review them. Sensitive ones always ask for approval.')}</p></div>{changing && own && <OwnAppSetup provider={own.provider} onClose={() => setChanging(false)} />}diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex 4edc5f2..2c358aa 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -8318,6 +8318,23 @@ button.wk-pill.is-on { box-shadow: 0 0 0 1.5px var(--k); background: color-mix(i.connector-setup__body .warn-box {margin: 0 0 8px;}+/* A service whose servers sit between the agents and your accounts: a paragraph, not a line, and+ the warn color as its border too, so it can't pass for a hint. */+.warn-box--third-party {+ align-items: flex-start;+ border: 1px solid var(--warn);+ padding: 10px 12px;+ font-size: 13px;+ line-height: 1.45;+}+.warn-box--third-party .icon {+ flex: none;+ margin-top: 2px;+}+.warn-box--third-party strong {+ display: block;+ margin-bottom: 2px;+}/* A connector's details, over the page: the tools scroll, the head stays. */.modal__card.connector-modal {width: min(680px, calc(100vw - 32px));diff --git a/src/shared/classify.ts b/src/shared/classify.tsnew file mode 100644index 0000000..8d3d60c--- /dev/null+++ b/src/shared/classify.ts@@ -0,0 +1,144 @@+// How a connector's tool, or one call of it, is classified: read, write or sensitive. Pure, so the+// core decides with it and the approval card shows what "always allow" would cover.+import { innerActions, perCallTool, PROXY_EXECUTE, type InnerAction } from './composio'+import type { GrantLevel, ToolClass } from './types'++const READ_WORDS = new Set(['get', 'list', 'search', 'read', 'find', 'fetch', 'query', 'describe', 'show', 'view', 'count', 'lookup', 'retrieve'])+const SENSITIVE_WORDS = new Set(['delete', 'remove', 'merge', 'deploy', 'send', 'publish', 'transfer', 'pay', 'destroy', 'drop', 'revoke'])+// Verbs that put something in front of other people. Each is also a noun ("list_messages", "get_comment"),+// so it counts only as the call's verb: the first verb in the name, with no read verb after it.+const OUTBOUND = new Set(['reply', 'post', 'forward', 'invite', 'share', 'comment', 'email', 'message'])+// Verbs that make something: what they make, when it's one of those (create_comment, add_reply,+// save_comment), goes out too; a draft doesn't.+const MAKE = new Set(['create', 'add', 'new', 'write', 'compose', 'submit', 'make', 'save'])+// Other verbs: the first one in the name is the call's verb, so a noun after it is only a noun.+const OTHER_VERBS = new Set(+ 'update set edit modify patch put insert upsert upload download move mark label unlabel assign unassign rename archive unarchive close open reopen star unstar pin unpin react resolve complete toggle enable disable apply attach detach link unlink copy duplicate import export sync generate summarize translate format convert parse schedule cancel start stop run execute restore trash untrash mute unmute block unblock watch unwatch subscribe unsubscribe approve reject lock unlock join leave install uninstall render validate check test preview draft unshare'.split(' ')+)+const PREPOSITIONS = new Set(['to', 'for', 'on', 'in', 'into', 'from', 'with', 'by', 'of', 'at', 'as', 'via'])+// What a made thing is called, plural or not.+const OUTBOUND_THING: Record<string, string> = { replies: 'reply', posts: 'post', invites: 'invite', invitation: 'invite', invitations: 'invite', comments: 'comment', emails: 'email', messages: 'message' }+const thing = (w: string): string => OUTBOUND_THING[w] ?? w++// Tools that run whatever action they're handed (another tool, a request, code), so neither their+// name nor their annotations say what a call does: Composio's, which stand in front of every app's+// real actions. By name they're sensitive; on Composio itself each call is judged by what it runs.+const RUNS_ANY_ACTION = new Set(['composio_multi_execute_tool', 'composio_execute_tool', 'composio_proxy_execute', 'composio_remote_workbench', 'composio_remote_bash_tool'])++// "mergePullRequest" and "merge_pull_request" both become ["merge", "pull", "request"].+export const words = (name: string): string[] =>+ name+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter(Boolean)++// Whether the name's verb, from word `from` on, sends something out: an outbound verb ("post_message",+// "GMAIL_REPLY_TO_THREAD"), or a verb that makes an outbound thing ("create_issue_comment"; not+// "create_email_draft", nor "add_label_to_email", whose thing is the label).+function outbound(w: string[], from: number): boolean {+ const i = w.findIndex((x, k) => k >= from && (READ_WORDS.has(x) || OUTBOUND.has(x) || MAKE.has(x) || OTHER_VERBS.has(x) || SENSITIVE_WORDS.has(x)))+ if (i < 0) return false+ const verb = w[i]!+ if (OUTBOUND.has(verb)) return !w.slice(i + 1).some((x) => READ_WORDS.has(x)) // "email_search" is a search+ if (!MAKE.has(verb) || w.includes('draft')) return false+ const span = w.slice(i + 1)+ const end = span.findIndex((x) => PREPOSITIONS.has(x))+ const made = (end < 0 ? span : span.slice(0, end)).at(-1)+ return !!made && OUTBOUND.has(thing(made))+}++// A tool that runs any action is sensitive; then annotations; then the name. A sensitive word anywhere,+// or an outbound verb, wins over a read verb at the start, since a wrong "read" would skip approval.+export function classify(tool: { name: string; annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean } }): ToolClass {+ if (RUNS_ANY_ACTION.has(tool.name.toLowerCase())) return 'sensitive'+ if (tool.annotations?.readOnlyHint === true) return 'read'+ if (tool.annotations?.destructiveHint === true) return 'sensitive'+ const w = words(tool.name)+ if (w.some((x) => SENSITIVE_WORDS.has(x)) || outbound(w, 0)) return 'sensitive'+ if (w[0] && READ_WORDS.has(w[0])) return 'read'+ return 'write'+}++// The rules before outbound verbs (0.2.15 and earlier). Only to tell, on the first sync after an+// upgrade, a class still automatic (equal to this) from one the person chose by hand.+export function legacyClassify(tool: { name: string; annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean } }): ToolClass {+ if (tool.annotations?.readOnlyHint === true) return 'read'+ if (tool.annotations?.destructiveHint === true) return 'sensitive'+ const w = words(tool.name)+ if (w.some((x) => SENSITIVE_WORDS.has(x))) return 'sensitive'+ if (w[0] && READ_WORDS.has(w[0])) return 'read'+ return 'write'+}++// Whether a grant lets one call of this class run (a sensitive one still asks for approval).+export const permits = (cls: ToolClass, grant: GrantLevel | undefined): boolean => (grant === 'read' ? cls === 'read' : grant === 'read_write')++const RANK: Record<ToolClass, number> = { read: 0, write: 1, sensitive: 2 }+const strictest = (classes: ToolClass[]): ToolClass => classes.reduce((a, b) => (RANK[b] > RANK[a] ? b : a), 'read')++// Words that run code or a workflow: inside a Composio call they're sensitive, like the runners themselves.+const RUNS_CODE = new Set(['execute', 'exec', 'run', 'bash', 'shell', 'eval', 'script'])+// Words in a request that change something, though it goes as a GET (RPC-style APIs: chat.postMessage).+const CHANGE_WORDS = new Set(['post', 'create', 'update', 'set', 'add', 'edit', 'modify', 'write', 'put', 'patch', 'insert', 'upload', 'invite', 'kick', 'archive', 'move', 'rename', 'mark', 'star', 'pin', 'react', 'join', 'leave', 'close', 'open', 'reply', 'forward', 'share', 'approve', 'cancel', 'subscribe', 'unsubscribe', 'trash', 'restore', 'save', 'start', 'stop'])+// Query keys whose value is the operation itself (?action=create).+const OPERATION_KEYS = new Set(['action', 'method', '_method', 'op', 'operation', 'do', 'cmd', 'command', 'mode', 'verb'])++// A Composio tool inside a call that can't be allowed for good: Composio's own (a runner inside a+// runner) or one that runs code.+const neverForGood = (slug: string): boolean => {+ const w = words(slug)+ return w[0] === 'composio' || w.some((x) => RUNS_CODE.has(x))+}++// One action inside a Composio call. A tool's slug starts with its toolkit ("GMAIL_FETCH_EMAILS"),+// so its verb comes after that; a sensitive word anywhere, or an outbound verb, still wins.+export function classifyAction(a: InnerAction): ToolClass {+ if (a.kind === 'tool') {+ const w = words(a.slug)+ if (neverForGood(a.slug) || w.some((x) => SENSITIVE_WORDS.has(x)) || outbound(w, 1)) return 'sensitive'+ return w[1] && READ_WORDS.has(w[1]) ? 'read' : 'write'+ }+ // A raw request: DELETE, or a sensitive word anywhere in it (path, query, headers), is sensitive.+ // GET and HEAD read, unless the path or a parameter's name names a change (a value may be a search:+ // "state=open") or a header overrides the method; the other methods write.+ const said = words([a.toolkit, a.endpoint, ...a.params.flatMap((p) => [p.name, p.value])].join(' '))+ if (a.method === 'DELETE' || a.toolkit.toLowerCase() === 'composio' || said.some((x) => SENSITIVE_WORDS.has(x) || RUNS_CODE.has(x))) return 'sensitive'+ if (a.method !== 'GET' && a.method !== 'HEAD') return 'write'+ // The query in the endpoint counts like the query parameters; a value counts when its key names an operation.+ const [path = '', query = ''] = a.endpoint.split('?')+ const pairs = [...new URLSearchParams(query)].map(([name, value]) => ({ name, value })).concat(a.params)+ const named = words([path, ...pairs.flatMap((p) => (OPERATION_KEYS.has(p.name.toLowerCase()) ? [p.name, p.value] : [p.name]))].join(' '))+ const override = a.params.some((p) => p.type === 'header' && /method|override/i.test(p.name))+ return override || named.some((x) => CHANGE_WORDS.has(x)) ? 'write' : 'read'+}++// The class of one call: a runner judged on each call takes the strictest of what it runs, and a call+// whose arguments aren't understood is sensitive; any other tool keeps its own class.+export function callClass(tool: { name: string; cls: ToolClass }, connectorUrl: string | undefined, args: Record<string, unknown>): ToolClass {+ if (!perCallTool(connectorUrl, tool.name)) return tool.cls+ const actions = innerActions(tool.name, args)+ if (!actions) return 'sensitive'+ const cls = strictest(actions.map(classifyAction))+ // A request with a body but read by its method would send that body: not a read.+ return cls === 'read' && 'body' in args && args['body'] !== undefined && args['body'] !== null ? 'write' : cls+}++// "Always allow" on a runner's call: one rule per inner tool that asked for approval, keyed by the+// connector and that tool's slug ("<connector>:GMAIL_REPLY_TO_THREAD"), never by the runner. Undefined+// when any of them can't be allowed for good: a raw request, a call not understood, Composio's own+// tools or code.+export function runnerRules(connectorId: string, toolName: string, args: Record<string, unknown>): string[] | undefined {+ if (toolName === PROXY_EXECUTE) return undefined+ const actions = innerActions(toolName, args)+ if (!actions) return undefined+ const asking = actions.filter((a) => classifyAction(a) === 'sensitive')+ if (!asking.length || asking.some((a) => a.kind !== 'tool' || neverForGood(a.slug))) return undefined+ return [...new Set(asking.map((a) => `${connectorId}:${(a as { slug: string }).slug.toUpperCase()}`))]+}++// A runner's call runs without asking only when every inner tool that would ask is allowed for good.+export const runnerAllowed = (connectorId: string, toolName: string, args: Record<string, unknown>, rules: string[]): boolean => {+ const need = runnerRules(connectorId, toolName, args)+ return !!need && need.every((r) => rules.includes(r))+}diff --git a/src/shared/composio.ts b/src/shared/composio.tsnew file mode 100644index 0000000..7e8640e--- /dev/null+++ b/src/shared/composio.ts@@ -0,0 +1,65 @@+// Composio's tools that run other actions: what one call runs, read from its arguments, so the call is+// judged by that and not by the runner's name. Shapes from docs.composio.dev/toolkits/meta-tools+// (multi_execute_tool, proxy_execute); anything else, an extra field included, isn't understood, and a+// call that isn't understood is sensitive.++export const MULTI_EXECUTE = 'COMPOSIO_MULTI_EXECUTE_TOOL'+export const EXECUTE = 'COMPOSIO_EXECUTE_TOOL' // the older single one: tool_slug and arguments at the top+export const PROXY_EXECUTE = 'COMPOSIO_PROXY_EXECUTE'+const RUNNERS = new Set([MULTI_EXECUTE, EXECUTE, PROXY_EXECUTE])++// One action a call runs: an app's tool by its slug ("GMAIL_FETCH_EMAILS"), or a raw request to an app's API.+export type InnerAction = { kind: 'tool'; slug: string } | { kind: 'http'; toolkit: string; method: string; endpoint: string; params: { name: string; value: string; type: string }[] }++export const isComposio = (url: string | undefined): boolean => {+ try {+ const u = new URL(url ?? '')+ return u.protocol === 'https:' && /(^|\.)composio\.dev$/i.test(u.hostname)+ } catch {+ return false+ }+}++// A runner whose every call is judged by what it runs: only on Composio's own servers, by its exact name.+export const perCallTool = (url: string | undefined, name: string): boolean => isComposio(url) && RUNNERS.has(name)+// The same by name only, for the approval card, which shows what a call runs.+export const isRunner = (name: string): boolean => RUNNERS.has(name)++const SLUG = /^[A-Za-z0-9]+(?:_[A-Za-z0-9]+)+$/ // TOOLKIT_ACTION: letters, digits, single underscores+const METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'])+// What the runners take besides the actions themselves: notes about the workflow, never an action.+const NOTES: Record<string, 'string' | 'boolean'> = { thought: 'string', current_step: 'string', current_step_metric: 'string', session_id: 'string', sync_response_to_workbench: 'boolean' }++const plainObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype+// Only these keys, and the notes with their types.+const only = (o: Record<string, unknown>, keys: string[]): boolean => Object.entries(o).every(([k, v]) => keys.includes(k) || (k in NOTES && typeof v === NOTES[k]))+const toolOf = (o: unknown): InnerAction | undefined =>+ plainObject(o) && only(o, ['tool_slug', 'arguments']) && typeof o['tool_slug'] === 'string' && SLUG.test(o['tool_slug']) && plainObject(o['arguments']) ? { kind: 'tool', slug: o['tool_slug'] } : undefined++// What a runner's call runs; undefined when its arguments aren't one of the documented shapes.+export function innerActions(name: string, args: unknown): InnerAction[] | undefined {+ if (!plainObject(args)) return undefined+ if (name === MULTI_EXECUTE) {+ const tools = args['tools']+ if (!only(args, ['tools']) || !Array.isArray(tools) || tools.length === 0 || tools.length > 50) return undefined+ const actions = tools.map(toolOf)+ return actions.every(Boolean) ? (actions as InnerAction[]) : undefined+ }+ if (name === EXECUTE) {+ const { tool_slug, arguments: a, ...rest } = args+ const action = only(rest, []) ? toolOf({ tool_slug, arguments: a }) : undefined+ return action ? [action] : undefined+ }+ if (name === PROXY_EXECUTE) {+ const { toolkit_slug: toolkit, endpoint, method, parameters = [] } = args+ if (!only(args, ['toolkit_slug', 'endpoint', 'method', 'body', 'parameters'])) return undefined+ if (typeof toolkit !== 'string' || !/^[A-Za-z0-9_]+$/.test(toolkit) || typeof endpoint !== 'string' || typeof method !== 'string' || !METHODS.has(method) || !Array.isArray(parameters)) return undefined+ const params = parameters.map((p) => (plainObject(p) && only(p, ['name', 'value', 'type']) && typeof p['name'] === 'string' && typeof p['value'] === 'string' && (p['type'] === 'header' || p['type'] === 'query') ? { name: p['name'], value: p['value'], type: p['type'] } : undefined))+ if (!params.every(Boolean)) return undefined+ return [{ kind: 'http', toolkit, method, endpoint, params: params as { name: string; value: string; type: string }[] }]+ }+ return undefined+}++// "GMAIL_SEND_EMAIL" or "GET github /user/repos", for the approval card.+export const actionLabel = (a: InnerAction): string => (a.kind === 'tool' ? a.slug : `${a.method} ${a.toolkit} ${a.endpoint}`)diff --git a/src/shared/connector-catalog.ts b/src/shared/connector-catalog.tsindex c4136bc..9f34114 100644--- a/src/shared/connector-catalog.ts+++ b/src/shared/connector-catalog.ts@@ -32,6 +32,7 @@ export interface CatalogEntry {local?: { command: string; args: string[]; env?: Record<string, string> } // runs on this computerfields?: CatalogField[]app?: { provider: AppProvider; scopes: string[] } // signs in with the person's own app, asking for these scopes+ warning?: () => string // said before connecting and on its page: the data goes through someone else's servers}// Whose sign-in needs an app the person makes: Google's (one for its five servers) and Slack's.@@ -192,6 +193,16 @@ export const CATALOG: CatalogEntry[] = []}),e('zapier', 'Zapier', 'https://mcp.zapier.com/api/mcp/mcp', 'business', 'Ações em milhares de apps', 'Actions across thousands of apps'),+ // Composio Connect: hundreds of apps through Composio's servers, which hold the sign-in to each account+ // and see every call. It offers a handful of tools that find and run the real actions, so each run+ // asks for approval (see policy.ts).+ e('composio', 'Composio', 'https://connect.composio.dev/mcp', 'business', 'Seus dados passam pela Composio · centenas de apps sem configurar nada', 'Your data goes through Composio · hundreds of apps with nothing to set up', 'oauth', {+ warning: () =>+ L(+ 'Pela Composio, seus dados passam pelos servidores dela: e-mails, planilhas e o que mais os agentes acessarem. O acesso às suas contas (Google, Notion…) fica guardado com a Composio, não no seu computador. O Tucano não controla o que ela guarda nem por quanto tempo. Se preferir que nada passe por terceiros, use os conectores diretos.',+ "Through Composio, your data goes through its servers: emails, spreadsheets and whatever else the agents reach. The access to your accounts (Google, Notion…) is kept by Composio, not on your computer. Tucano doesn't control what it keeps or for how long. If you'd rather nothing go through a third party, use the direct connectors."+ )+ }),e('canva', 'Canva', 'https://mcp.canva.com/mcp', 'design', 'Designs, modelos e exportações', 'Designs, templates and exports'),e('webflow', 'Webflow', 'https://mcp.webflow.com/mcp', 'design', 'Sites, páginas e CMS', 'Sites, pages and CMS'),diff --git a/test/composio-calls.test.ts b/test/composio-calls.test.tsnew file mode 100644index 0000000..5b6f7a7--- /dev/null+++ b/test/composio-calls.test.ts@@ -0,0 +1,354 @@+// Composio's runners (COMPOSIO_MULTI_EXECUTE_TOOL and the like) run whatever action they're handed, so+// each call counts as what it runs: reads go through on a read grant, a send asks for approval, anything+// not understood is sensitive. The rules, then the runner with a scripted model and a stand-in server.+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { Client } from '@modelcontextprotocol/sdk/client/index.js'+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'+import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { innerActions, isComposio, MULTI_EXECUTE, perCallTool, PROXY_EXECUTE } from '../src/shared/composio'+import type { Agent, Connector, GrantLevel, Settings } from '../src/shared/types'+import { callClass, classify, classifyAction, runnerAllowed, runnerRules } from '../src/core/policy'+import { Db } from '../src/core/db'+import { fakeEngine } from '../src/core/engines/fake'+import type { Engine, Turn } from '../src/core/engines/types'+import { Gateway } from '../src/core/gateway'+import { Runner } from '../src/core/runs'++const URL_ = 'https://connect.composio.dev/mcp'+const multi = { name: MULTI_EXECUTE, cls: classify({ name: MULTI_EXECUTE }) }+const batch = (...slugs: string[]): Record<string, unknown> => ({ tools: slugs.map((tool_slug) => ({ tool_slug, arguments: {} })), sync_response_to_workbench: false })+const proxy = (method: string, endpoint = '/user/repos', more: Record<string, unknown> = {}): Record<string, unknown> => ({ toolkit_slug: 'github', endpoint, method, ...more })+const of = (args: unknown, name = MULTI_EXECUTE): string => callClass({ name, cls: 'sensitive' }, URL_, args as Record<string, unknown>)++describe('what a Composio call runs, and its class', () => {+ it('reads the slugs, skipping the toolkit for the read verb, with a sensitive word anywhere winning', () => {+ expect(of(batch('GMAIL_FETCH_EMAILS', 'GOOGLESHEETS_GET_SPREADSHEET_INFO', 'NOTION_SEARCH_NOTION_PAGE'))).toBe('read')+ expect(of(batch('GMAIL_CREATE_EMAIL_DRAFT'))).toBe('write')+ expect(of(batch('GMAIL_SEND_EMAIL'))).toBe('sensitive')+ expect(of(batch('GMAIL_FETCH_AND_DELETE_EMAILS'))).toBe('sensitive') // a read verb first doesn't save it+ expect(of(batch('gmail_fetch_emails'))).toBe('read') // same words, whatever the case+ expect(of(batch('FETCH_GMAIL_SEND'))).toBe('sensitive')+ expect(of(batch('GET_ISSUES'))).toBe('write') // "GET" is the toolkit here: no read verb after it+ })++ it('takes the strictest action in a batch', () => {+ expect(of(batch('GMAIL_FETCH_EMAILS', 'GMAIL_CREATE_EMAIL_DRAFT'))).toBe('write')+ expect(of(batch('GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'))).toBe('sensitive')+ })++ it("treats Composio's own tools and code runners inside a call as sensitive", () => {+ expect(of(batch('COMPOSIO_REMOTE_BASH_TOOL'))).toBe('sensitive')+ expect(of(batch('COMPOSIO_SEARCH_TOOLS'))).toBe('sensitive')+ expect(of(batch('CODEINTERPRETER_EXECUTE_CODE'))).toBe('sensitive')+ expect(of(batch('GITHUB_RUN_WORKFLOW'))).toBe('sensitive')+ })++ it('fails closed on anything but the documented shape', () => {+ for (const bad of [+ undefined,+ {},+ { tools: [] },+ { tools: 'GMAIL_FETCH_EMAILS' },+ { tools: JSON.stringify([{ tool_slug: 'GMAIL_FETCH_EMAILS', arguments: {} }]) }, // a JSON string, not the list+ { tools: [[{ tool_slug: 'GMAIL_FETCH_EMAILS', arguments: {} }]] }, // nested+ { tools: [{ tool_slug: 'GMAIL_FETCH_EMAILS' }] }, // no arguments+ { tools: [{ tool_slug: 'GMAIL_FETCH_EMAILS', arguments: '{}' }] },+ { tools: [{ tool_slug: 'GMAIL_FETCH_EMAILS', arguments: {}, tool: 'GMAIL_SEND_EMAIL' }] }, // an extra field+ { tools: [{ tool_slug: 'GMAIL_FETCH_EMAILS', arguments: {} }], then: 'GMAIL_SEND_EMAIL' },+ { tools: [{ tool_slug: 'GMAIL_FETCH_EMAILS', arguments: {} }], thought: { tool_slug: 'GMAIL_SEND_EMAIL' } }, // a note that isn't one+ { tools: [{ tool_slug: 'GMAIL', arguments: {} }] }, // no action in it+ { tools: [{ tool_slug: ' GMAIL_FETCH_EMAILS', arguments: {} }] },+ { tools: [{ tool_slug: 'GMAIL_FETCH_EMAİLS', arguments: {} }] }, // a look-alike letter+ { tools: [{ tool_slug: 'GMAIL__FETCH_EMAILS', arguments: {} }] },+ { tools: [{ tool_slug: 'GMAIL_FETCH_EMAILS,GMAIL_SEND_EMAIL', arguments: {} }] },+ { tools: [{ tool_slug: 42, arguments: {} }] },+ { tools: Array.from({ length: 51 }, () => ({ tool_slug: 'GMAIL_FETCH_EMAILS', arguments: {} })) }+ ])+ expect(of(bad), JSON.stringify(bad)).toBe('sensitive')+ expect(innerActions(MULTI_EXECUTE, { tools: [{ tool_slug: 'X_GET_Y', arguments: {} }], thought: 'why', current_step: 'FETCHING', session_id: 's1' })).toEqual([{ kind: 'tool', slug: 'X_GET_Y' }])+ })++ it('judges the older single runner the same way', () => {+ expect(of({ tool_slug: 'GMAIL_FETCH_EMAILS', arguments: {} }, 'COMPOSIO_EXECUTE_TOOL')).toBe('read')+ expect(of({ tool_slug: 'GMAIL_SEND_EMAIL', arguments: {} }, 'COMPOSIO_EXECUTE_TOOL')).toBe('sensitive')+ expect(of({ tool_slug: 'GMAIL_FETCH_EMAILS' }, 'COMPOSIO_EXECUTE_TOOL')).toBe('sensitive')+ })++ it('judges a raw request by its method, and a GET that names a change as a write', () => {+ expect(of(proxy('GET'), PROXY_EXECUTE)).toBe('read')+ expect(of(proxy('HEAD'), PROXY_EXECUTE)).toBe('read')+ expect(of(proxy('GET', '/repos/a/b/issues?state=open'), PROXY_EXECUTE)).toBe('read') // a value is a search, not a change+ expect(of(proxy('POST'), PROXY_EXECUTE)).toBe('write')+ expect(of(proxy('PATCH'), PROXY_EXECUTE)).toBe('write')+ expect(of(proxy('DELETE'), PROXY_EXECUTE)).toBe('sensitive')+ expect(of(proxy('GET', '/api/chat.postMessage'), PROXY_EXECUTE)).toBe('write') // RPC over GET+ expect(of(proxy('GET', '/api/chat.delete'), PROXY_EXECUTE)).toBe('sensitive')+ expect(of(proxy('GET', '/x', { parameters: [{ name: 'X-HTTP-Method-Override', value: 'DELETE', type: 'header' }] }), PROXY_EXECUTE)).toBe('sensitive')+ expect(of(proxy('GET', '/x', { parameters: [{ name: 'X-HTTP-Method-Override', value: 'PUT', type: 'header' }] }), PROXY_EXECUTE)).toBe('write')+ expect(of(proxy('GET', '/x', { body: { a: 1 } }), PROXY_EXECUTE)).toBe('write')+ expect(of(proxy('GET', '/legacy?action=create&id=1'), PROXY_EXECUTE)).toBe('write') // the operation in a query value+ expect(of(proxy('GET', '/legacy', { parameters: [{ name: 'Op', value: 'post', type: 'query' }] }), PROXY_EXECUTE)).toBe('write')+ expect(of(proxy('GET', '/x?then=remove'), PROXY_EXECUTE)).toBe('sensitive') // a sensitive word anywhere+ expect(of(proxy('GET', '/v1/tools', { toolkit_slug: 'composio' }), PROXY_EXECUTE)).toBe('sensitive') // Composio's own API+ expect(of(proxy('GET', '/x', { toolkit_slug: 'git hub' }), PROXY_EXECUTE)).toBe('sensitive')+ expect(of(proxy('get'), PROXY_EXECUTE)).toBe('sensitive') // not a documented method+ expect(of(proxy('GET', '/x', { parameters: [{ name: 'q', value: 'a', type: 'cookie' }] }), PROXY_EXECUTE)).toBe('sensitive')+ expect(of(proxy('GET', '/x', { extra: 1 }), PROXY_EXECUTE)).toBe('sensitive')+ })++ it('applies only to the runners on Composio itself; elsewhere, those names stay sensitive', () => {+ expect(isComposio(URL_)).toBe(true)+ expect(isComposio('https://backend.composio.dev/tool_router/x/mcp')).toBe(true)+ expect(isComposio('https://composio.dev.evil.com/mcp')).toBe(false)+ expect(isComposio('http://connect.composio.dev/mcp')).toBe(false)+ expect(perCallTool(URL_, 'COMPOSIO_REMOTE_BASH_TOOL')).toBe(false) // code: always sensitive+ expect(perCallTool(URL_, 'composio_multi_execute_tool')).toBe(false) // only the exact name+ expect(callClass(multi, 'https://mcp.example.com/mcp', batch('GMAIL_FETCH_EMAILS'))).toBe('sensitive')+ expect(callClass({ name: 'list_issues', cls: 'read' }, URL_, {})).toBe('read') // any other tool keeps its class+ expect(classifyAction({ kind: 'tool', slug: 'SLACK_LIST_CHANNELS' })).toBe('read')+ })+})++// ---- Through the runner ----++const ready = { installed: true, loggedIn: true }+type Plan = { tool: string; args: Record<string, unknown> } | null+let dir: string+let db: Db+let gateway: Gateway+let settings: Settings+let calls: { name: string; args: Record<string, unknown> }[]+let seen: { prompts: string[]; tools: string[][]; results: CallToolResult[] }+const CID = 'cmp'+const SID = 'slk' // a direct connector, for the outbound defaults++const composio = (): Connector => ({ id: CID, name: 'Composio', kind: 'remote', url: URL_, auth: 'oauth', status: 'connected', tools: db.tools(CID) })+const agent = (grant: GrantLevel, autoApprove: string[] = []): Agent => ({+ id: 'a1', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low',+ limit: 1_000_000, used: 0, grants: { [CID]: grant, [SID]: grant }, memory: 'auto', computer: false, archived: false, autoApprove+})++function scripted(plan: (prompt: string, tools: string[]) => Plan): Engine {+ return {+ id: 'claude',+ async *run(turn: Turn) {+ seen.prompts.push(turn.prompt)+ 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.map((t) => t.name)+ seen.tools.push(tools)+ const p = plan(turn.prompt, tools)+ if (p) seen.results.push((await client.callTool({ name: p.tool, arguments: p.args })) as CallToolResult)+ await client.close()+ }+ yield { type: 'text', delta: 'ok' }+ yield { type: 'done', text: 'ok', usage: { inputTokens: 10, cacheReadTokens: 0, outputTokens: 2 } }+ }+ }+}++function runner(plan: (prompt: string, tools: string[]) => Plan): Runner {+ return new Runner({+ db,+ engines: { claude: scripted(plan), codex: fakeEngine('codex'), 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: {+ list: () => [composio(), { id: SID, name: 'Slack', kind: 'remote', url: 'https://mcp.slack.com/mcp', auth: 'oauth', status: 'connected', tools: db.tools(SID) }],+ call: async (_id, name, args) => (calls.push({ name, args }), { content: [{ type: 'text', text: `ran ${name}` }] })+ }+ })+}++const once = (args: Record<string, unknown>) => (prompt: string, tools: string[]): Plan =>+ prompt.includes('aprovou') || prompt.includes('recusou') ? null : { tool: tools.find((t) => t.endsWith(`__${MULTI_EXECUTE}`)) ?? `composio__${MULTI_EXECUTE}`, args }+const textOf = (r: CallToolResult | undefined): string => (r?.content[0] as { text?: string } | undefined)?.text ?? ''++beforeEach(async () => {+ dir = mkdtempSync(join(tmpdir(), 'ad-composio-'))+ db = new Db(join(dir, 'test.db'))+ calls = []+ seen = { prompts: [], tools: [], results: [] }+ 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' }+ gateway = new Gateway()+ await gateway.start()+ db.saveConnector({ id: CID, name: 'Composio', kind: 'remote', url: URL_, auth: 'oauth' })+ const schema = { type: 'object', properties: {} }+ db.syncTools(CID, [+ { name: MULTI_EXECUTE, description: 'Runs tools.', inputSchema: schema, cls: classify({ name: MULTI_EXECUTE, annotations: { destructiveHint: true } }) },+ { name: 'COMPOSIO_SEARCH_TOOLS', description: 'Finds tools.', inputSchema: schema, cls: classify({ name: 'COMPOSIO_SEARCH_TOOLS', annotations: { readOnlyHint: true } }) },+ { name: 'COMPOSIO_REMOTE_BASH_TOOL', description: 'Runs bash.', inputSchema: schema, cls: classify({ name: 'COMPOSIO_REMOTE_BASH_TOOL' }) }+ ])+ db.saveConnector({ id: SID, name: 'Slack', kind: 'remote', url: 'https://mcp.slack.com/mcp', auth: 'oauth' })+ db.syncTools(SID, ['chat_post_message', 'conversations_history'].map((name) => ({ name, description: name, inputSchema: schema, cls: classify({ name }) })))+ db.saveAgent(agent('none'))+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })+})++afterEach(async () => {+ await gateway.stop()+})++describe('a Composio call through the runner', () => {+ it('a read grant sees the runner (not bash) and runs a batch of reads right away', async () => {+ db.saveAgent(agent('read'))+ const r = runner(once(batch('GMAIL_FETCH_EMAILS', 'GOOGLESHEETS_GET_SPREADSHEET_INFO')))+ await r.send('d1', 'lê meus e-mails')+ await r.idle()+ expect(seen.tools[0]).toEqual(expect.arrayContaining([`composio__${MULTI_EXECUTE}`, 'composio__COMPOSIO_SEARCH_TOOLS']))+ expect(seen.tools[0]!.some((t) => t.includes('BASH'))).toBe(false)+ expect(calls).toEqual([{ name: MULTI_EXECUTE, args: batch('GMAIL_FETCH_EMAILS', 'GOOGLESHEETS_GET_SPREADSHEET_INFO') }])+ expect(db.approvals()).toHaveLength(0)+ expect(db.messages().find((m) => m.author.kind === 'agent')?.run?.steps.map((s) => s.label)).toContain('Consultou')+ })++ it('a read grant is refused a write inside the batch, and nothing runs', async () => {+ db.saveAgent(agent('read'))+ const r = runner(once(batch('GMAIL_FETCH_EMAILS', 'GMAIL_CREATE_EMAIL_DRAFT')))+ await r.send('d1', 'rascunha')+ await r.idle()+ expect(seen.results[0]).toMatchObject({ isError: true })+ expect(textOf(seen.results[0])).toContain('leitura e escrita')+ expect(calls).toHaveLength(0)+ expect(db.approvals()).toHaveLength(0)+ })++ it('read_write: a write runs; a batch mixing a read and a send asks for approval with exactly its arguments', async () => {+ db.saveAgent(agent('read_write'))+ const w = runner(once(batch('GMAIL_CREATE_EMAIL_DRAFT')))+ await w.send('d1', 'rascunha')+ await w.idle()+ expect(calls).toHaveLength(1)+ expect(db.approvals()).toHaveLength(0)+ calls = []+ const args = { ...batch('GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'), _motivo: 'responder o cliente' }+ const r = runner(once(args))+ await r.send('d1', 'responde')+ await r.idle()+ expect(calls).toHaveLength(0)+ const [ap] = db.approvals()+ expect(ap).toMatchObject({ state: 'pending', tool: MULTI_EXECUTE, args: batch('GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'), why: 'responder o cliente' })+ await r.decide(ap!.id, 'approved')+ await r.idle()+ expect(calls).toEqual([{ name: MULTI_EXECUTE, args: batch('GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL') }]) // the stored call, as approved+ })++ it('an unknown or malformed call asks for approval instead of running', async () => {+ db.saveAgent(agent('read_write'))+ const r = runner(once({ tools: JSON.stringify([{ tool_slug: 'GMAIL_FETCH_EMAILS', arguments: {} }]) }))+ await r.send('d1', 'lê')+ await r.idle()+ expect(calls).toHaveLength(0)+ expect(db.approvals()[0]).toMatchObject({ state: 'pending', tool: MULTI_EXECUTE })+ })++ it('"always allow" never sticks to the runner itself, even a rule for it already there', async () => {+ db.saveAgent(agent('read_write', [`${CID}:${MULTI_EXECUTE}`])) // even if it got there somehow+ const r = runner(once(batch('GMAIL_SEND_EMAIL')))+ await r.send('d1', 'manda')+ await r.idle()+ expect(calls).toHaveLength(0)+ expect(db.approvals()[0]?.state).toBe('pending')+ })++ it('"always allow" on a batch allows each inner tool that asked, on its own, for this agent', async () => {+ db.saveAgent(agent('read_write'))+ // One batch per message, in order (a prompt carries the history, so it goes by count).+ const plans = [batch('GMAIL_FETCH_EMAILS', 'GMAIL_REPLY_TO_THREAD'), batch('gmail_reply_to_thread', 'GMAIL_FETCH_EMAILS'), batch('GMAIL_REPLY_TO_THREAD', 'GMAIL_SEND_EMAIL')]+ const r = runner((prompt, tools) => (prompt.includes('aprovou') ? null : { tool: tools.find((t) => t.endsWith(`__${MULTI_EXECUTE}`))!, args: plans.shift()! }))+ await r.send('d1', 'primeira')+ await r.idle()+ const ap = db.approvals()[0]!+ await r.decide(ap.id, 'approved', undefined, true)+ await r.idle()+ expect(db.agent('a1')?.autoApprove).toEqual([`${CID}:GMAIL_REPLY_TO_THREAD`]) // the inner tool, not the runner+ expect(calls).toHaveLength(1)++ await r.send('d1', 'segunda')+ await r.idle()+ expect(calls).toHaveLength(2) // ran without asking+ expect(db.approvals()).toHaveLength(1)++ await r.send('d1', 'terceira') // a reply and a send: the send still asks, so the whole call does+ await r.idle()+ expect(calls).toHaveLength(2)+ expect(db.approvals().filter((a) => a.state === 'pending')).toHaveLength(1)+ })++ it('a raw request, a call not understood, code and a high-risk runner are never allowed for good', async () => {+ const rules = [`${CID}:GMAIL_SEND_EMAIL`, `${CID}:COMPOSIO_REMOTE_BASH_TOOL`, `${CID}:${PROXY_EXECUTE}`]+ expect(runnerRules(CID, PROXY_EXECUTE, proxy('DELETE'))).toBeUndefined()+ expect(runnerRules(CID, MULTI_EXECUTE, { tools: 'GMAIL_SEND_EMAIL' })).toBeUndefined()+ expect(runnerRules(CID, MULTI_EXECUTE, batch('GMAIL_SEND_EMAIL', 'COMPOSIO_REMOTE_BASH_TOOL'))).toBeUndefined()+ expect(runnerRules(CID, MULTI_EXECUTE, batch('GMAIL_SEND_EMAIL', 'CODEINTERPRETER_EXECUTE_CODE'))).toBeUndefined()+ expect(runnerRules(CID, MULTI_EXECUTE, batch('GMAIL_FETCH_EMAILS'))).toBeUndefined() // nothing to allow+ expect(runnerAllowed(CID, MULTI_EXECUTE, batch('GMAIL_SEND_EMAIL', 'COMPOSIO_REMOTE_BASH_TOOL'), rules)).toBe(false)+ expect(runnerAllowed(CID, PROXY_EXECUTE, proxy('DELETE'), rules)).toBe(false)+ expect(runnerAllowed(CID, MULTI_EXECUTE, batch('GMAIL_SEND_EMAIL'), rules)).toBe(true)+ expect(runnerAllowed('other', MULTI_EXECUTE, batch('GMAIL_SEND_EMAIL'), rules)).toBe(false) // per connector++ // High risk on the runner: an allowed action still asks, and "always" adds nothing.+ db.saveAgent(agent('read_write', [`${CID}:GMAIL_SEND_EMAIL`]))+ db.updateTool(CID, MULTI_EXECUTE, { highRisk: true })+ const r = runner(once(batch('GMAIL_SEND_EMAIL')))+ await r.send('d1', 'manda')+ await r.idle()+ expect(calls).toHaveLength(0)+ const ap = db.approvals()[0]!+ expect(ap).toMatchObject({ state: 'pending', highRisk: true })+ db.saveAgent(agent('read_write'))+ await r.decide(ap.id, 'approved', undefined, true)+ await r.idle()+ expect(db.agent('a1')?.autoApprove ?? []).toEqual([])+ })++ it('an approved call whose grant dropped to read no longer runs a send', async () => {+ db.saveAgent(agent('read_write'))+ const r = runner(once(batch('GMAIL_SEND_EMAIL')))+ await r.send('d1', 'manda')+ await r.idle()+ db.saveAgent(agent('read'))+ await r.decide(db.approvals()[0]!.id, 'approved')+ await r.idle()+ expect(calls).toHaveLength(0)+ expect(db.approvals()[0]?.outcome).toMatch(/Não executou/)+ })+})++describe('sends and posts ask by default, and the person can change that', () => {+ const post = (prompt: string, tools: string[]): Plan => (prompt.includes('aprovou') ? null : { tool: tools.find((t) => t.endsWith('__chat_post_message'))!, args: { channel: 'C1', text: 'oi' } })++ it('a post asks; "always allow" then lets this agent post without asking', async () => {+ db.saveAgent(agent('read_write'))+ expect(db.tools(SID).find((t) => t.name === 'chat_post_message')?.cls).toBe('sensitive')+ const r = runner(post)+ await r.send('d1', 'avisa no canal')+ await r.idle()+ expect(calls).toHaveLength(0)+ await r.decide(db.approvals()[0]!.id, 'approved', undefined, true)+ await r.idle()+ expect(db.agent('a1')?.autoApprove).toEqual([`${SID}:chat_post_message`])+ await r.send('d1', 'avisa de novo')+ await r.idle()+ expect(calls).toHaveLength(2)+ expect(db.approvals()).toHaveLength(1)+ })++ it('a post set to "write" by hand runs right away, and stays so when the tools are refreshed', async () => {+ db.saveAgent(agent('read_write'))+ db.updateTool(SID, 'chat_post_message', { cls: 'write' })+ db.syncTools(SID, ['chat_post_message', 'conversations_history'].map((name) => ({ name, description: name, inputSchema: { type: 'object', properties: {} }, cls: classify({ name }) })))+ expect(db.tools(SID).find((t) => t.name === 'chat_post_message')?.cls).toBe('write')+ const r = runner(post)+ await r.send('d1', 'avisa no canal')+ await r.idle()+ expect(calls).toHaveLength(1)+ expect(db.approvals()).toHaveLength(0)+ })+})diff --git a/test/connector-catalog.test.ts b/test/connector-catalog.test.tsindex b63c9b3..e260453 100644--- a/test/connector-catalog.test.ts+++ b/test/connector-catalog.test.ts@@ -4,7 +4,7 @@ import { LOGOS } from '../src/renderer/src/connector-logos'describe('the connector catalog', () => {it('lists each service once, at an https address, in a category that exists', () => {- expect(CATALOG.length).toBe(47)+ expect(CATALOG.length).toBe(48)expect(new Set(CATALOG.map((c) => c.id)).size).toBe(CATALOG.length)const remote = CATALOG.filter((c) => !c.local)expect(new Set(remote.map((c) => c.url)).size).toBe(remote.length)@@ -75,6 +75,16 @@ describe('the connector catalog', () => {expect(entryOf({ kind: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-postgres'] })).toBeUndefined()})+ it('warns, before connecting, when the data goes through a third party', () => {+ const composio = CATALOG.find((c) => c.id === 'composio')!+ expect(catalogInput(composio)).toEqual({ name: 'Composio', kind: 'remote', url: 'https://connect.composio.dev/mcp', auth: 'oauth' })+ expect(composio.about()).toMatch(/Composio/) // on the card, too+ expect(composio.warning?.()).toMatch(/Composio/)+ expect(searchCatalog('composio').map((c) => c.id)).toEqual(['composio'])+ // Only the ones that go through someone else's servers say so.+ expect(CATALOG.filter((c) => c.warning).map((c) => c.id)).toEqual(['composio'])+ })+it("signs in to Google's five with the person's app, asking only what their tools need", () => {const google = CATALOG.filter((c) => c.app?.provider === 'google')expect(google.map((c) => c.id)).toEqual(['gmail', 'google-calendar', 'google-drive', 'google-docs', 'google-sheets'])diff --git a/test/connector-classes.test.ts b/test/connector-classes.test.tsnew file mode 100644index 0000000..93ab608--- /dev/null+++ b/test/connector-classes.test.ts@@ -0,0 +1,50 @@+// A tool's class follows the rules while it's automatic, and stays as the person set it once they+// chose one by hand: on a refresh, and on the first sync after an upgrade that changed the rules+// (sends and posts became sensitive), when the database doesn't yet know which classes were automatic.+import { mkdtempSync } from 'node:fs'+import { DatabaseSync } from 'node:sqlite'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { Db } from '../src/core/db'+import { classify, legacyClassify } from '../src/core/policy'++const schema = { type: 'object', properties: {} }+const listed = (names: string[]) => names.map((name) => ({ name, description: name, inputSchema: schema, cls: classify({ name }), legacyCls: legacyClassify({ name }) }))+const cls = (db: Db, name: string) => db.tools('s').find((t) => t.name === name)?.cls++describe("a tool's class across syncs", () => {+ it('upgrading: an automatic class takes the new rules; one set by hand stays', () => {+ const file = join(mkdtempSync(join(tmpdir(), 'tucano-classes-')), 'tucano.db')+ let db = new Db(file)+ db.saveConnector({ id: 's', name: 'Slack', kind: 'remote', url: 'https://mcp.slack.com/mcp', auth: 'oauth' })+ db.syncTools('s', listed(['chat_post_message', 'reply_to_thread', 'share_file', 'list_messages']))+ db.close()+ // As 0.2.15 left it: the old classes, one changed by hand (share_file to read), none marked automatic.+ const raw = new DatabaseSync(file)+ raw.exec("UPDATE connector_tools SET cls = 'write', cls_auto = NULL; UPDATE connector_tools SET cls = 'read' WHERE name IN ('share_file', 'list_messages')")+ raw.close()++ db = new Db(file)+ db.syncTools('s', listed(['chat_post_message', 'reply_to_thread', 'share_file', 'list_messages']))+ expect(cls(db, 'chat_post_message')).toBe('sensitive') // was automatic ("write" by the old rules)+ expect(cls(db, 'reply_to_thread')).toBe('sensitive')+ expect(cls(db, 'share_file')).toBe('read') // the person's choice: the old rules said "write"+ expect(cls(db, 'list_messages')).toBe('read')+ db.close()+ })++ it('refreshing: a class chosen by hand stays, and going back to the automatic one follows the rules again', () => {+ const db = new Db(join(mkdtempSync(join(tmpdir(), 'tucano-classes-')), 'tucano.db'))+ db.saveConnector({ id: 's', name: 'Slack', kind: 'remote', url: 'https://mcp.slack.com/mcp', auth: 'oauth' })+ db.syncTools('s', listed(['chat_post_message', 'create_task']))+ db.updateTool('s', 'chat_post_message', { cls: 'write' })+ db.syncTools('s', listed(['chat_post_message', 'create_task']))+ expect(cls(db, 'chat_post_message')).toBe('write')+ expect(cls(db, 'create_task')).toBe('write')+ db.updateTool('s', 'chat_post_message', { cls: 'sensitive' }) // back to what the rules say+ db.syncTools('s', [{ name: 'chat_post_message', description: '', inputSchema: schema, cls: 'write' }, ...listed(['create_task'])]) // the rules change (an annotation, say)+ expect(cls(db, 'chat_post_message')).toBe('write')+ db.close()+ })+})diff --git a/test/connector-errors.test.ts b/test/connector-errors.test.tsindex 1ef1e77..d2e8fbd 100644--- a/test/connector-errors.test.ts+++ b/test/connector-errors.test.ts@@ -12,7 +12,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { setLang } from '../src/shared/lang'import type { CoreEvent } from '../src/shared/rpc'import type { Agent, Message, Settings } from '../src/shared/types'-import { callError, ConnectorManager, errorReason } from '../src/core/connectors'+import { callError, ConnectorManager, errorReason, GOOGLE_PREVIEW_URL, googlePreviewHint } from '../src/core/connectors'import { Db } from '../src/core/db'import { fakeEngine } from '../src/core/engines/fake'import type { Engine } from '../src/core/engines/types'@@ -190,6 +190,27 @@ describe('callError and errorReason', () => {})})+describe("Google's Developer Preview error", () => {+ const raw = 'Access to this tool requires that your Google Cloud project (123456789012) is enrolled in the Google Workspace Developer Preview Program.'+ it('says it is a step in the person’s own Google Cloud project, not something to retry or ask the Tuca for', () => {+ setLang('en')+ const hint = googlePreviewHint('https://gmailmcp.googleapis.com/mcp/v1', raw)!+ expect(hint).toContain(GOOGLE_PREVIEW_URL)+ expect(hint).toMatch(/only the person can do/)+ expect(hint).toMatch(/few days/)+ expect(hint).toMatch(/Neither you nor the Tuca can fix this/)+ setLang('pt')+ expect(googlePreviewHint('https://sheetsmcp.googleapis.com/mcp/v1', raw)).toMatch(/só a pessoa pode fazer/)+ })++ it("leaves other servers' errors, and Google's other errors, as they are", () => {+ expect(googlePreviewHint('https://mcp.linear.app/mcp', raw)).toBeUndefined()+ expect(googlePreviewHint('https://evil.example/googleapis.com', raw)).toBeUndefined()+ expect(googlePreviewHint('https://gmailmcp.googleapis.com/mcp/v1', 'Requested entity was not found.')).toBeUndefined()+ expect(googlePreviewHint(undefined, raw)).toBeUndefined()+ })+})+describe('a connector step reads as it goes', () => {it('shows the SQL while it runs, and the result in a few words when it is done', async () => {const sql = 'select region, sum(total) from main.sales.orders group by 1'diff --git a/test/db-queries.test.ts b/test/db-queries.test.tsindex 57ae5a2..f6265af 100644--- a/test/db-queries.test.ts+++ b/test/db-queries.test.ts@@ -77,7 +77,7 @@ describe('indexes for what runs often', () => {it('an existing database gains them, keeps its data, and the hot queries use them', () => {const file = join(mkdtempSync(join(tmpdir(), 'tucano-idx-')), 'tucano.db')- // A database from before the indexes: the last migration undone, with messages in it.+ // A database from before the indexes: those migrations undone (and the one after them), with messages in it.const db0 = new Db(file)db0.saveAgent(agent('a1'))db0.createConversation({ id: 'c1', kind: 'channel', name: 'geral', members: ['a1'] })@@ -86,7 +86,7 @@ describe('indexes for what runs often', () => {db0.close()const raw = new DatabaseSync(file)const { user_version } = raw.prepare('PRAGMA user_version').get() as { user_version: number }- raw.exec(`DROP INDEX messages_by_thread_id; DROP INDEX messages_by_author; DROP INDEX receipts_by_message; PRAGMA user_version = ${user_version - 1}`)+ raw.exec(`DROP INDEX messages_by_thread_id; DROP INDEX messages_by_author; DROP INDEX receipts_by_message; ALTER TABLE connector_tools DROP COLUMN cls_auto; PRAGMA user_version = ${user_version - 2}`)expect(plan(raw, "SELECT conversation_id FROM messages WHERE author_kind = 'agent' AND author_id = 'a1' ORDER BY at DESC LIMIT 1")).toContain('SCAN messages')raw.close()diff --git a/test/policy.test.ts b/test/policy.test.tsindex 120fcde..c166caf 100644--- a/test/policy.test.ts+++ b/test/policy.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { allowed, approvalHash, canonical, classify } from '../src/core/policy'+import { allowed, approvalHash, canonical, classify, legacyClassify } from '../src/core/policy'import type { ConnectorTool } from '../src/shared/types'describe('classify', () => {@@ -23,9 +23,43 @@ describe('classify', () => {expect(classify({ name: 'get_and_delete_cache' })).toBe('sensitive')})+ it("makes every tool that runs another action sensitive, whatever its annotations say", () => {+ // Composio's executors stand in front of every app's real actions: a call can read or send.+ for (const name of ['COMPOSIO_MULTI_EXECUTE_TOOL', 'COMPOSIO_PROXY_EXECUTE', 'COMPOSIO_REMOTE_WORKBENCH', 'COMPOSIO_REMOTE_BASH_TOOL']) {+ expect(classify({ name }), name).toBe('sensitive')+ expect(classify({ name, annotations: { readOnlyHint: true } }), name).toBe('sensitive')+ }+ // Finding a tool and reading its schema only read; connecting an account goes by its annotations.+ expect(classify({ name: 'COMPOSIO_SEARCH_TOOLS', annotations: { readOnlyHint: true } })).toBe('read')+ expect(classify({ name: 'COMPOSIO_GET_TOOL_SCHEMAS', annotations: { readOnlyHint: true } })).toBe('read')+ expect(classify({ name: 'COMPOSIO_MANAGE_CONNECTIONS', annotations: { destructiveHint: true } })).toBe('sensitive')+ // Its direct tools, app first in the name: sending is sensitive; anything else is at least a write.+ expect(classify({ name: 'GMAIL_SEND_EMAIL' })).toBe('sensitive')+ expect(classify({ name: 'GMAIL_FETCH_EMAILS' })).toBe('write')+ expect(classify({ name: 'GMAIL_FETCH_EMAILS', annotations: { readOnlyHint: true } })).toBe('read')+ })++ it('makes sending something to other people sensitive, as the verb only', () => {+ for (const name of ['post_message', 'chat_post_message', 'reply_to_thread', 'forward_email', 'share_file', 'share_issue', 'invite_user', 'comment_on_issue', 'message_create', 'resend_invite'])+ expect(classify({ name }), name).toBe('sensitive')+ // Making a comment, a reply or a post sends it; a draft, a label or an issue doesn't.+ for (const name of ['create_comment', 'add_issue_comment', 'save_comment', 'notion-create-comment', 'add_comment_to_pending_review', 'createReply'])+ expect(classify({ name }), name).toBe('sensitive')+ for (const name of ['create_email_draft', 'create_draft_reply', 'draft_reply', 'add_label_to_email', 'create_issue', 'save_issue', 'update_message', 'unshare_issue'])+ expect(classify({ name }), name).toBe('write')+ // The same words as nouns: still reads.+ for (const name of ['list_messages', 'get_message', 'search_emails', 'list_comments', 'get_issue_comments', 'get_share_link', 'fetch_posts'])+ expect(classify({ name }), name).toBe('read')+ expect(classify({ name: 'email_search' })).toBe('write') // a search after it: a noun, not a send+ expect(classify({ name: 'post_message', annotations: { readOnlyHint: true } })).toBe('read') // annotations still first+ // What it was before: only these changed.+ expect(legacyClassify({ name: 'post_message' })).toBe('write')+ expect(legacyClassify({ name: 'send_email' })).toBe('sensitive')+ })+it('does not match words inside other words', () => {expect(classify({ name: 'list_payments' })).toBe('read') // "pay" is not "payments"- expect(classify({ name: 'resend_invite' })).toBe('write') // "send" is not "resend"+ expect(classify({ name: 'resend_code' })).toBe('write') // "send" is not "resend"})})