Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(connected-apps): name the other accounts of a refused call
David Neyra6e7b4234e66d
diff --git a/server/connector-account-hint.test.ts b/server/connector-account-hint.test.tsnew file mode 100644index 0000000000..bdca76c89f--- /dev/null+++ b/server/connector-account-hint.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from "vitest";++import { accountHint, accountsByApp, withAccountHint } from "./connector-account-hint.ts";++const encode = (value: unknown) => new TextEncoder().encode(typeof value === "string" ? value : JSON.stringify(value));+const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes);++const githubError = JSON.stringify({ successful: false, error: JSON.stringify({ message: "Resource not accessible by integration" }) });+const refused = {+ jsonrpc: "2.0",+ id: 7,+ result: { content: [{ type: "text", text: githubError }], isError: true },+};+const accounts = {+ github: [+ { id: "github_adrue-sump", alias: "vyrgs", status: "ACTIVE" },+ { id: "github_barie-scud", alias: "personal", status: "ACTIVE" },+ ],+};+const load = async () => accounts;++describe("connector account hint", () => {+ it("names the other accounts of the app a call was refused on", async () => {+ const out = JSON.parse(decode(await withAccountHint(encode(refused), "application/json", ["GITHUB_CREATE_AN_ISSUE"], load)));+ expect(out.result.content[0]).toEqual(refused.result.content[0]);+ expect(out.result.isError).toBe(true);+ expect(out.result.content[1].text).toContain("GitHub refused this because the connected account the call used cannot reach it");+ expect(out.result.content[1].text).toContain("not about a lack of access to GitHub");+ expect(out.result.content[1].text).toContain("vyrgs");+ expect(out.result.content[1].text).toContain("personal");+ expect(out.result.content[1].text).toContain("account field");+ });++ it("leaves a call alone when the app has one account only", async () => {+ const one = { github: [{ id: "github_barie-scud", alias: "personal", status: "ACTIVE" }] };+ const bytes = encode(refused);+ expect(await withAccountHint(bytes, "application/json", ["GITHUB_CREATE_AN_ISSUE"], async () => one)).toBe(bytes);+ });++ it("leaves an answer that is not a refusal untouched", async () => {+ const ok = encode({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: "relay-ok" }] } });+ expect(await withAccountHint(ok, "application/json", ["GITHUB_CREATE_AN_ISSUE"], load)).toBe(ok);+ });++ it("leaves a refusal of another kind untouched", async () => {+ const scope = encode({+ jsonrpc: "2.0",+ id: 2,+ result: { content: [{ type: "text", text: "403 Forbidden: Request had insufficient authentication scopes. ACCESS_TOKEN_SCOPE_INSUFFICIENT" }], isError: true },+ });+ expect(await withAccountHint(scope, "application/json", ["GMAIL_CREATE_FILTER"], load)).toBe(scope);+ });++ it("annotates a streamed (SSE) response", async () => {+ const body = `event: message\ndata: ${JSON.stringify(refused)}\n\n`;+ const out = decode(await withAccountHint(encode(body), "text/event-stream", ["GITHUB_CREATE_AN_ISSUE"], load));+ const frame = JSON.parse(out.split("\n").find((line) => line.startsWith("data:"))!.slice(5));+ expect(frame.result.content).toHaveLength(2);+ expect(out.startsWith("event: message\n")).toBe(true);+ });++ it("returns an unreadable body byte for byte", async () => {+ const unreadable = encode("Resource not accessible by integration but not JSON");+ expect(await withAccountHint(unreadable, "application/json", ["GITHUB_CREATE_AN_ISSUE"], load)).toBe(unreadable);+ });++ it("names an account without an alias by its id", () => {+ const hint = accountHint(["GITHUB_CREATE_AN_ISSUE"], {+ github: [{ id: "github_one", status: "ACTIVE" }, { id: "github_two", status: "ACTIVE" }],+ });+ expect(hint).toContain("github_one");+ expect(hint).toContain("github_two");+ });++ it("counts only the accounts that can run a call", () => {+ expect(accountHint(["GITHUB_CREATE_AN_ISSUE"], {+ github: [+ { id: "github_one", alias: "personal", status: "ACTIVE" },+ { id: "github_two", alias: "old", status: "EXPIRED" },+ ],+ })).toBe("");+ });++ it("reads the accounts out of a services inventory", () => {+ const read = accountsByApp({ github: { accounts: [{ id: "github_one", alias: "personal", status: "ACTIVE" }] } });+ expect(read.github?.[0]?.alias).toBe("personal");+ });+});diff --git a/server/connector-account-hint.ts b/server/connector-account-hint.tsnew file mode 100644index 0000000000..847a6a895a--- /dev/null+++ b/server/connector-account-hint.ts@@ -0,0 +1,73 @@+// A connected app can have more than one connected account. A call that names one the app's installation cannot reach+// is refused for lack of access, and GitHub's answer for that is "Resource not accessible by integration": the wording+// of an app closed to the bot, not of one account closed to another. Composio refuses a call that names no account at+// all ("Multiple github accounts connected. Specify which to use via the 'account' field"), so the account is always+// the bot's own choice, and a refusal it gets back reads as a wall. The scope hint already turns a failed call into+// something the bot can act on; this one names the other accounts of the same app, so the bot tries them before it+// tells the person it has no access.++import { withFailedCallHint } from "./connector-scope-hint.ts";++/** GitHub's wording when the connected account's app installation cannot reach what the call asks for. */+const ACCOUNT_ERROR = /not accessible by integration/i;++/** A connected account of one app, as the services inventory gives it. */+export interface ConnectedAccount {+ id: string;+ alias?: string;+ status: string;+}++/** The accounts of every connected app, by app slug. */+export type ConnectedAccounts = Record<string, readonly ConnectedAccount[]>;++/** The app a Composio tool slug belongs to: the part before the first underscore, lower case. */+export function toolkitOf(slug: string): string {+ const cut = slug.indexOf("_");+ return (cut > 0 ? slug.slice(0, cut) : slug).toLowerCase();+}++function appName(toolkit: string): string {+ if (toolkit === "gmail") return "Gmail";+ if (toolkit === "github") return "GitHub";+ if (toolkit === "slack") return "Slack";+ if (toolkit === "notion") return "Notion";+ if (toolkit.startsWith("google")) return "Google";+ return toolkit.charAt(0).toUpperCase() + toolkit.slice(1);+}++/** The accounts of one app that can run a call now. */+function usable(accounts: ConnectedAccounts, toolkit: string): readonly ConnectedAccount[] {+ return (accounts[toolkit] ?? []).filter((account) => /^active$/i.test(account.status));+}++/** The note for a call refused on the account it used: the other accounts of that app, by alias or id. */+export function accountHint(slugs: readonly string[], accounts: ConnectedAccounts): string {+ const slug = slugs.find((candidate) => candidate && !candidate.startsWith("COMPOSIO_")) ?? "";+ const toolkit = toolkitOf(slug);+ const known = usable(accounts, toolkit);+ if (known.length < 2) return "";+ const app = appName(toolkit);+ const names = known.map((account) => account.alias?.trim() || account.id).join(", ");+ return `OpenMausBot note: ${app} refused this because the connected account the call used cannot reach it. `+ + `That is about that account, not about a lack of access to ${app}: ${app} has ${known.length} connected accounts (${names}). `+ + `Name another one in the call's account field (an alias or an id) and try it once, `+ + `before telling the person you have no access to ${app}.`;+}++/** The accounts of every app, as the services inventory gives them. */+export function accountsByApp(services: Record<string, { accounts: readonly ConnectedAccount[] }>): ConnectedAccounts {+ return Object.fromEntries(Object.entries(services).map(([slug, state]) => [slug, state.accounts]));+}++/** Adds the account note to a call refused for the account it used, when that app has another account to try. */+export async function withAccountHint(+ bytes: Uint8Array,+ contentType: string,+ slugs: readonly string[],+ loadAccounts: () => Promise<ConnectedAccounts>,+): Promise<Uint8Array> {+ if (!ACCOUNT_ERROR.test(new TextDecoder().decode(bytes))) return bytes;+ const accounts = await loadAccounts().catch(() => ({}) as ConnectedAccounts);+ return withFailedCallHint(bytes, contentType, ACCOUNT_ERROR, (failed) => accountHint(failed, accounts), slugs);+}diff --git a/server/connector-scope-hint.ts b/server/connector-scope-hint.tsindex 6c15de8ad7..219d516f91 100644--- a/server/connector-scope-hint.ts+++ b/server/connector-scope-hint.ts@@ -93,7 +93,10 @@ export function annotateFailedCall(if (!refusals.length && result.isError === true && texts.some((text) => pattern.test(text))) refusals.push(null);if (!refusals.length) return false;const named = refusals.filter((slug): slug is string => slug !== null);- result.content.push({ type: "text", text: hint(named.length ? named : slugs) });+ // A hint with nothing to say (an app with no other account to try) leaves the result as it was.+ const note = hint(named.length ? named : slugs);+ if (!note) return false;+ result.content.push({ type: "text", text: note });return true;}diff --git a/server/index.ts b/server/index.tsindex 5e6568c767..278e200ad0 100644--- a/server/index.ts+++ b/server/index.ts@@ -646,6 +646,7 @@ import { createDevsReports } from "./host/devs-reports.ts"; import { createSettiimport { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";import { createThreadRoutes } from "./routes/threads.ts";import { createWebhookRoutes } from "./routes/webhooks.ts";+import { accountsByApp, withAccountHint } from "./connector-account-hint.ts";import { withScopeHint } from "./connector-scope-hint.ts";import { connectorFileDeps, connectorFileScope, prepareConnectorFiles, withMissingFileHint } from "./connector-files.ts";import { createConnectorCards } from "./host/connector-cards.ts";@@ -14416,7 +14417,12 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {};if (upstream.transportSessionId) headers["mcp-session-id"] = upstream.transportSessionId; if (connectorCalls.length) connectionHealth.appCall({ ...(internalCapability.connectorsFor ? { person: internalCapability.connectorsFor } : {}), slugs: connectorCalls.map((one) => one.slug), status: upstream.status, bytes: upstream.bytes, contentType: upstream.contentType });res.writeHead(upstream.status, headers);- return res.end(Buffer.from(withMissingFileHint(withScopeHint(proactive.fence.confines(internalCapability.threadId) ? recordsAnswer(upstream.bytes, upstream.contentType) : upstream.bytes, upstream.contentType, connectorCalls.map((call) => call.slug)), upstream.contentType, connectorCalls.map((call) => call.slug))));+ // A call refused for the connected account it used names the other accounts of that app, so the bot tries them+ // before it tells the person it has no access.+ const callSlugs = connectorCalls.map((call) => call.slug);+ const answered = proactive.fence.confines(internalCapability.threadId) ? recordsAnswer(upstream.bytes, upstream.contentType) : upstream.bytes;+ const hinted = withMissingFileHint(withScopeHint(answered, upstream.contentType, callSlugs), upstream.contentType, callSlugs);+ return res.end(Buffer.from(await withAccountHint(hinted, upstream.contentType, callSlugs, () => composio.connectedServices(...teamConnections.via(actor.access)).then(accountsByApp))));}if (path === "/api/internal/computer-control") {const botId = url.searchParams.get("botId") ?? "";