Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a bot's app-event automations to the accounts it may use
Bugfixer 2e1eaf3ff3ed6
diff --git a/docs/composio.md b/docs/composio.mdindex 51e85a1110..efbf91f006 100644--- a/docs/composio.md+++ b/docs/composio.md@@ -100,6 +100,8 @@ If a provider or restricted Composio project policy prevents another authorizatiThe hosted/managed connected-apps broker exposes the same account-aware response shape and account-specific removal routes as the self-hosted project-key mode; it does not send broker or provider credentials to the renderer.+Each bot can be kept to some of those accounts: open the bot's settings, then **Access**, turn on **Limit this bot to specific apps**, and under an app with two or more accounts tick **Accounts this bot may use**. The bot's calls that name another account are refused, its app-event automations can watch only the allowed accounts, and an automation whose account is later taken off the list starts no runs.+## Permissions the default connection does not ask forEach app you connect uses the Composio project's authorization for that app. Unless you set up your own, that is the Composio-managed one, which asks the provider only for Composio's default permissions. Some actions need more. In Gmail:diff --git a/server/app-event-catalog.ts b/server/app-event-catalog.tsindex d5d97d23c2..924c041454 100644--- a/server/app-event-catalog.ts+++ b/server/app-event-catalog.ts@@ -1,6 +1,7 @@// The events a bot (or the person, for a bot) can watch: only connected apps that bot may use, each with its event// types from the connected-apps service. Apps it may not use are left out entirely, never listed as refused.import { botMayWatchApp, type AppEventCatalog, type AppEventType } from "../shared/app-triggers.ts";+import { accountLimit, type ConnectorScopes } from "../shared/connector-scopes.ts";import type { ConnectorToolGrant } from "../shared/wire.ts";import type { AppTriggerBroker, BrokerTriggerType } from "./app-trigger-broker.ts";@@ -10,7 +11,7 @@ const MAX_APPS = 10;const MAX_EVENTS = 25;const DESCRIPTION_MAX = 200;-type Bot = { composio?: boolean; connectorTools?: Record<string, ConnectorToolGrant>; connectorScopes?: { apps: Record<string, "read" | "write"> } };+type Bot = { composio?: boolean; connectorTools?: Record<string, ConnectorToolGrant>; connectorScopes?: ConnectorScopes };type Connected = Record<string, { connected: boolean; accounts: Array<{ id: string; alias?: string; status: string }> }>;const label = (slug: string) => ({ googlecalendar: "Google Calendar", googlesheets: "Google Sheets", github: "GitHub", hubspot: "HubSpot" } as Record<string, string>)[slug]@@ -43,8 +44,13 @@ export async function appEventCatalog(input: {app?: string;search?: string;}): Promise<AppEventCatalog> {+ // Only the active accounts the bot may use, per its Access settings: an app with none of them is not listed.+ const accounts = (slug: string) => {+ const limit = accountLimit(input.bot.connectorScopes, slug);+ return input.connected[slug]!.accounts.filter((account) => /^active$/i.test(account.status) && (!limit || limit.includes(account.id)));+ };const usable = Object.entries(input.connected)- .filter(([slug, state]) => state.connected && state.accounts.some((account) => /^active$/i.test(account.status)) && botMayWatchApp(input.bot, slug))+ .filter(([slug, state]) => state.connected && accounts(slug).length > 0 && botMayWatchApp(input.bot, slug)).map(([slug]) => slug).sort();const wanted = input.app?.trim().toLowerCase();@@ -60,7 +66,7 @@ export async function appEventCatalog(input: {return {app: slug,name: label(slug),- accounts: input.connected[slug]!.accounts.filter((account) => /^active$/i.test(account.status)).map((account) => ({ id: account.id, ...(account.alias ? { alias: account.alias } : {}) })),+ accounts: accounts(slug).map((account) => ({ id: account.id, ...(account.alias ? { alias: account.alias } : {}) })),events,...(loaded?.error ? { error: loaded.error } : {}),};diff --git a/server/app-trigger-host.ts b/server/app-trigger-host.tsindex b46d56403e..07a97a6e64 100644--- a/server/app-trigger-host.ts+++ b/server/app-trigger-host.ts@@ -3,6 +3,7 @@import type { ServerResponse } from "node:http";import { botMayWatchApp, type AppEventCatalog } from "../shared/app-triggers.ts";+import { accountLimit, type ConnectorScopes } from "../shared/connector-scopes.ts";import type { ConnectorToolGrant } from "../shared/wire.ts";import { appEventCatalog, appLabel } from "./app-event-catalog.ts";import { brokerClient, type AppTriggerBroker, type BrokerAccess } from "./app-trigger-broker.ts";@@ -19,7 +20,7 @@ import type { WebhookManager } from "./webhooks.ts";type Bot = RosterMember & {color: string; composio?: boolean;- connectorTools?: Record<string, ConnectorToolGrant>; connectorScopes?: { apps: Record<string, "read" | "write"> };+ connectorTools?: Record<string, ConnectorToolGrant>; connectorScopes?: ConnectorScopes;};type Connected = Record<string, { connected: boolean; accounts: Array<{ id: string; alias?: string; status: string }> }>;@@ -75,6 +76,7 @@ export function createAppTriggerHost(deps: AppTriggerHostDeps) {service,connectedApps: deps.connectedApps,botState: deps.botState,+ accountLimit: (botId, app) => accountLimit(deps.store.bot(botId)?.connectorScopes, app),runs: {enqueue: (input) => deps.routines().enqueueWebhook(input),merge: (triggerId, eventId, sameConversation, merge) => deps.routines().mergeIntoQueuedRun(triggerId, eventId, sameConversation, merge),@@ -96,8 +98,9 @@ export function createAppTriggerHost(deps: AppTriggerHostDeps) {const connected = await deps.connectedApps();const result = await appEventCatalog({ broker, connected, bot, app, search });const wanted = app?.trim().toLowerCase();- if (wanted && !result.apps.length && connected[wanted]?.connected && !botMayWatchApp(bot, wanted)) {- return { ...result, unavailable: `${bot.name} has not been given access to ${appLabel(wanted)}. Ask the person to allow it under the bot's Access settings.` };+ if (wanted && !result.apps.length && connected[wanted]?.connected) {+ if (!botMayWatchApp(bot, wanted)) return { ...result, unavailable: `${bot.name} has not been given access to ${appLabel(wanted)}. Ask the person to allow it under the bot's Access settings.` };+ if (accountLimit(bot.connectorScopes, wanted)) return { ...result, unavailable: `None of the ${appLabel(wanted)} accounts ${bot.name} may use is connected and working. Ask the person to reconnect one, or to allow another under the bot's Access settings.` };}return result;}diff --git a/server/app-triggers.test.ts b/server/app-triggers.test.tsindex 97ab63c0ff..a3e276477c 100644--- a/server/app-triggers.test.ts+++ b/server/app-triggers.test.ts@@ -526,3 +526,48 @@ describe("app-event automation that keeps one conversation", () => {expect(runsOf(trigger.id)[0]).not.toHaveProperty("sameConversation");});});++describe("a bot limited to some accounts of an app", () => {+ let support = "";+ beforeEach(() => {+ support = broker.account(owner.userId, "gmail", "support");+ connected.gmail!.accounts.push({ id: support, alias: "support", status: "ACTIVE" });+ });++ it("watches only an account it may use: the one allowed is picked, another is refused", async () => {+ const triggers = manager({ accountLimit: (botId, app) => (botId === "bot-1" && app === "gmail" ? [support] : undefined) });+ const picked = await gmailTrigger(triggers);+ expect(picked).toMatchObject({ accountId: support, accountLabel: "support" });+ await expect(triggers.create({ botId: "bot-1", name: "Sales", prompt: "Draft a reply.", app: "gmail", event: "GMAIL_NEW_GMAIL_MESSAGE", account: "sales" }))+ .rejects.toThrow("This bot may use only support in Gmail");+ expect(triggers.list().map((trigger) => trigger.accountId)).toEqual([support]);+ });++ it("starts no run for an account the bot may no longer use", async () => {+ let allowed: string[] | undefined;+ const triggers = manager({ accountLimit: () => allowed });+ const trigger = await triggers.create({ botId: "bot-1", name: "Sales", prompt: "Draft a reply.", app: "gmail", event: "GMAIL_NEW_GMAIL_MESSAGE", account: "sales" });+ allowed = [support];+ expect((await broker.deliver(trigger.remote.triggerId!, { subject: "Hello", sender: "[email protected]" }, "msg_1")).status).toBe(200);+ await drain(triggers);+ expect(runsOf(trigger.id)).toHaveLength(0);+ expect(triggers.attempts().at(-1)).toMatchObject({ triggerId: trigger.id, outcome: "rejected", reason: "its bot may no longer use this account" });+ await expect(triggers.runNow(trigger.id)).rejects.toThrow("Its bot may no longer use this account");+ // The app stops sending what would only be rejected, and the automation says why.+ await triggers.reconcile();+ const client = brokerClient(() => ({ url: broker.url, token: owner.token }));+ expect((await client.inventory()).triggers.find((binding) => binding.triggerId === trigger.remote.triggerId)?.enabled).toBe(false);+ expect(triggers.get(trigger.id)).toMatchObject({ enabled: true, problem: { kind: "error", text: expect.stringContaining("Access settings") } });+ allowed = undefined;+ await triggers.reconcile();+ expect((await client.inventory()).triggers.find((binding) => binding.triggerId === trigger.remote.triggerId)?.enabled).toBe(true);+ expect(triggers.get(trigger.id)?.problem).toBeUndefined();+ });++ it("lists only the accounts the bot may use in its event list", async () => {+ const client = brokerClient(() => ({ url: broker.url, token: owner.token }));+ const bot = { connectorScopes: { apps: { gmail: "read" as const }, accounts: { gmail: [support] } } };+ const catalog = await appEventCatalog({ broker: client, connected, bot });+ expect(catalog.apps.map((app) => app.accounts)).toEqual([[{ id: support, alias: "support" }]]);+ });+});diff --git a/server/app-triggers.ts b/server/app-triggers.tsindex 86656ec5bd..bc0b13406c 100644--- a/server/app-triggers.ts+++ b/server/app-triggers.ts@@ -59,6 +59,8 @@ export interface AppTriggerManagerOptions {service: () => { available: true } | { available: false; reason: "self-hosted" | "unavailable" | "off" };connectedApps: () => Promise<ConnectedApps>;botState: (botId: string) => "ready" | "busy" | "missing";+ /** The account ids of an app a bot may use, from its Access settings; undefined when it may use every account. */+ accountLimit?: (botId: string, app: string) => string[] | undefined;runs: {enqueue(input: { webhookId: string; webhookName: string; prompt: string; botId: string; runOn: RoutineRunOn; deliveryId: string; receivedAt: number; eventSource: "app"; sameConversation?: boolean }): { id: string };merge(triggerId: string, eventId: string, sameConversation: boolean, merge: (prompt: string) => string | null): { id: string } | null;@@ -163,6 +165,8 @@ export interface AppTriggerPatch {const utcDay = (at: number) => new Date(at).toISOString().slice(0, 10);const active = (status: string) => /^active$/i.test(status);+const ACCOUNT_NOT_ALLOWED = "Its bot may no longer use this account. Allow it again under the bot's Access settings, or make the automation for an account the bot may use.";+const names = (accounts: Array<{ id: string; alias?: string }>) => accounts.map((account) => account.alias ?? account.id).join(", ");function cleanFilter(filter: AppTriggerFilter | null | undefined): AppTriggerFilter | undefined {if (!filter) return undefined;@@ -272,7 +276,7 @@ export class AppTriggerManager {const type = await this.remote(() => this.options.broker.triggerType(input.event.trim()));if (!type) throw new AppTriggerError(`${input.event} is not an event OpenMausBot can watch. Call trigger_info action=events to see the events this app offers.`, 404);if (type.toolkit !== app) throw new AppTriggerError(`${type.slug} is a ${appLabel(type.toolkit)} event, not ${appLabel(app)}.`);- const account = await this.resolveAccount(app, input.account);+ const account = await this.resolveAccount(input.botId, app, input.account);const filter = cleanFilter(input.filter);const config = triggerConfig(type, input.config ?? {}, filter);const now = this.now();@@ -410,6 +414,7 @@ export class AppTriggerManager {const entry = this.deleted.find((candidate) => candidate.trigger.id === id && candidate.at >= this.now() - RESTORE_WINDOW_MS);if (!entry || this.triggers.some((trigger) => trigger.id === id)) return null;if (this.options.botState(entry.trigger.botId) === "missing") throw new AppTriggerError("The assigned bot no longer exists.", 410);+ if (!this.botMayUse(entry.trigger.botId, entry.trigger.app, entry.trigger.accountId)) throw new AppTriggerError(ACCOUNT_NOT_ALLOWED, 403);const trigger: StoredTrigger = { ...structuredClone(entry.trigger), remote: { state: "pending" }, updatedAt: this.now() };try { await this.bind(trigger); await this.applyEnabled(trigger.remote.triggerId, trigger.enabled); }catch (error) { this.markRemoteFailure(trigger, error); }@@ -426,6 +431,7 @@ export class AppTriggerManager {async runNow(id: string): Promise<{ via: "service" | "here"; runId?: string } | null> {const trigger = this.triggers.find((candidate) => candidate.id === id);if (!trigger) return null;+ if (!this.botMayUse(trigger.botId, trigger.app, trigger.accountId)) throw new AppTriggerError(ACCOUNT_NOT_ALLOWED, 403);const data = { omb_test: true, note: "A test run started from OpenMausBot." };if (trigger.remote.triggerId && trigger.remote.state === "active" && this.options.service().available) {try {@@ -520,6 +526,10 @@ export class AppTriggerManager {this.record(trigger, event, "rejected", { reason: "its bot was deleted" });continue;}+ if (!this.botMayUse(trigger.botId, trigger.app, trigger.accountId)) {+ this.record(trigger, event, "rejected", { reason: "its bot may no longer use this account" });+ continue;+ }if (!matchesFilter(trigger.app, trigger.filter, data)) {trigger.filtered += 1;this.record(trigger, event, "filtered", { reason: "did not match the filter" });@@ -651,7 +661,10 @@ export class AppTriggerManager {return;}trigger.remote = { triggerId: binding.triggerId, state: "active", syncedAt: this.now() };- if (trigger.problem?.kind === "error") delete trigger.problem;+ // Kept, not re-stamped, while the account stays off the bot's list, so each pass does not announce it again.+ const allowed = this.botMayUse(trigger.botId, trigger.app, trigger.accountId);+ if (trigger.problem?.kind === "error" && (allowed || trigger.problem.text !== ACCOUNT_NOT_ALLOWED)) delete trigger.problem;+ if (!allowed && !trigger.problem) trigger.problem = { kind: "error", text: ACCOUNT_NOT_ALLOWED, at: this.now() };}/** The service's drop counts never reset; today's share is what grew since the UTC day began. */@@ -675,7 +688,11 @@ export class AppTriggerManager {trigger.skipped = { ...current, [reason]: current[reason] + 1 };}- private async resolveAccount(app: string, wanted: string | undefined): Promise<{ id: string; alias?: string }> {+ private botMayUse(botId: string, app: string, accountId: string): boolean {+ return this.options.accountLimit?.(botId, app)?.includes(accountId) ?? true;+ }++ private async resolveAccount(botId: string, app: string, wanted: string | undefined): Promise<{ id: string; alias?: string }> {let apps: ConnectedApps;try {apps = await this.options.connectedApps();@@ -685,16 +702,22 @@ export class AppTriggerManager {const accounts = (apps[app]?.accounts ?? []).filter((account) => active(account.status));const label = appLabel(app);if (!accounts.length) throw new AppTriggerError(`${label} is not connected. Ask the person to connect ${label} first (COMPOSIO_MANAGE_CONNECTIONS shows them a card for it), then create the automation.`, 409);+ const allowed = accounts.filter((account) => this.botMayUse(botId, app, account.id));+ const refusal = () => new AppTriggerError(allowed.length+ ? `This bot may use only ${names(allowed)} in ${label}. Watch one of those, or ask the person to allow another account under the bot's Access settings.`+ : `This bot may use none of the connected ${label} accounts. Ask the person to allow one under the bot's Access settings.`, 403);if (wanted?.trim()) {const key = wanted.trim().toLowerCase();const match = accounts.find((account) => account.id === wanted.trim() || account.alias?.toLowerCase() === key);- if (!match) throw new AppTriggerError(`No connected ${label} account is called ${wanted}. The accounts are: ${accounts.map((account) => account.alias ?? account.id).join(", ")}.`);+ if (!match) throw allowed.length < accounts.length ? refusal() : new AppTriggerError(`No connected ${label} account is called ${wanted}. The accounts are: ${names(accounts)}.`);+ if (!allowed.includes(match)) throw refusal();return match;}- if (accounts.length > 1) {- throw new AppTriggerError(`The person has ${accounts.length} ${label} accounts (${accounts.map((account) => account.alias ?? account.id).join(", ")}). Ask which one, then pass account.`);+ if (!allowed.length) throw refusal();+ if (allowed.length > 1) {+ throw new AppTriggerError(`${allowed.length === accounts.length ? "The person has" : "This bot may use"} ${allowed.length} ${label} accounts (${names(allowed)}). Ask which one, then pass account.`);}- return accounts[0]!;+ return allowed[0]!;}private async bind(trigger: StoredTrigger): Promise<void> {@@ -730,7 +753,7 @@ export class AppTriggerManager {}private wantsEnabled(triggerId: string): boolean {- return this.triggers.some((trigger) => trigger.remote.triggerId === triggerId && trigger.enabled);+ return this.triggers.some((trigger) => trigger.remote.triggerId === triggerId && trigger.enabled && this.botMayUse(trigger.botId, trigger.app, trigger.accountId));}private markRemoteFailure(trigger: StoredTrigger, error: unknown): void {