Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Raise the per-app connected account cap from 5 to 10

Bugfixer 293bc9838ed0a
diff --git a/cloudflare/composio-broker/src/index.test.ts b/cloudflare/composio-broker/src/index.test.ts
index 59de57e0db..d67eb9c104 100644
--- a/cloudflare/composio-broker/src/index.test.ts
+++ b/cloudflare/composio-broker/src/index.test.ts
@@ -17,7 +17,7 @@ import { streamedBody } from "./test-harness";
const multiAccount = {
enable: true,
- max_accounts_per_toolkit: 5,
+ max_accounts_per_toolkit: 10,
require_explicit_selection: true,
};
@@ -340,12 +340,45 @@ describe("connected-apps broker boundaries", () => {
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({ error: "Add an account alias so the existing connection is not replaced" });
}
- fixture.accounts = Array.from({ length: 5 }, (_, id) => ({ id: String(id), status: "INITIALIZING", toolkit: { slug: "gmail" } }));
- expect((await fixture.authorize()).status).toBe(409);
+ fixture.accounts = Array.from({ length: 10 }, (_, id) => ({ id: String(id), status: "INITIALIZING", toolkit: { slug: "gmail" } }));
+ const full = await fixture.authorize();
+ expect(full.status).toBe(409);
+ await expect(full.json()).resolves.toEqual({ error: "gmail already has the maximum of 10 accounts" });
expect(fixture.links()).toHaveLength(successfulLinks);
expect(fixture.deletes()).toEqual([]);
});
+ it("links a sixth account, raising a Session made under the old cap of 5 in place first", async () => {
+ const fetchCalls: Array<{ url: string; init?: RequestInit }> = [];
+ const { env, ctx } = testEnv(fetchCalls, "agency-user");
+ const installation = { id: "agency-install", composio_user_id: "agency-user", session_id: "trs_old_cap", disabled_at: null };
+ let cap = 5;
+ const accounts = Array.from({ length: 5 }, (_, id) => ({ id: `ca_${id}`, alias: `sub-${id}`, status: "ACTIVE", toolkit: { slug: "gmail" } }));
+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ fetchCalls.push({ url, init });
+ if (url.includes("/connected_accounts")) return Response.json({ items: accounts });
+ if (url.endsWith("/link")) return Response.json({ redirect_url: "https://connect.composio.dev/link/gmail" });
+ if (url.includes("/auth_configs")) return Response.json({ items: [] });
+ if (init?.method === "PATCH") {
+ cap = (JSON.parse(String(init.body)) as { multi_account: { max_accounts_per_toolkit: number } }).multi_account.max_accounts_per_toolkit;
+ return Response.json({ session_id: "trs_old_cap" });
+ }
+ const old = session("trs_old_cap", "agency-user");
+ return Response.json({ ...old, config: { ...old.config, multi_account: { ...multiAccount, max_accounts_per_toolkit: cap } } });
+ });
+
+ const response = await authorize("gmail", "sub-5", installation, env as never, ctx as never);
+ expect(response.status).toBe(200);
+ const steps = fetchCalls.filter((call) => call.init?.method === "PATCH" || call.url.endsWith("/link"));
+ expect(steps.map((call) => [call.init?.method, call.url])).toEqual([
+ ["PATCH", "https://backend.composio.dev/api/v3.1/tool_router/session/trs_old_cap"],
+ ["POST", "https://backend.composio.dev/api/v3.1/tool_router/session/trs_old_cap/link"],
+ ]);
+ expect(JSON.parse(String(steps[0]!.init?.body))).toEqual({ multi_account: multiAccount });
+ expect(fetchCalls.some((call) => call.init?.method === "POST" && call.url.endsWith("/tool_router/session"))).toBe(false);
+ });
+
it("links a toolkit whose only account failed to sign in", async () => {
const fixture = accountFixture("failed-user");
fixture.accounts = [{ id: "ca_failed", status: "FAILED", toolkit: { slug: "gmail" } }];
@@ -377,10 +410,10 @@ describe("connected-apps broker boundaries", () => {
expect(fixture.deletes()).toHaveLength(1);
expect(fixture.links()).toHaveLength(1);
- const working = Array.from({ length: 4 }, (_, id) => ({ id: `ca_${id}`, alias: `other-${id}`, status: "ACTIVE", toolkit: { slug: "gmail" } }));
+ const working = Array.from({ length: 9 }, (_, id) => ({ id: `ca_${id}`, alias: `other-${id}`, status: "ACTIVE", toolkit: { slug: "gmail" } }));
fixture.accounts = [{ id: "ca_old_work", alias: "work", status: "INITIATED", toolkit: { slug: "gmail" } }, ...working];
expect((await fixture.authorize("work")).status).toBe(200);
- fixture.accounts.push({ id: "ca_4", alias: "other-4", status: "ACTIVE", toolkit: { slug: "gmail" } });
+ fixture.accounts.push({ id: "ca_9", alias: "other-9", status: "ACTIVE", toolkit: { slug: "gmail" } });
expect((await fixture.authorize("work")).status).toBe(409);
expect(fixture.links()).toHaveLength(2);
diff --git a/cloudflare/composio-broker/src/index.ts b/cloudflare/composio-broker/src/index.ts
index 710a0b9fa0..43ca83809f 100644
--- a/cloudflare/composio-broker/src/index.ts
+++ b/cloudflare/composio-broker/src/index.ts
@@ -28,6 +28,8 @@ interface ComposioSession {
headers: Record<string, string>;
userId?: string;
multiAccountConfigured: boolean;
+ /** The account cap Composio echoed, when it did. */
+ maxAccounts?: number;
/** Project auth configs the Session was created with, by canonical toolkit slug. */
authConfigs: AuthConfigMap;
}
@@ -100,9 +102,11 @@ const toolkitPageSchema = z.object({
const linkResponseSchema = z.object({ redirect_url: z.string().optional() });
const aliasRequestSchema = z.object({ alias: z.string().nullable().optional() });
const MAX_MCP_BODY = 2 * 1024 * 1024;
+/** Ten accounts per app is the most Composio allows (its range is 2-10). A Session keeps the cap it was made with,
+ * so one made under a lower cap is raised in place before its next sign-in link. */
const MULTI_ACCOUNT_CONFIG = {
enable: true,
- max_accounts_per_toolkit: 5,
+ max_accounts_per_toolkit: 10,
require_explicit_selection: true,
} as const;
const MAX_AUTH_CONFIG_PAGES = 20;
@@ -162,6 +166,7 @@ function parseSession(value: SessionWire): ComposioSession {
// creation, and recreating a Session would post the same config and get
// the same echo back — strict equality here can only churn, never fix.
multiAccountConfigured: multi?.enable === true,
+ maxAccounts: multi?.max_accounts_per_toolkit,
authConfigs: Object.fromEntries(
Object.entries(config?.auth_configs ?? {}).map(([slug, id]) => [canonicalToolkitSlug(slug), id]),
),
@@ -251,6 +256,26 @@ function authConfigsKey(sessionId: string, wanted: AuthConfigMap) {
/** Session ids this isolate already tried to upgrade once. If the fresh Session
* still doesn't echo multi-account, Composio isn't granting it. */
const multiAccountUpgradeAttempted = new Set<string>();
+/** Session ids this isolate already raised to the current account cap. */
+const accountCapRaised = new Set<string>();
+
+/** A Session made under a lower account cap gets the current one, in place, so
+ * its MCP endpoint stays. If Composio refuses, the old cap stays and the link
+ * goes ahead. */
+async function raiseAccountCap(session: ComposioSession, env: Env) {
+ if (session.maxAccounts === undefined || session.maxAccounts >= MULTI_ACCOUNT_CONFIG.max_accounts_per_toolkit
+ || accountCapRaised.has(session.sessionId)) return;
+ const response = await composioRequest(env, `/tool_router/session/${encodeURIComponent(session.sessionId)}`, {
+ method: "PATCH",
+ body: JSON.stringify({ multi_account: MULTI_ACCOUNT_CONFIG }),
+ });
+ if (!response.ok) {
+ console.warn(JSON.stringify({ message: "account cap not raised", status: response.status }));
+ return;
+ }
+ accountCapRaised.add(session.sessionId);
+}
+
/** Likewise for an `auth_configs` echo Composio leaves out, keyed by the map
* asked for so a new auth config still triggers one more upgrade. */
const authConfigUpgradeAttempted = new Set<string>();
@@ -607,6 +632,7 @@ async function authorize(
const removed = await composioRequest(env, `/connected_accounts/${encodeURIComponent(id)}?revoke_on_delete=true`, { method: "DELETE" });
if (!removed.ok) return json({ error: await upstreamError(removed, "Removing the earlier sign-in failed") }, 502);
}
+ await raiseAccountCap(session, env);
const linkRequest: AccountLinkRequest = { toolkit: slug };
if (plan.alias) linkRequest.alias = plan.alias;
const response = await composioRequest(env, `/tool_router/session/${encodeURIComponent(session.sessionId)}/link`, {
diff --git a/cloudflare/composio-broker/src/test-harness.ts b/cloudflare/composio-broker/src/test-harness.ts
index d119c45fc1..227c4a9ed7 100644
--- a/cloudflare/composio-broker/src/test-harness.ts
+++ b/cloudflare/composio-broker/src/test-harness.ts
@@ -142,7 +142,7 @@ export function fakeComposio() {
const sessionPayload = (session: FakeSession) => ({
session_id: session.id,
mcp: { type: "http", url: `https://backend.composio.dev/tool_router/${session.id}/mcp` },
- config: { user_id: session.user_id, multi_account: { enable: true, max_accounts_per_toolkit: 5, require_explicit_selection: true } },
+ config: { user_id: session.user_id, multi_account: { enable: true, max_accounts_per_toolkit: 10, require_explicit_selection: true } },
});
if (method === "POST" && path === "/tool_router/session" && body) {
const session = { id: `trs_${next++}`, user_id: String(body.user_id) };
diff --git a/server/composio-session.ts b/server/composio-session.ts
index 8b6f90c1de..f51c8c588d 100644
--- a/server/composio-session.ts
+++ b/server/composio-session.ts
@@ -34,9 +34,11 @@ const sessionResponseSchema = z.object({
});
export type SessionResponse = z.infer<typeof sessionResponseSchema>;
+/** Ten accounts per app is the most Composio allows (its range is 2-10). A Session keeps the cap it was made with,
+ * so one made under a lower cap is raised in place before its next sign-in link. */
export const MULTI_ACCOUNT_CONFIG = {
enable: true,
- max_accounts_per_toolkit: 5,
+ max_accounts_per_toolkit: 10,
require_explicit_selection: true,
} as const;
@@ -88,6 +90,8 @@ function supportsMultiAccount(session: SessionResponse): boolean {
/** Sessions this boot already upgraded once: if Composio still doesn't echo multi-account, it isn't granting it. */
const multiAccountUpgradeAttempted = new Set<string>();
+/** Sessions this boot already raised to the current account cap. */
+const accountCapRaised = new Set<string>();
/** Likewise for an `auth_configs` echo Composio leaves out. */
const authConfigUpgradeAttempted = new Set<string>();
/** What Composio said when it refused a Session naming an auth config, by config id. */
@@ -255,6 +259,24 @@ async function nameAuthConfigsInPlace(apiKey: string, session: SessionResponse,
return getProjectSession(apiKey, session.session_id);
}
+/** A Session made under a lower account cap gets the current one, in place, so its MCP endpoint stays. If Composio
+ * refuses, the old cap stays and the link goes ahead. */
+export async function raiseAccountCap(apiKey: string, session: SessionResponse): Promise<void> {
+ const cap = session.config?.multi_account?.max_accounts_per_toolkit;
+ if (cap === undefined || cap >= MULTI_ACCOUNT_CONFIG.max_accounts_per_toolkit || accountCapRaised.has(session.session_id)) return;
+ const res = await fetch(`${apiBase()}/tool_router/session/${encodeURIComponent(session.session_id)}`, {
+ method: "PATCH",
+ headers: projectHeaders(apiKey, true),
+ body: JSON.stringify({ multi_account: MULTI_ACCOUNT_CONFIG }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ if (!res.ok) {
+ console.warn(`[composio] Composio would not raise the Session's account cap (${await responseError(res, `HTTP ${res.status}`)})`);
+ return;
+ }
+ accountCapRaised.add(session.session_id);
+}
+
export async function ensureProjectSession(cfg: AppConfig, wanted?: AuthConfigMap): Promise<SessionResponse> {
const composio = cfg.composio;
const apiKey = projectApiKey(cfg);
diff --git a/server/composio.test.ts b/server/composio.test.ts
index 1bddd951cf..e119254b45 100644
--- a/server/composio.test.ts
+++ b/server/composio.test.ts
@@ -82,6 +82,8 @@ let brokerCatalogBody: { items: Array<{ slug: string; name: string }> } | null =
// The project's own auth configs, and those the stub Session was created with: a Session knows only the configs named at creation.
let customAuthConfigs: Array<Record<string, unknown>> = [];
let sessionAuthConfigs: Record<string, string> = {};
+// The cap the stub Session echoes: 10 for one made now, 5 for one made before the cap was raised.
+let sessionAccountCap = 10;
beforeAll(async () => {
api = createServer(async (req, res) => {
@@ -310,13 +312,18 @@ beforeAll(async () => {
user_id: "openmausbot_existing",
multi_account: {
enable: true,
- max_accounts_per_toolkit: 5,
+ max_accounts_per_toolkit: sessionAccountCap,
require_explicit_selection: true,
},
auth_configs: sessionAuthConfigs,
},
}));
}
+ if (req.method === "PATCH" && url.pathname === "/api/v3.1/tool_router/session/trs_test" && body?.multi_account) {
+ sessionAccountCap = body.multi_account.max_accounts_per_toolkit;
+ res.writeHead(200, { "content-type": "application/json" });
+ return res.end(JSON.stringify({ session_id: "trs_test" }));
+ }
if (req.method === "GET" && url.pathname === "/api/v3.1/auth_configs") {
res.writeHead(200, { "content-type": "application/json" });
return res.end(JSON.stringify({ items: customAuthConfigs }));
@@ -766,7 +773,7 @@ describe.sequential("Composio Sessions", () => {
},
multi_account: {
enable: true,
- max_accounts_per_toolkit: 5,
+ max_accounts_per_toolkit: 10,
require_explicit_selection: true,
},
});
@@ -794,7 +801,7 @@ describe.sequential("Composio Sessions", () => {
user_id: "openmausbot_legacy",
multi_account: {
enable: true,
- max_accounts_per_toolkit: 5,
+ max_accounts_per_toolkit: 10,
require_explicit_selection: true,
},
});
@@ -1392,18 +1399,49 @@ describe.sequential("Composio Sessions", () => {
const cfg: AppConfig = {
composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
};
- connectedAccountsOverride = Array.from({ length: 5 }, (_, index) => ({
+ connectedAccountsOverride = Array.from({ length: 10 }, (_, index) => ({
id: `ca_pending_${index}`, status: "INITIALIZING", toolkit: { slug: "slack" },
}));
const before = calls.length;
try {
- await expect(authorizeService(cfg, "slack")).rejects.toThrow(/maximum of 5 accounts/i);
- await expect(authorizeService(cfg, "slack", "team")).rejects.toThrow(/maximum of 5 accounts/i);
+ await expect(authorizeService(cfg, "slack")).rejects.toThrow(/maximum of 10 accounts/i);
+ await expect(authorizeService(cfg, "slack", "team")).rejects.toThrow(/maximum of 10 accounts/i);
expect(calls.slice(before).some((call) => call.method === "POST" && call.path.endsWith("/link"))).toBe(false);
} finally {
connectedAccountsOverride = null;
}
});
+
+ it("links a sixth account, raising a Session made under the old cap of 5 in place first", async () => {
+ const cfg: AppConfig = {
+ composio: { apiKey: "ak_test", userId: "openmausbot_existing", sessionId: "trs_test" },
+ };
+ sessionAccountCap = 5;
+ connectedAccountsOverride = Array.from({ length: 5 }, (_, index) => ({
+ id: `ca_sub_${index}`, alias: `sub-${index}`, status: "ACTIVE", toolkit: { slug: "slack" },
+ }));
+ const before = calls.length;
+ try {
+ await expect(authorizeService(cfg, "slack", "sub-5")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
+ const since = calls.slice(before).filter((call) => call.method === "PATCH" || call.path.endsWith("/link"));
+ expect(since.map((call) => [call.method, call.path])).toEqual([
+ ["PATCH", "/api/v3.1/tool_router/session/trs_test"],
+ ["POST", "/api/v3.1/tool_router/session/trs_test/link"],
+ ]);
+ expect(since[0]!.body).toEqual({
+ multi_account: { enable: true, max_accounts_per_toolkit: 10, require_explicit_selection: true },
+ });
+ expect(cfg.composio?.sessionId).toBe("trs_test");
+
+ // Raised once: the next sign-in link goes straight through.
+ const again = calls.length;
+ await expect(authorizeService(cfg, "slack", "sub-6")).resolves.toEqual({ url: "https://connect.composio.dev/link/slack" });
+ expect(calls.slice(again).some((call) => call.method === "PATCH")).toBe(false);
+ } finally {
+ sessionAccountCap = 10;
+ connectedAccountsOverride = null;
+ }
+ });
});
describe("a connector tools/list that fails", () => {
diff --git a/server/composio.ts b/server/composio.ts
index ad2603e6d2..56c5beb294 100644
--- a/server/composio.ts
+++ b/server/composio.ts
@@ -19,7 +19,7 @@ import {
responseError,
type ConnectedAccountResponse,
} from "./composio-project.ts";
-import { MULTI_ACCOUNT_CONFIG, authConfigRefusal, ensureProjectSession, projectApiKey, sessionForToolkit } from "./composio-session.ts";
+import { MULTI_ACCOUNT_CONFIG, authConfigRefusal, ensureProjectSession, projectApiKey, raiseAccountCap, sessionForToolkit } from "./composio-session.ts";
import { authConfigUseLine, noManagedAuthToolkit, withNoManagedAuthNote } from "./connector-auth-config-hint.ts";
import { planAccountLink } from "../shared/connector-account-link.ts";
import type { CuratedConnectorSlug } from "../shared/connector-curated.ts";
@@ -807,8 +807,8 @@ export async function authorizeService(cfg: AppConfig, slug: string, requestedAl
const plan = planAccountLink(toolkit, serviceAccounts, alias, MULTI_ACCOUNT_CONFIG.max_accounts_per_toolkit, () => `omb-retry-${randomUUID()}`);
if (!plan.ok) throw inputError(plan.error, plan.status);
for (const id of plan.replace) await deleteConnectedAccount(apiKey, id);
- const linkRequest: AccountLinkRequest = { toolkit };
- if (plan.alias) linkRequest.alias = plan.alias;
+ await raiseAccountCap(apiKey, session);
+ const linkRequest: AccountLinkRequest = plan.alias ? { toolkit, alias: plan.alias } : { toolkit };
const link = (sessionId: string) =>
fetch(`${apiBase()}/tool_router/session/${encodeURIComponent(sessionId)}/link`, {
method: "POST",
diff --git a/server/testing/broker-fake.ts b/server/testing/broker-fake.ts
index 42b22f0308..39218e2b23 100644
--- a/server/testing/broker-fake.ts
+++ b/server/testing/broker-fake.ts
@@ -66,7 +66,7 @@ export async function startBrokerFake(): Promise<BrokerFake> {
const session = (id: string, userId: string) => ({
session_id: id,
mcp: { url: `https://mcp.composio.dev/${id}` },
- config: { user_id: userId, multi_account: { enable: true, max_accounts_per_toolkit: 5, require_explicit_selection: true } },
+ config: { user_id: userId, multi_account: { enable: true, max_accounts_per_toolkit: 10, require_explicit_selection: true } },
});
let sessions = 0;
const sessionUsers: string[] = [];
diff --git a/server/testing/fake-composio-project.ts b/server/testing/fake-composio-project.ts
index 83e7270713..cef15de2e4 100644
--- a/server/testing/fake-composio-project.ts
+++ b/server/testing/fake-composio-project.ts
@@ -45,7 +45,7 @@ export async function startFakeComposioProject(apiKey: string): Promise<FakeComp
let origin = "";
const session = (id: string) => ({
session_id: id, mcp: { type: "http", url: `${origin}/mcp/${id}` },
- config: { user_id: fake.sessions.get(id), multi_account: { enable: true, max_accounts_per_toolkit: 5, require_explicit_selection: true } },
+ config: { user_id: fake.sessions.get(id), multi_account: { enable: true, max_accounts_per_toolkit: 10, require_explicit_selection: true } },
});
const server = createServer(async (req, res) => {
diff --git a/server/trust-controls.e2e.test.ts b/server/trust-controls.e2e.test.ts
index 9f44a80da6..56e90bdad7 100644
--- a/server/trust-controls.e2e.test.ts
+++ b/server/trust-controls.e2e.test.ts
@@ -86,7 +86,7 @@ beforeAll(async () => {
await new Promise<void>(resolve => { blockSession = resolve; });
}
return res.end(JSON.stringify({ session_id: "fixture-session", mcp: { type: "http", url: brokerOrigin + "/mcp" },
- config: { user_id: "fixture-user", multi_account: { enable: true, max_accounts_per_toolkit: 5, require_explicit_selection: true } } }));
+ config: { user_id: "fixture-user", multi_account: { enable: true, max_accounts_per_toolkit: 10, require_explicit_selection: true } } }));
}
if (req.url === "/mcp") {
relayed.push(body);