Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(connectors): name an allowed account in app shortcuts, briefing reads and login-mail codes
AdityaUmalea21fa24d9d2e
diff --git a/packages/phone-protocol/src/connector-scopes.ts b/packages/phone-protocol/src/connector-scopes.tsindex 3fa0176ed3..22bdf11bc6 100644--- a/packages/phone-protocol/src/connector-scopes.ts+++ b/packages/phone-protocol/src/connector-scopes.ts@@ -80,6 +80,11 @@ function toolkitFor(slug: string, toolkits: readonly string[]): string {.sort((a, b) => b.length - a.length)[0] ?? toolkitOf(slug);}+/** The connected-account ids a bot may use in `toolkit`, or undefined when that app has no account limit. */+export function accountLimit(scopes: ConnectorScopes | undefined, toolkit: string): string[] | undefined {+ return scopes?.accounts && Object.hasOwn(scopes.accounts, toolkit) ? scopes.accounts[toolkit] : undefined;+}+export type ConnectorAccess =| { ok: true }| { ok: false; slug: string; toolkit: string; reason: "app" | "write" | "account"; allowed?: string[] };@@ -96,7 +101,7 @@ export function connectorAccessDecision(scopes: ConnectorScopes | undefined, calconst scope = call.slug === "COMPOSIO_PROXY_EXECUTE" || !Object.hasOwn(scopes.apps, toolkit) ? undefined : scopes.apps[toolkit];if (!scope) return { ok: false, slug: call.slug, toolkit, reason: "app" };if (scope === "read" && !isReadOnlyAction(call.slug, toolkit)) return { ok: false, slug: call.slug, toolkit, reason: "write" };- const allowed = scopes.accounts && Object.hasOwn(scopes.accounts, toolkit) ? scopes.accounts[toolkit] : undefined;+ const allowed = accountLimit(scopes, toolkit);if (allowed && (!call.account || !allowed.includes(call.account))) return { ok: false, slug: call.slug, toolkit, reason: "account", allowed };}return { ok: true };diff --git a/server/connected-reads.ts b/server/connected-reads.tsindex f1f80a0d78..7fb203bd18 100644--- a/server/connected-reads.ts+++ b/server/connected-reads.ts@@ -398,8 +398,8 @@ export interface ConnectedReadDeps {/** Null when connected apps are not set up here; else which of the two apps are connected. */connected(): Promise<Record<ReadApp, boolean> | null>;/** The account to read for each app with several connected (Composio refuses a read that names none then); an app- * with one is left out, and its reads name no account. Asked once per session. */- accounts?(): Promise<AppAccounts>;+ * with one is left out, and its reads name no account. Asked once per session, with the bot the session reads for. */+ accounts?(botId?: string): Promise<AppAccounts>;relay(payload: unknown, transportSessionId: string | undefined, signal: AbortSignal): Promise<{ status: number; bytes: Uint8Array; transportSessionId?: string }>;readTimeoutMs?: number;}@@ -427,7 +427,8 @@ export interface MailBodySession extends ReadSession {export interface ConnectedReads {connected(): Promise<Record<ReadApp, boolean> | null>;- session(): ReadSession;+ /** `botId`: the bot the reads are for, so an account limit of its own picks the account. */+ session(botId?: string): ReadSession;}// A 50-email page is past the connected-apps service's size limit and comes back shortened; 20 fits, and a page that@@ -438,10 +439,10 @@ const GMAIL_PAGES = 6;const appOf = (slug: string): ReadApp | "outlook" => (slug.startsWith("GMAIL_") ? "gmail" : slug.startsWith("OUTLOOK_") ? "outlook" : "googlecalendar");-export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedReads, "session"> & { session(): MailBodySession } {+export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedReads, "session"> & { session(botId?: string): MailBodySession } {const readTimeoutMs = deps.readTimeoutMs ?? READ_TIMEOUT_MS;- function session(): MailBodySession {+ function session(botId?: string): MailBodySession {let opened: Promise<string | undefined> | undefined;let accounts: Promise<AppAccounts> | undefined;@@ -470,7 +471,7 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedRea});const transport = await opened;// A failed lookup reads as no account named and is asked again on the next read, not kept for the session.- accounts ??= deps.accounts?.().catch((): AppAccounts => {+ accounts ??= deps.accounts?.(botId).catch((): AppAccounts => {accounts = undefined;return {};}) ?? Promise.resolve({});diff --git a/server/connector-app-tools.test.ts b/server/connector-app-tools.test.tsindex 5527cd7a2d..75d4cd583f 100644--- a/server/connector-app-tools.test.ts+++ b/server/connector-app-tools.test.ts@@ -63,6 +63,19 @@ describe("a call to one", () => {expect(appToolCall("COMPOSIO_SEARCH_TOOLS", {})).toBeNull();});+ it("names the connected account the bot chose, so an account limit can be met through the shortcut too", () => {+ for (const tool of APP_TOOLS) {+ const [entry] = appToolEntries([tool.name], "plain");+ expect((entry!.inputSchema as { properties: Record<string, unknown> }).properties.account).toMatchObject({ type: "string" });+ }+ expect(appToolCall("gmail.search_emails", { query: "is:unread", account: " ca_home " })?.frame(1)).toMatchObject({ params: { arguments: { tools: [{+ tool_slug: "GMAIL_FETCH_EMAILS", account: "ca_home", arguments: { query: "is:unread" },+ }] } } });+ const item = (appToolCall("googlecalendar.list_events", { account: "" })!.frame(1) as { params: { arguments: { tools: Array<Record<string, unknown>> } } }).params.arguments.tools[0]!;+ expect(item).not.toHaveProperty("account");+ expect(item.arguments).not.toHaveProperty("account");+ });+it("answers with the tool's own data, and passes a refusal or failure through as it came", () => {const ok = { jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: JSON.stringify({ successful: true, data: { results: [{ tool_slug: "GMAIL_FETCH_EMAILS", response: { successful: true, data: { messages: [{ messageId: "m1" }] } } }] } }) }] } };expect(appToolAnswer("GMAIL_FETCH_EMAILS", ok)).toEqual({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: JSON.stringify({ messages: [{ messageId: "m1" }] }) }] } });diff --git a/server/connector-app-tools.ts b/server/connector-app-tools.tsindex 4bcf06b6ec..59ebdecc0d 100644--- a/server/connector-app-tools.ts+++ b/server/connector-app-tools.ts@@ -12,6 +12,8 @@ export const APP_TOOLS_ENV = "OMB_CONNECTOR_APP_TOOLS";* dot in a tool name, and they show the same name either way. */export const APP_TOOL_NAMES_ENV = "OMB_CONNECTOR_APP_TOOL_NAMES";const MULTI_EXECUTE = "COMPOSIO_MULTI_EXECUTE_TOOL";+/** Every app tool takes the connected account to use, which a bot limited to some accounts must name. */+const ACCOUNT = { type: "string", description: "Connected account id to use. Needed when this bot may use only certain accounts of the app." };type Input = Record<string, unknown>;interface AppTool {@@ -210,7 +212,7 @@ export function appToolEntries(names: readonly string[], style: "dotted" | "plaireturn APP_TOOLS.filter((tool) => names.includes(tool.name)).map((tool) => ({name: style === "dotted" ? tool.name : plainName(tool.name),description: tool.description,- inputSchema: { type: "object", additionalProperties: false, properties: tool.properties, ...(tool.required ? { required: tool.required } : {}) },+ inputSchema: { type: "object", additionalProperties: false, properties: { ...tool.properties, account: ACCOUNT }, ...(tool.required ? { required: tool.required } : {}) },annotations: { readOnlyHint: isReadOnlyAction(tool.slug, appOf(tool)) },}));}@@ -219,10 +221,12 @@ export function appToolEntries(names: readonly string[], style: "dotted" | "plaiexport function appToolCall(name: string, input: unknown): { slug: string; frame(id: unknown): Record<string, unknown> } | null {const tool = BY_NAME.get(name.trim().toLowerCase());if (!tool) return null;- const args = tool.args(input && typeof input === "object" && !Array.isArray(input) ? input as Input : {});+ const fields = input && typeof input === "object" && !Array.isArray(input) ? input as Input : {};+ const args = tool.args(fields);+ const account = text(fields.account);return {slug: tool.slug,- frame: (id) => ({ jsonrpc: "2.0", id, method: "tools/call", params: { name: MULTI_EXECUTE, arguments: { tools: [{ tool_slug: tool.slug, arguments: args }] } } }),+ frame: (id) => ({ jsonrpc: "2.0", id, method: "tools/call", params: { name: MULTI_EXECUTE, arguments: { tools: [{ tool_slug: tool.slug, arguments: args, ...(account ? { account } : {}) }] } } }),};}diff --git a/server/host/login-mail-codes.test.ts b/server/host/login-mail-codes.test.tsindex 476aaf9baf..72d40d45c7 100644--- a/server/host/login-mail-codes.test.ts+++ b/server/host/login-mail-codes.test.ts@@ -178,6 +178,34 @@ describe("whose mailbox", () => {expect(await codes.offerConnect(bot, turn)).toEqual({ shown: false, line });});+ it("reads only the accounts a bot's limit allows, naming each, in an app with an account limit", async () => {+ const { codes, deps, fake } = await setup();+ deps.composio.connectedServices = async () => ({ gmail: { connected: true, accounts: [{ id: "ca_work", status: "ACTIVE" }, { id: "ca_home", status: "ACTIVE" }] } }) as never;+ fake.emails = [gmailMail()];+ const limited = { ...bot, connectorScopes: { apps: { gmail: "read" as const }, accounts: { gmail: ["ca_home"] } } };+ expect(await codes.find(limited, turn, ask(), () => true)).toMatchObject({ kind: "code", code: CODE });+ expect(fake.calls.length).toBeGreaterThan(0);+ expect(new Set(fake.calls.map((call) => call.item.account))).toEqual(new Set(["ca_home"]));+ });++ it("names the allowed account even when it is the app's only one", async () => {+ const { codes, deps, fake } = await setup();+ deps.composio.connectedServices = async () => ({ gmail: { connected: true, accounts: [{ id: "ca_home", status: "ACTIVE" }] } }) as never;+ fake.emails = [gmailMail()];+ const limited = { ...bot, connectorScopes: { apps: { gmail: "read" as const }, accounts: { gmail: ["ca_home"] } } };+ expect(await codes.find(limited, turn, ask(), () => true)).toMatchObject({ kind: "code", code: CODE });+ expect(new Set(fake.calls.map((call) => call.item.account))).toEqual(new Set(["ca_home"]));+ });++ it("reads nothing when none of the allowed accounts is connected", async () => {+ const { codes, deps, fake } = await setup();+ deps.composio.connectedServices = async () => ({ gmail: { connected: true, accounts: [{ id: "ca_work", status: "ACTIVE" }] } }) as never;+ fake.emails = [gmailMail()];+ const limited = { ...bot, connectorScopes: { apps: { gmail: "read" as const }, accounts: { gmail: ["ca_home"] } } };+ expect(await codes.find(limited, turn, ask({ via: "unknown" }), () => true)).toEqual({ kind: "skip" });+ expect(fake.calls).toEqual([]);+ });+it("respects a bot's own switches", async () => {const { codes, fake } = await setup();fake.emails = [gmailMail()];diff --git a/server/host/login-mail-codes.ts b/server/host/login-mail-codes.tsindex 544f131bc8..388c5afc7e 100644--- a/server/host/login-mail-codes.ts+++ b/server/host/login-mail-codes.ts@@ -7,7 +7,7 @@ import { createHash, randomUUID } from "node:crypto";import { readFileSync } from "node:fs";import { join } from "node:path";-import { connectorAccessDecision } from "../../shared/connector-scopes.ts";+import { accountLimit, connectorAccessDecision } from "../../shared/connector-scopes.ts";import { writeFileAtomic } from "../atomic.ts";import type * as Composio from "../composio.ts";import type { AppConfig } from "../config.ts";@@ -72,8 +72,12 @@ export function createLoginMailCodes(deps: LoginMailCodesDeps) {const usedKey = (site: string, code: string) => createHash("sha256").update(`${site}\0${code}`).digest("hex");const forgetOld = (map: Map<string, number>, before: number) => { for (const [key, at] of map) if (at < before) map.delete(key); };- const mayRead = (bot: Bot, app: MailApp): boolean => deps.appAllowed(app) && READS[app].every((slug) =>- connectorAccessDecision(bot.connectorScopes, [{ slug }], [app]).ok && evaluateConnectorTools([slug], bot.connectorTools, [app]).allowed);+ // In an app with an account limit only allowed accounts are read (appBoxes), so the check names one of them.+ const mayRead = (bot: Bot, app: MailApp): boolean => {+ const account = accountLimit(bot.connectorScopes, app)?.[0];+ return deps.appAllowed(app) && READS[app].every((slug) =>+ connectorAccessDecision(bot.connectorScopes, [{ slug, ...(account ? { account } : {}) }], [app]).ok && evaluateConnectorTools([slug], bot.connectorTools, [app]).allowed);+ };function imapBox(account: EmailAccount): CodeMailbox {return {@@ -87,7 +91,7 @@ export function createLoginMailCodes(deps: LoginMailCodesDeps) {return { list: (sinceMs) => reads.outlookEmails(sinceMs, LIST_LIMIT), body: (id) => reads.outlookBody(id) };}- async function appBoxes(turn: Turn, app: MailApp): Promise<CodeMailbox[]> {+ async function appBoxes(bot: Bot, turn: Turn, app: MailApp): Promise<CodeMailbox[]> {let cfg = deps.cfg();let access: BrokerAccess | undefined;if (deps.personApps().includes(app)) {@@ -100,8 +104,11 @@ export function createLoginMailCodes(deps: LoginMailCodesDeps) {const state = (await deps.composio.connectedServices(cfg, access))[app];if (!state?.connected) return [];const active = (state.accounts ?? []).filter((one) => /^active$/i.test(one.status));- // Composio refuses a read that names no account when an app has several.- const accounts: Array<string | undefined> = active.length > 1 ? active.slice(0, ACCOUNTS_PER_APP).map((one) => one.id) : [undefined];+ const allowed = accountLimit(bot.connectorScopes, app);+ // A bot limited to some accounts reads only those, each named. Otherwise Composio refuses a read that names no+ // account when an app has several.+ const accounts: Array<string | undefined> = allowed ? active.filter((one) => allowed.includes(one.id)).slice(0, ACCOUNTS_PER_APP).map((one) => one.id)+ : active.length > 1 ? active.slice(0, ACCOUNTS_PER_APP).map((one) => one.id) : [undefined];return accounts.map((account) => appBox(app, createConnectedReads({connected: async () => null,...(account ? { accounts: async () => ({ [app]: account }) } : {}),@@ -116,7 +123,7 @@ export function createLoginMailCodes(deps: LoginMailCodesDeps) {if (deps.composio.configured(deps.cfg()) && bot.composio !== false) {for (const app of ["gmail", "outlook"] as const) {if (!mayRead(bot, app)) continue;- try { boxes.push(...await appBoxes(turn, app)); } catch { unknown = true; }+ try { boxes.push(...await appBoxes(bot, turn, app)); } catch { unknown = true; }}}return { boxes, unknown };diff --git a/server/host/proactive.test.ts b/server/host/proactive.test.tsindex 9fa9a32a18..e67f143df9 100644--- a/server/host/proactive.test.ts+++ b/server/host/proactive.test.ts@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";+import type { ConnectorScopes } from "../../shared/connector-scopes.ts";import type { AppConfig } from "../config.ts";import { RoutineManager } from "../routines.ts";import { Store } from "../store.ts";@@ -109,6 +110,32 @@ describe("the watch's checks", () => {expect(s.reads.flatMap((slug, index) => (slug.startsWith("GOOGLECALENDAR_") ? [s.accounts[index]] : []))).not.toContain("ca_cal");});+ it("read only an account the bot's limit allows, and name it even for an app with one account", async () => {+ const s = setup({ services: {+ gmail: { connected: true, accounts: [{ id: "ca_newest", status: "ACTIVE" }, { id: "ca_expired", status: "EXPIRED" }, { id: "ca_older", status: "ACTIVE" }] },+ googlecalendar: { connected: true, accounts: [{ id: "ca_cal", status: "ACTIVE" }] },+ } });+ const limited: ConnectorScopes = { apps: { gmail: "read", googlecalendar: "read" }, accounts: { gmail: ["ca_expired", "ca_older"], googlecalendar: ["ca_cal"] } };+ s.store.patchBot(s.chief.id, { connectorScopes: limited });+ await s.proactive.checks.check(s.proactive.ensureWatch()!, { manual: true });+ const gmail = s.reads.flatMap((slug, index) => (slug.startsWith("GMAIL_") ? [s.accounts[index]] : []));+ expect(gmail.length).toBeGreaterThan(0);+ expect(new Set(gmail)).toEqual(new Set(["ca_older"]));+ const calendar = s.reads.flatMap((slug, index) => (slug.startsWith("GOOGLECALENDAR_") ? [s.accounts[index]] : []));+ expect(calendar.length).toBeGreaterThan(0);+ expect(new Set(calendar)).toEqual(new Set(["ca_cal"]));+ });++ it("never read as another account when none of the allowed accounts is active", async () => {+ const s = setup({ services: { gmail: { connected: true, accounts: [{ id: "ca_newest", status: "ACTIVE" }, { id: "ca_older", status: "ACTIVE" }] }, googlecalendar: { connected: false } } });+ const limited: ConnectorScopes = { apps: { gmail: "read" }, accounts: { gmail: ["ca_gone"] } };+ s.store.patchBot(s.chief.id, { connectorScopes: limited });+ await s.proactive.checks.check(s.proactive.ensureWatch()!, { manual: true });+ const gmail = s.reads.flatMap((slug, index) => (slug.startsWith("GMAIL_") ? [s.accounts[index]] : []));+ expect(gmail.length).toBeGreaterThan(0);+ expect(new Set(gmail)).toEqual(new Set(["ca_gone"]));+ });+it("belong to the main agent only: a briefing routine of another bot reads nothing", async () => {const s = setup();const other = s.store.createBot({ name: "Scout" });diff --git a/server/host/proactive.ts b/server/host/proactive.tsindex 8238d80c5f..6f21f07686 100644--- a/server/host/proactive.ts+++ b/server/host/proactive.ts@@ -8,7 +8,7 @@ import { z } from "zod";import type { NeedsYouItem } from "../../shared/today.ts";import type { RuntimeEvent } from "../../shared/runtime-events.ts";-import { connectorAccessDecision } from "../../shared/connector-scopes.ts";+import { accountLimit, connectorAccessDecision } from "../../shared/connector-scopes.ts";import type { Notification } from "../../shared/notification.ts";import type { RequestAuth } from "../request-auth.ts";import { writeFileAtomic } from "../atomic.ts";@@ -98,12 +98,17 @@ export function createProactive(deps: ProactiveDeps) {const services = await composio.connectedServices(cfg);return Object.fromEntries(READ_APPS.map((app) => [app, services[app]?.connected === true])) as Record<ReadApp, boolean>;},- // Several accounts of one app: read the newest active one, as Composio refuses a read that names none.- accounts: async () => {+ // Several accounts of one app: read the newest active one, as Composio refuses a read that names none. A bot limited+ // to some accounts reads one of those, named even when it is the app's only one; with none of them active the read+ // names the first anyway, so it is refused rather than run as another account.+ accounts: async (botId) => {const services = await composio.connectedServices(cfg);+ const scopes = botId ? store.bot(botId)?.connectorScopes : undefined;return Object.fromEntries(READ_APPS.flatMap((app) => {- const active = (services[app]?.accounts ?? []).filter((one) => /^active$/i.test(one.status));- return active.length > 1 ? [[app, active[0]!.id]] : [];+ const active = (services[app]?.accounts ?? []).filter((one) => /^active$/i.test(one.status)).map((one) => one.id);+ const allowed = accountLimit(scopes, app);+ if (allowed) return [[app, active.find((id) => allowed.includes(id)) ?? allowed[0]!]];+ return active.length > 1 ? [[app, active[0]!]] : [];}));},relay: (payload, session, signal) => composio.relayMcp(cfg, payload as never, session, undefined, signal),@@ -114,7 +119,9 @@ export function createProactive(deps: ProactiveDeps) {const bot = store.bot(botId);if (!bot || bot.composio === false || !composio.configured(cfg)) return false;const slug = READ_SLUG[app];- return connectorAccessDecision(bot.connectorScopes, [{ slug }], [...READ_APPS]).ok && evaluateConnectorTools([slug], bot.connectorTools, [...READ_APPS]).allowed;+ // Its reads name one of its allowed accounts (accounts above), so the check names one too.+ const account = accountLimit(bot.connectorScopes, app)?.[0];+ return connectorAccessDecision(bot.connectorScopes, [{ slug, ...(account ? { account } : {}) }], [...READ_APPS]).ok && evaluateConnectorTools([slug], bot.connectorTools, [...READ_APPS]).allowed;}const fenced = (botId: string): boolean => {const bot = store.bot(botId);@@ -132,7 +139,7 @@ export function createProactive(deps: ProactiveDeps) {store, dataDir: deps.dataDir, hosted: deps.team, watching, mainThread: deps.mainThread, threadBusy: deps.threadBusy, runs,needsYou: deps.needsYou, engineName: deps.engineName, hostTimeZone: deps.hostTimeZone, language: () => cfg.language,notify: (bot, threadId, detail) => deps.notify(briefNotification(bot, threadId, detail)),- session: () => (composio.configured(cfg) ? reads.session() : null),+ session: () => (composio.configured(cfg) ? reads.session(owner()?.id) : null),address: () => checks.address(),failRun: (runId, why) => deps.routines()?.rejectResult(runId, why),keep: (key) => checks.commit(key),diff --git a/server/host/routine-checks.ts b/server/host/routine-checks.tsindex 9e7a09766a..f82ed78c22 100644--- a/server/host/routine-checks.ts+++ b/server/host/routine-checks.ts@@ -222,7 +222,7 @@ export function createRoutineChecks(deps: RoutineChecksDeps): RoutineChecks & {const held = new Set(Object.values(entry.pending ?? {}).flatMap((one) => [...one.mail, ...one.prep]));let wakeAt: number | undefined;const apps = checks.includes("calendar") || checks.includes("mail") ? await deps.reads.connected().catch(() => null) : null;- const session = deps.reads.session();+ const session = deps.reads.session(routine.botId);report.session = session;const readable = (app: ReadApp): boolean => apps?.[app] === true && deps.mayRead(routine.botId, app) && !trouble.some((one) => one.app === app) &&(context.manual || !readsBackOff(entry, app));