Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Name one account for every request of a calendar or mail read
AdityaUmale1fcfce88da9f
diff --git a/docs/verification/proactive-routines.md b/docs/verification/proactive-routines.mdindex 1e13c4acfe..a244de41d2 100644--- a/docs/verification/proactive-routines.md+++ b/docs/verification/proactive-routines.md@@ -38,6 +38,10 @@ Expected:dismissed sender as records.- A Gmail error is a failed check, never "nothing new": the routine shows`checkTrouble` and the brief says to reconnect Gmail.+- A MausBot limited to some Gmail accounts names one of them in every Gmail+ read. While the service's account list fails after the connected check, the+ reads name the first allowed account; once it answers again, the next check+ asks it afresh and reads the allowed account that is active.- A routine of the person's own runs as before: at the bot's own level, as aline in the chat.- In a read-and-draft run, the fake CLI tries to send, post to another app,diff --git a/server/connected-reads.test.ts b/server/connected-reads.test.tsindex fc8dc0e72f..41ff54b377 100644--- a/server/connected-reads.test.ts+++ b/server/connected-reads.test.ts@@ -210,6 +210,31 @@ describe("a check's reads", () => {for (const frame of frames.filter((one) => one.slug?.startsWith("GOOGLECALENDAR_"))) expect(frame.item!.account).toBe("ca_cal_newest");});+ it("names one account for every request of a calendar or mail read, even when the lookup recovers part-way", async () => {+ const { deps, frames } = relay({+ GOOGLECALENDAR_LIST_CALENDARS: () => ({ successful: true, data: { items: [{ id: "[email protected]", selected: true, accessRole: "reader" }] } }),+ GOOGLECALENDAR_EVENTS_LIST: () => ({ successful: true, data: { items: [] } }),+ GMAIL_FETCH_EMAILS: (args) => ({ successful: true, data: { messages: [], ...(args.page_token ? {} : { nextPageToken: "page-2" }) } }),+ });+ let asked = 0;+ const accounts = async () => {+ asked += 1;+ if (asked === 1 || asked === 3) throw new Error("inventory down");+ return { gmail: "ca_mail_new", googlecalendar: "ca_cal_new" };+ };+ const session = createConnectedReads({ ...deps, accounts, fallbackAccounts: () => ({ gmail: "ca_mail_old", googlecalendar: "ca_cal_old" }) }).session("bot-1");+ await session.events(0, 1);+ const calendar = frames.filter((one) => one.slug?.startsWith("GOOGLECALENDAR_"));+ expect(calendar.map((one) => one.slug)).toEqual(["GOOGLECALENDAR_LIST_CALENDARS", "GOOGLECALENDAR_EVENTS_LIST", "GOOGLECALENDAR_EVENTS_LIST"]);+ for (const frame of calendar) expect(frame.item!.account).toBe("ca_cal_old");+ await session.events(0, 1);+ expect(frames.filter((one) => one.slug?.startsWith("GOOGLECALENDAR_")).slice(3).map((one) => one.item!.account)).toEqual(["ca_cal_new", "ca_cal_new", "ca_cal_new"]);+ asked = 2;+ const fresh = createConnectedReads({ ...deps, accounts, fallbackAccounts: () => ({ gmail: "ca_mail_old", googlecalendar: "ca_cal_old" }) }).session("bot-1");+ await fresh.emails(0, 5);+ expect(frames.filter((one) => one.slug === "GMAIL_FETCH_EMAILS").map((one) => one.item!.account)).toEqual(["ca_mail_old", "ca_mail_old"]);+ });+it("gives up on an account lookup that outlasts the read's time limit, and asks again on the next read", async () => {const { deps, frames } = relay({ GMAIL_GET_PROFILE: () => ({ successful: true, data: { emailAddress: "[email protected]" } }) });let asked = 0;diff --git a/server/connected-reads.ts b/server/connected-reads.tsindex 786639c9f2..51908292b1 100644--- a/server/connected-reads.ts+++ b/server/connected-reads.ts@@ -439,6 +439,9 @@ const GMAIL_PAGE = 20;const GMAIL_PAGE_MIN = 5;const GMAIL_PAGES = 6;+/** The account lookup one multi-request read keeps for all its requests. */+type AccountPin = { accounts?: Promise<AppAccounts> };+const appOf = (slug: string): ReadApp | "outlook" => (slug.startsWith("GMAIL_") ? "gmail" : slug.startsWith("OUTLOOK_") ? "outlook" : "googlecalendar");export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedReads, "session"> & { session(botId?: string): MailBodySession } {@@ -460,9 +463,10 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedRea}/** One tool's data, GONE when `gone` says the tool's own failure means the thing asked for is missing, or SHORTENED- * when `shortened` is set and the answer was too large to come back whole. */- async function call(slug: string, args: Record<string, unknown>, options: { signal?: AbortSignal; gone?: (toolError: string) => boolean; shortened?: boolean } = {}): Promise<unknown> {- const { gone, shortened, signal = AbortSignal.timeout(readTimeoutMs) } = options;+ * when `shortened` is set and the answer was too large to come back whole. Calls sharing one `pin` name the same+ * account, so the pages and calendars of one read all come from one account. */+ async function call(slug: string, args: Record<string, unknown>, options: { signal?: AbortSignal; gone?: (toolError: string) => boolean; shortened?: boolean; pin?: AccountPin } = {}): Promise<unknown> {+ const { gone, shortened, pin, signal = AbortSignal.timeout(readTimeoutMs) } = options;const app = appOf(slug);let account: string | undefined;try {@@ -474,12 +478,12 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedReaconst transport = await opened;// A failed lookup reads as the fallback (no account named, unless the bot is limited to some) and is asked again// on the next read, not kept for the session.- accounts ??= deps.accounts?.(botId).catch((): AppAccounts => {+ const lookup = pin?.accounts ?? (accounts ??= deps.accounts?.(botId).catch((): AppAccounts => {accounts = undefined;return deps.fallbackAccounts?.(botId) ?? {};- }) ?? Promise.resolve({});+ }) ?? Promise.resolve<AppAccounts>({}));+ if (pin) pin.accounts = lookup;// The lookup counts toward this read's time limit; one that runs out is dropped so the next read asks again.- const lookup = accounts;account = (await untilAborted(lookup, signal, () => {if (accounts === lookup) accounts = undefined;}))[app];@@ -511,13 +515,13 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedReaif (times.some((time) => !Number.isFinite(time))) throw new SourceError(app, "the time window was not a finite time");}- async function calendarPages<T>(slug: string, args: Record<string, unknown>, parse: (data: unknown) => T[], signal: AbortSignal): Promise<T[]> {+ async function calendarPages<T>(slug: string, args: Record<string, unknown>, parse: (data: unknown) => T[], signal: AbortSignal, pin: AccountPin): Promise<T[]> {const results: T[] = [];const seen = new Set<string>();let page: string | undefined;for (let index = 0; index < CALENDAR_PAGES; index++) {const pageArgs = page ? { ...args, [slug === CALENDARS_TOOL ? "page_token" : "pageToken"]: page } : args;- const data = await call(slug, pageArgs, { signal });+ const data = await call(slug, pageArgs, { signal, pin });results.push(...parsed("googlecalendar", () => parse(data)));page = nextPageOf(data);if (!page) return results;@@ -532,14 +536,15 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedRearequireFinite("googlecalendar", fromMs, toMs);const failed = new AbortController();const signal = AbortSignal.any([AbortSignal.timeout(readTimeoutMs), failed.signal]);- const listed = await calendarPages(CALENDARS_TOOL, {}, calendarsFromData, signal);+ const pin: AccountPin = {};+ const listed = await calendarPages(CALENDARS_TOOL, {}, calendarsFromData, signal, pin);const read = [...(listed.some((calendar) => calendar.primary) ? [] : [PRIMARY_CALENDAR]), ...listed.filter((calendar) => calendar.read)];const perCalendar = await inParallel(read, CALENDAR_READS_AT_ONCE, async (calendar) => {try {return await calendarPages(CALENDAR_LIST_TOOL, {calendarId: calendar.id, timeMin: new Date(fromMs).toISOString(), timeMax: new Date(toMs).toISOString(),singleEvents: true, orderBy: "startTime", maxResults: 100, showDeleted: true,- }, (data) => eventsFromData(data, { id: calendar.id, owned: calendar.owned }), signal);+ }, (data) => eventsFromData(data, { id: calendar.id, owned: calendar.owned }), signal, pin);} catch (error) {failed.abort();throw new SourceError("googlecalendar", `calendar ${calendar.name}: ${errorText(error)}`, error instanceof SourceError && error.severalAccounts);@@ -552,12 +557,13 @@ export function createConnectedReads(deps: ConnectedReadDeps): Omit<ConnectedReaconst found: EmailHeader[] = [];let page: string | undefined;let size = GMAIL_PAGE;+ const pin: AccountPin = {};// Only whole pages count toward GMAIL_PAGES; a shortened answer is asked again smaller, at most twice per read.for (let pages = 0; pages < GMAIL_PAGES;) {const data = await call(GMAIL_FETCH_TOOL, {user_id: "me", query: `in:inbox after:${seconds(sinceMs)} -category:promotions -category:social`,max_results: size, include_payload: false, verbose: false, ...(page ? { page_token: page } : {}),- }, { shortened: size > GMAIL_PAGE_MIN });+ }, { shortened: size > GMAIL_PAGE_MIN, pin });if (data === SHORTENED) {size = Math.max(GMAIL_PAGE_MIN, Math.floor(size / 2));continue;diff --git a/server/proactive-routines.e2e.test.ts b/server/proactive-routines.e2e.test.tsindex 873ae7d413..2d290982b6 100644--- a/server/proactive-routines.e2e.test.ts+++ b/server/proactive-routines.e2e.test.ts@@ -189,6 +189,27 @@ describe("MausBot keeps an eye on the day, hidden from the sidebar", () => {expect(shown).not.toMatch(/Needs you|Your day|Reconnect Gmail/);delete apps.gmailError;});++ it("a MausBot limited to some Gmail accounts names one of them in every read, also while the account lookup fails", async () => {+ apps.accounts = { gmail: [{ id: "ca_other", status: "ACTIVE" }, { id: "ca_mine", status: "ACTIVE" }] };+ await api("PATCH", `/api/bots/${chief.id}`, { connectorScopes: { apps: { gmail: "read", googlecalendar: "read" }, accounts: { gmail: ["ca_gone", "ca_mine"] } } });+ const gmailAccounts = () => apps.calls.filter((call) => call.tool.startsWith("GMAIL_")).map((call) => call.item.account);+ // The check's connected list answers; the account lookup after it does not, so the reads name the first allowed one.+ apps.inventoryFailsAfter = 1;+ apps.calls.length = 0;+ await settled((await runNow()).id);+ expect(apps.inventoryFailsAfter).toBeLessThan(0);+ expect(gmailAccounts().length).toBeGreaterThan(0);+ expect(new Set(gmailAccounts())).toEqual(new Set(["ca_gone"]));+ for (const call of apps.calls.filter((one) => one.tool.startsWith("GOOGLECALENDAR_"))) expect(call.item).not.toHaveProperty("account");+ // The lookup answers again: the next check asks it and reads the allowed account that is active.+ delete apps.inventoryFailsAfter;+ apps.calls.length = 0;+ await settled((await runNow()).id);+ expect(gmailAccounts().length).toBeGreaterThan(0);+ expect(new Set(gmailAccounts())).toEqual(new Set(["ca_mine"]));+ apps.accounts = {};+ });});describe("a read-and-draft run", () => {diff --git a/server/testing/fake-connected-apps.ts b/server/testing/fake-connected-apps.tsindex 93ce3fc561..c035252efd 100644--- a/server/testing/fake-connected-apps.ts+++ b/server/testing/fake-connected-apps.ts@@ -8,6 +8,10 @@ export interface FakeConnectedApps {url: string;token: string;connected: Record<string, boolean>;+ /** The connected accounts the list names per app. */+ accounts: Record<string, Array<{ id: string; status: string }>>;+ /** While set, the connected list answers this many more times, then HTTP 503 until cleared. */+ inventoryFailsAfter?: number;address: string;/** Google Calendar event resources of the primary calendar. */events: unknown[];@@ -34,7 +38,7 @@ const field = (value: unknown, name: string): unknown => (value && typeof valueexport async function startFakeConnectedApps(): Promise<FakeConnectedApps> {const fake: Omit<FakeConnectedApps, "url" | "token" | "close"> = {- connected: { gmail: true, googlecalendar: true }, address: "[email protected]", events: [], emails: [], calls: [], threads: {}, outlook: [],+ connected: { gmail: true, googlecalendar: true }, accounts: {}, address: "[email protected]", events: [], emails: [], calls: [], threads: {}, outlook: [],calendars: [{ id: "[email protected]", primary: true, accessRole: "owner", selected: true }],};@@ -73,7 +77,12 @@ export async function startFakeConnectedApps(): Promise<FakeConnectedApps> {for await (const chunk of req) raw += chunk;res.setHeader("content-type", "application/json");if (req.method === "GET" && req.url === "/v1/connectors/connected") {- return res.end(JSON.stringify({ services: Object.fromEntries(Object.entries(fake.connected).map(([slug, connected]) => [slug, { connected }])) }));+ if (fake.inventoryFailsAfter !== undefined && fake.inventoryFailsAfter-- <= 0) {+ res.statusCode = 503;+ return res.end(JSON.stringify({ error: "fake connected apps: account inventory down" }));+ }+ return res.end(JSON.stringify({ services: Object.fromEntries(Object.entries(fake.connected).map(([slug, connected]) =>+ [slug, { connected, ...(fake.accounts[slug] ? { accounts: fake.accounts[slug] } : {}) }])) }));}// A connection card's status check: the services it names.if (req.method === "GET" && req.url?.startsWith("/v1/connectors?")) {