Multiplayer agent harness for work.
Let people reconnect or disconnect connected apps (#2452)
Joshua Franceaeae4d1ff982
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex aa4a76c18..9db6c9e2f 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -1374,6 +1374,16 @@ const apiRoutes: readonly WebRoute[] = [);},},+ {+ method: "POST",+ path: "/api/composio/disconnect",+ handle: async (c) => {+ const body = await readJson<{ accountId?: unknown }>(c.req, c.res, false);+ if (!body) return;+ c.res.setHeader("Cache-Control", "no-store");+ return relayCore(c.res, "POST", "/v1/composio/disconnect", JSON.stringify({ accountId: body.accountId }));+ },+ },{match: (_method, pathname) => pathname === "/me",handle: async (c) => {diff --git a/plugins/web-ui/src/connection-picker.ts b/plugins/web-ui/src/connection-picker.tsindex 6b601a927..f98e45b94 100644--- a/plugins/web-ui/src/connection-picker.ts+++ b/plugins/web-ui/src/connection-picker.ts@@ -1,5 +1,5 @@import { html, nothing, render } from "lit";-import { Search, ArrowUpRight, Check } from "lucide";+import { Search, ArrowUpRight, Check, RefreshCw } from "lucide";import { connectorLogo } from "./connector-logo";import { icon } from "./icons";@@ -10,6 +10,7 @@ export interface ConnectionService {popularity: number;logoUrl?: string;connected?: boolean;+ stale?: boolean;}export function mountConnectionPicker(@@ -58,20 +59,22 @@ export function mountConnectionPicker(</div>`}<div class="connection-picker-grid">- ${shown.map(- (service) =>- html`<button- type="button"- class="connection-picker-app"- ?disabled=${service.connected}- aria-label=${service.connected ? `${service.name} connected` : `Connect ${service.name}`}- @click=${() => onSelect(service)}- >- ${connectorLogo(service.id, service.logoUrl)}- <span class="connection-picker-name">${service.name}</span>- <span class="connection-picker-trailing">${icon(service.connected ? Check : ArrowUpRight, 14)}</span>- </button>`,- )}+ ${shown.map((service) => {+ let action = { label: `Connect ${service.name}`, mark: ArrowUpRight };+ if (service.stale) action = { label: `Reconnect ${service.name}`, mark: RefreshCw };+ else if (service.connected) action = { label: `${service.name} connected`, mark: Check };+ return html`<button+ type="button"+ class=${service.stale ? "connection-picker-app stale" : "connection-picker-app"}+ ?disabled=${service.connected && !service.stale}+ aria-label=${action.label}+ @click=${() => onSelect(service)}+ >+ ${connectorLogo(service.id, service.logoUrl)}+ <span class="connection-picker-name">${service.name}</span>+ <span class="connection-picker-trailing">${icon(action.mark, 14)}</span>+ </button>`;+ })}</div>${matches.length === 0 ? html`<p class="connection-picker-empty">No apps match “${query}”. Try another name.</p>` : nothing}${diff --git a/plugins/web-ui/src/connection-return.ts b/plugins/web-ui/src/connection-return.tsindex 7662fbe85..d40d0c8a4 100644--- a/plugins/web-ui/src/connection-return.ts+++ b/plugins/web-ui/src/connection-return.ts@@ -5,12 +5,14 @@ export interface ConnectionAttempt {user: string;service: { id: string; name: string };accountId: string;+ replaces?: string;widget: string;expiresAt: number;path: string;picker: PickerState;scrollTop: number;}+export const ACCOUNT_ID = /^ca_[a-zA-Z0-9_-]+$/;const key = (user: string) => `qm-connection-return:${user}`;export function saveConnectionAttempt(attempt: ConnectionAttempt): void {@@ -28,7 +30,9 @@ export function readConnectionAttempt(user: string, state: string, path: string)!Number.isFinite(attempt.expiresAt) ||attempt.expiresAt <= Date.now() ||typeof attempt.accountId !== "string" ||- !/^ca_[a-zA-Z0-9_-]+$/.test(attempt.accountId) ||+ !ACCOUNT_ID.test(attempt.accountId) ||+ (attempt.replaces !== undefined &&+ (typeof attempt.replaces !== "string" || !ACCOUNT_ID.test(attempt.replaces))) ||typeof attempt.widget !== "string" ||typeof attempt.service?.id !== "string" ||typeof attempt.service.name !== "string" ||diff --git a/plugins/web-ui/src/onboarding-welcome.css b/plugins/web-ui/src/onboarding-welcome.cssindex 99dde8e6b..12610a2eb 100644--- a/plugins/web-ui/src/onboarding-welcome.css+++ b/plugins/web-ui/src/onboarding-welcome.css@@ -220,6 +220,14 @@ qm-onboarding-welcome {color: var(--success);flex: none;}+.connection-connected .stale svg,+.connection-picker-app.stale .connection-picker-trailing {+ color: var(--warning);+}+.connection-connected .kc-text-action {+ padding: 0 2px;+ font-size: inherit;+}.connection-result strong {font-weight: 550;}diff --git a/plugins/web-ui/src/onboarding-welcome.ts b/plugins/web-ui/src/onboarding-welcome.tsindex 154923184..838cfce4e 100644--- a/plugins/web-ui/src/onboarding-welcome.ts+++ b/plugins/web-ui/src/onboarding-welcome.ts@@ -6,11 +6,18 @@ import {saveConnectionAttempt,clearConnectionAttempt,type ConnectionAttempt,+ ACCOUNT_ID,} from "./connection-return";import { LitElement, html, nothing } from "lit";-import { Check } from "lucide";+import { Check, TriangleAlert } from "lucide";import { icon } from "./icons";import { mountConnectionPicker, type ConnectionService } from "./connection-picker";++interface ConnectedAccount {+ id: string;+ toolkit: string;+ missingScopes?: string[];+}import type { Me } from "./shell-state";import "./onboarding-welcome.css";import "./onboarding-slack";@@ -70,7 +77,8 @@ export class OnboardingWelcome extends LitElement {declare error: string;declare authorizing: string;declare authorizationError: string;- private connections: Array<{ id: string; toolkit: string }> = [];+ private connections: ConnectedAccount[] = [];+ private disconnecting = "";private connectionError = "";private workspaceConnected: boolean | null = null;private workspaceError = false;@@ -210,13 +218,18 @@ export class OnboardingWelcome extends LitElement {const connected = this.preview? previewConnections(this.previewUser()): this.connections.map((account) => account.toolkit);- const services = this.services.map((service) => ({ ...service, connected: connected.includes(service.id) }));+ const stale = this.staleToolkits();+ const services = this.services.map((service) => ({+ ...service,+ connected: connected.includes(service.id),+ stale: stale.has(service.id),+ }));const requested = services.find((service) => service.id === this.requestedToolkit());if (target && !this.error && !this.loading)mountConnectionPicker(target,requested ? [requested] : services,- (service) => this.authorize(service),+ (service) => this.authorize(service, this.staleAccount(service.id)),requested ? { query: "", expanded: false } : this.pickerState,requested,);@@ -228,6 +241,47 @@ export class OnboardingWelcome extends LitElement {window.removeEventListener("focus", this.refreshConnections);document.removeEventListener("visibilitychange", this.refreshConnections);}+ private staleToolkits(): Set<string> {+ if (this.preview) return new Set();+ const toolkits = new Set(this.connections.map((account) => account.toolkit));+ return new Set(+ [...toolkits].filter((toolkit) =>+ this.connections.every((account) => account.toolkit !== toolkit || account.missingScopes?.length),+ ),+ );+ }+ private staleAccount(toolkit: string): string | undefined {+ return this.staleToolkits().has(toolkit)+ ? this.connections.find((account) => account.toolkit === toolkit)?.id+ : undefined;+ }+ private async disconnect(account: ConnectedAccount, name: string): Promise<boolean> {+ this.disconnecting = account.id;+ this.connectionError = "";+ this.requestUpdate();+ try {+ const response = await fetch(`${this.base}api/composio/disconnect`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ accountId: account.id }),+ });+ if (!response.ok && response.status !== 404) throw new Error(`Could not disconnect ${name}. Please try again.`);+ this.connections = this.connections.filter((candidate) => candidate.id !== account.id);+ return true;+ } catch (error) {+ this.connectionError = error instanceof Error ? error.message : `Could not disconnect ${name}.`;+ return false;+ } finally {+ this.disconnecting = "";+ this.requestUpdate();+ await this.updateComplete;+ this.drawPicker();+ }+ }+ private confirmDisconnect(account: ConnectedAccount, name: string): void {+ if (window.confirm(`Disconnect ${name}? QM will lose access to it until you connect it again.`))+ void this.disconnect(account, name);+ }private requestedToolkit(): string {return this.services.some((service) => service.id === this.toolkit) ? this.toolkit : "";}@@ -236,7 +290,7 @@ export class OnboardingWelcome extends LitElement {const controller = (this.connectionsController = new AbortController());this.connectionError = "";try {- const accounts: Array<{ id: string; toolkit: string }> = [];+ const accounts: ConnectedAccount[] = [];const seen = new Set<string>();let cursor = "";do {@@ -265,6 +319,11 @@ export class OnboardingWelcome extends LitElement {if (this.connectionOutcome === "success") {completeConnectionReturn(this.previewUser(), attempt.state);this.realReturn = null;+ const replaced = accounts.find(+ (account) => account.id === attempt.replaces && account.id !== attempt.accountId,+ );+ if (replaced && !(await this.disconnect(replaced, attempt.service.name)))+ this.connectionError = `${attempt.service.name} is reconnected, but the old connection is still there. Disconnect it below.`;if (attempt.service.id === this.toolkit && !continuedAttempts.has(attempt.state)) {continuedAttempts.add(attempt.state);this.onConnected?.(attempt.service.name);@@ -326,7 +385,7 @@ export class OnboardingWelcome extends LitElement {});}}- private async authorize(service: ConnectionService): Promise<void> {+ private async authorize(service: ConnectionService, replaces?: string): Promise<void> {if (this.authorizing) return;if (this.preview) {startPreviewAttempt(this.previewUser(), service, this.pickerState, this.closest(".chat-scroll")?.scrollTop ?? 0);@@ -342,6 +401,7 @@ export class OnboardingWelcome extends LitElement {user: this.previewUser(),service: { id: service.id, name: service.name },accountId: "",+ ...(replaces ? { replaces } : {}),widget: this.returnKey,expiresAt: Date.now() + 20 * 60_000,path: location.pathname,@@ -356,7 +416,7 @@ export class OnboardingWelcome extends LitElement {});const result = await response.json();if (!response.ok) throw new Error(result.message ?? "Could not open authorization. Please try again.");- if (typeof result.accountId !== "string" || !/^ca_[a-zA-Z0-9_-]+$/.test(result.accountId))+ if (typeof result.accountId !== "string" || !ACCOUNT_ID.test(result.accountId))throw new Error("Could not start authorization. Please try again.");saveConnectionAttempt({ ...attempt, accountId: result.accountId });window.location.assign(result.url);@@ -402,9 +462,11 @@ export class OnboardingWelcome extends LitElement {? previewConnections(this.previewUser()): this.connections.map((account) => account.toolkit);const requested = this.requestedToolkit();- const connectedServices = [...new Set(connected)]- .filter((id) => !requested || id === requested)- .map((id) => this.services.find((service) => service.id === id) ?? { id, name: id });+ const connectedAccounts = (+ this.preview ? connected.map((toolkit) => ({ id: "", toolkit }) as ConnectedAccount) : this.connections+ ).filter((account) => !requested || account.toolkit === requested);+ const serviceFor = (id: string) =>+ this.services.find((service) => service.id === id) ?? { id, name: id, description: "", popularity: 0 };const outcome = {"": { title: "", detail: "" },checking: {@@ -529,9 +591,35 @@ export class OnboardingWelcome extends LitElement {${!this.preview && this.connectionOutcome === "failed" ? html`<button class="btn" @click=${() => void this.loadConnections()}>Check again</button>` : nothing}<div class="welcome-picker" ?inert=${Boolean(this.authorizing)}></div>${- connectedServices.length+ connectedAccounts.length? html`<div class="connection-connected" role="status" aria-live="polite">- ${connectedServices.map((service) => html`<span>${icon(Check, 10)}${service.name} connected</span>`)}+ ${connectedAccounts.map((account) => {+ const service = serviceFor(account.toolkit);+ const stale = Boolean(account.missingScopes?.length);+ return html`<span class=${stale ? "stale" : ""}+ >${icon(stale ? TriangleAlert : Check, 10)}${`${service.name} ${stale ? "needs new permissions" : "connected"}`}+ ${+ account.id+ ? html`<button+ type="button"+ class="kc-text-action"+ ?disabled=${Boolean(this.authorizing || this.disconnecting)}+ @click=${() => void this.authorize(service, account.id)}+ >+ Reconnect+ </button>+ <button+ type="button"+ class="kc-text-action danger"+ ?disabled=${Boolean(this.authorizing || this.disconnecting)}+ @click=${() => this.confirmDisconnect(account, service.name)}+ >+ Disconnect+ </button>`+ : nothing+ }</span+ >`;+ })}</div>`: nothing}diff --git a/plugins/web-ui/test/api-body-parsing.test.ts b/plugins/web-ui/test/api-body-parsing.test.tsindex 1f0c16b33..95edcf2dd 100644--- a/plugins/web-ui/test/api-body-parsing.test.ts+++ b/plugins/web-ui/test/api-body-parsing.test.ts@@ -165,6 +165,17 @@ test("app authorization accepts existing browser payloads and validates new retuassert.equal(calls.length, before);});+test("app disconnection forwards only the chosen account to core", async () => {+ const response = await fetch(`${base}/api/composio/disconnect`, {+ method: "POST",+ headers,+ body: JSON.stringify({ accountId: "ca_mine", user_id: "bob", principalId: "bob" }),+ });+ assert.equal(response.status, 200);+ assert.ok(calls.at(-1)?.url.startsWith("/v1/composio/disconnect"));+ assert.deepEqual(calls.at(-1)?.body, { accountId: "ca_mine" });+});+test("Composio verifier forwards only the opaque session and redirects safely", async () => {composioReturnTo = "http://localhost:8790//evil.example/path";const response = await fetch(`${base}/api/composio/callback?session_uri=opaque&user_id=bob`, {diff --git a/plugins/web-ui/test/connection-reconnect-cancelled.test.ts b/plugins/web-ui/test/connection-reconnect-cancelled.test.tsnew file mode 100644index 000000000..7452c2007--- /dev/null+++ b/plugins/web-ui/test/connection-reconnect-cancelled.test.ts@@ -0,0 +1,37 @@+import assert from "node:assert/strict";+import test from "node:test";+import { harness } from "./deep-link-boot-fixture.ts";++test("a cancelled reconnect leaves the existing connection in place", async () => {+ const disconnects: string[] = [];+ const h = await harness({+ path: "/s/sess-deep?composioReturn=return-nonce&status=failed&error=access_denied&connectedAccountId=ca_test",+ connectionReturn: true,+ returnWidget: "reply:1:0:0",+ returnReplaces: "ca_old",+ api: (path) => {+ if (path.startsWith("/api/composio/connections"))+ return Response.json({ items: [{ id: "ca_old", toolkit: "gmail", missingScopes: ["gmail.send"] }] });+ if (path === "/api/composio/disconnect") disconnects.push(path);+ return undefined;+ },+ });+ try {+ await h.boot();+ const widget = Object.assign(document.createElement("qm-onboarding-welcome"), {+ me: { org: "test", user: "tester" },+ widget: "apps",+ setupOnly: true,+ toolkit: "gmail",+ returnKey: "reply:1:0:0",+ });+ document.querySelector(".message-stack")!.append(widget);+ for (let i = 0; i < 200 && !/wasn’t connected/.test(widget.textContent ?? ""); i++)+ await new Promise((resolve) => setTimeout(resolve, 5));+ assert.match(widget.textContent ?? "", /Gmail wasn’t connected/);+ assert.match(widget.textContent ?? "", /Gmail needs new permissions/);+ assert.deepEqual(disconnects, []);+ } finally {+ await h.close();+ }+});diff --git a/plugins/web-ui/test/connection-reconnect-return.test.ts b/plugins/web-ui/test/connection-reconnect-return.test.tsnew file mode 100644index 000000000..604a7ceb9--- /dev/null+++ b/plugins/web-ui/test/connection-reconnect-return.test.ts@@ -0,0 +1,43 @@+import assert from "node:assert/strict";+import test from "node:test";+import { harness } from "./deep-link-boot-fixture.ts";++test("a verified reconnect removes the replaced connection only after the new one is active", async () => {+ const disconnects: unknown[] = [];+ let items = [+ { id: "ca_old", toolkit: "gmail", missingScopes: ["gmail.send"] },+ { id: "ca_test", toolkit: "gmail", missingScopes: [] },+ ];+ const h = await harness({+ path: "/s/sess-deep?composioReturn=return-nonce&status=success&connectedAccountId=ca_test",+ connectionReturn: true,+ returnWidget: "reply:1:0:0",+ returnReplaces: "ca_old",+ api: (path, init) => {+ if (path.startsWith("/api/composio/connections")) return Response.json({ items, nextCursor: null });+ if (path !== "/api/composio/disconnect") return undefined;+ const body = JSON.parse(String(init?.body));+ disconnects.push(body);+ items = items.filter((item) => item.id !== body.accountId);+ return Response.json({ disconnected: body.accountId, toolkit: "gmail" });+ },+ });+ try {+ await h.boot();+ const widget = Object.assign(document.createElement("qm-onboarding-welcome"), {+ me: { org: "test", user: "tester" },+ widget: "apps",+ setupOnly: true,+ toolkit: "gmail",+ returnKey: "reply:1:0:0",+ });+ document.querySelector(".message-stack")!.append(widget);+ for (let i = 0; i < 200 && !(disconnects.length && /Gmail connected/.test(widget.textContent ?? "")); i++)+ await new Promise((resolve) => setTimeout(resolve, 5));+ assert.deepEqual(disconnects, [{ accountId: "ca_old" }]);+ assert.equal(widget.querySelectorAll(".connection-connected > span").length, 1);+ assert.doesNotMatch(widget.textContent ?? "", /needs new permissions/);+ } finally {+ await h.close();+ }+});diff --git a/plugins/web-ui/test/connection-reconnect.test.ts b/plugins/web-ui/test/connection-reconnect.test.tsnew file mode 100644index 000000000..2042beba7--- /dev/null+++ b/plugins/web-ui/test/connection-reconnect.test.ts@@ -0,0 +1,70 @@+import assert from "node:assert/strict";+import test from "node:test";+import { harness } from "./deep-link-boot-fixture.ts";++const settle = async (done: () => boolean) => {+ for (let i = 0; i < 200 && !done(); i++) await new Promise((resolve) => setTimeout(resolve, 5));+};++function gmailWidget(): HTMLElement {+ const widget = Object.assign(document.createElement("qm-onboarding-welcome"), {+ me: { org: "test", user: "tester" },+ widget: "apps",+ setupOnly: true,+ toolkit: "gmail",+ returnKey: "reply:1:0:0",+ });+ document.querySelector(".message-stack")!.append(widget);+ return widget;+}++test("a connection missing configured permissions can be reconnected or disconnected", async () => {+ const posts: Array<{ path: string; body: Record<string, unknown> }> = [];+ let items = [{ id: "ca_old", toolkit: "gmail", missingScopes: ["gmail.send"] }];+ const h = await harness({+ path: "/s/sess-deep",+ api: (path, init) => {+ if (path.startsWith("/api/composio/connections")) return Response.json({ items, nextCursor: null });+ if (init?.method !== "POST" || !path.startsWith("/api/composio/")) return undefined;+ const body = JSON.parse(String(init.body));+ posts.push({ path, body });+ if (path === "/api/composio/disconnect") {+ items = [];+ return Response.json({ disconnected: body.accountId, toolkit: "gmail" });+ }+ return Response.json({ url: "https://connect.composio.dev/link/lk_test", accountId: "ca_new" });+ },+ });+ try {+ await h.boot();+ const widget = gmailWidget();+ await settle(() => Boolean(widget.querySelector(".connection-picker-app")));+ const app = widget.querySelector<HTMLButtonElement>(".connection-picker-app")!;+ assert.equal(app.disabled, false);+ assert.equal(app.getAttribute("aria-label"), "Reconnect Gmail");+ assert.match(widget.textContent ?? "", /Gmail needs new permissions/);+ app.click();+ await settle(() => JSON.parse(sessionStorage.getItem("qm-connection-return:test:tester") ?? "{}").accountId);+ assert.deepEqual(+ posts.map((post) => [post.path, post.body.toolkit]),+ [["/api/composio/authorize", "gmail"]],+ );+ const attempt = JSON.parse(sessionStorage.getItem("qm-connection-return:test:tester")!);+ assert.deepEqual([attempt.accountId, attempt.replaces], ["ca_new", "ca_old"]);++ const disconnect = [...widget.querySelectorAll<HTMLButtonElement>(".connection-connected button")].find(+ (button) => button.textContent?.trim() === "Disconnect",+ )!;+ const answers = [false, true];+ window.confirm = () => answers.shift()!;+ disconnect.click();+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.equal(posts.length, 1);+ disconnect.click();+ await settle(() => !widget.querySelector(".connection-connected"));+ assert.deepEqual(posts.at(-1), { path: "/api/composio/disconnect", body: { accountId: "ca_old" } });+ assert.equal(widget.querySelector(".connection-picker-app")?.getAttribute("aria-label"), "Connect Gmail");+ } finally {+ await h.close();+ }+});diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.tsindex a08e60815..675b9746f 100644--- a/plugins/web-ui/test/deep-link-boot-fixture.ts+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts@@ -46,6 +46,7 @@ interface HarnessOptions {connectionReturn?: boolean;slackReturn?: "success" | "expired" | "cancelled" | "wrong-account";returnWidget?: string;+ returnReplaces?: string;openNewChat?: boolean;}@@ -107,6 +108,7 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {path: "/s/sess-deep",service: { id: "gmail", name: "Gmail" },accountId: "ca_test",+ ...(opts.returnReplaces ? { replaces: opts.returnReplaces } : {}),widget: opts.returnWidget ?? "welcome",expiresAt: Date.now() + 60000,picker: { query: "mail", expanded: true },diff --git a/skills-seed/composio/SKILL.md b/skills-seed/composio/SKILL.mdindex 3bf3147ac..9336301da 100644--- a/skills-seed/composio/SKILL.md+++ b/skills-seed/composio/SKILL.md@@ -26,6 +26,15 @@ Check `connections` before work that depends on an app. If the app is in the cat- For other apps in Slack conversations, mint a link with `authorize` (step 3 below) and say you'll pick the task back up when they reply.- If the app isn't in the catalog, say so in one sentence and don't show the picker. Look for the provider's official API or MCP server yourself. If it uses API keys, send a secure keychain drop link instead of asking for the key in chat.+## Reconnect or disconnect an app++Each account in `connections` lists `missingScopes`: permissions the app's configuration now requests that this connection never got. Providers like X can't upgrade a token in place, so only a fresh consent fixes it.++- When a tool fails with 403 or an insufficient-scope error and that account's `missingScopes` is non-empty, say so in one sentence and offer to reconnect instead of retrying.+- In web chat, show `::connect-apps{toolkit="twitter"}`. For a connected app it offers Reconnect and Disconnect, and removes the replaced account itself after a verified reconnect.+- Elsewhere, `authorize` a new link (step 3 below). Once the new account ID is listed in `connections`, remove the old one with `apps("disconnect", {accountId})`, never before.+- When asked to remove or reset a connection, call `apps("disconnect", {accountId})` on a turn the user started. It only removes their own connections and can't be undone.+## Backend APIUse the authenticated QM API from the computer through `execute` with an explicit `sandbox_id`. The Composio project key stays in QM's backend. Do not request it from the keychain, install the Composio SDK, use old SDK scripts, or call Composio directly. Existing execute approval and command policies still apply.diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex 58fad06e5..536f11c05 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -30,7 +30,7 @@ const FAMILIES: AgentApiFamily[] = [match: (method, path) =>(method === "GET" &&["identity", "connections", "toolkits", "tools"].some((name) => path === `/v1/composio/${name}`)) ||- (method === "POST" && ["authorize", "execute"].some((name) => path === `/v1/composio/${name}`)),+ (method === "POST" && ["authorize", "execute", "disconnect"].some((name) => path === `/v1/composio/${name}`)),guidance:"Use the composio skill for backend app access. Never load a Composio project key or call its SDK directly. Execution binds accounts to your identity and sharing permissions.",routes: [@@ -51,6 +51,12 @@ const FAMILIES: AgentApiFamily[] = [path: "/v1/composio/execute",summary: "{tool,accountId,version,arguments} executes a discovered tool using your own active connection",},+ {+ method: "POST",+ path: "/v1/composio/disconnect",+ summary:+ "{accountId} permanently removes one of your own connections on a human-started turn; use when asked to remove or reset one, or to retire the old account after a reconnect",+ },{method: "GET",path: "/v1/composio/identity",diff --git a/src/api/routes/composio.ts b/src/api/routes/composio.tsindex 655558514..ce908f50d 100644--- a/src/api/routes/composio.ts+++ b/src/api/routes/composio.ts@@ -18,6 +18,8 @@ import { errMessage, httpFailure, reportFailure } from "../../util/errors.ts";import { activePrincipal, audit } from "./shared.ts";import type { ApiCtx, Route } from "./route.ts";+const ACCOUNT_ID = /^ca_[a-zA-Z0-9_-]+$/;+export function composioUserId(org: string, principal: string): string {return `qm_${createHash("sha256").update(JSON.stringify([org, principal]))@@ -154,9 +156,10 @@ export async function request(path: string,body?: unknown,timeoutMs = 20_000,+ method = body ? "POST" : "GET",): Promise<Record<string, unknown>> {const response = await (ctx.deps.composioFetch ?? fetch)(`https://backend.composio.dev/api/v3.1${path}`, {- method: body ? "POST" : "GET",+ method,headers: { "x-api-key": key, "Content-Type": "application/json" },...(body ? { body: JSON.stringify(body) } : {}),redirect: "error",@@ -247,7 +250,7 @@ async function authorize(ctx: ApiCtx, linkSlack = false): Promise<void> {toolkit,...(callbackUrl ? { callback_url: callbackUrl } : {}),});- if (typeof link.connected_account_id !== "string" || !/^ca_[a-zA-Z0-9_-]+$/.test(link.connected_account_id))+ if (typeof link.connected_account_id !== "string" || !ACCOUNT_ID.test(link.connected_account_id))throw new Error("Invalid account");await ctx.deps.composioReturns?.put(`${userId}:${link.connected_account_id}`, {url: typeof callbackUrl === "string" ? callbackUrl : null,@@ -298,6 +301,52 @@ async function authorize(ctx: ApiCtx, linkSlack = false): Promise<void> {}}+async function ownedAccount(+ ctx: ApiCtx,+ access: { key: string; principal: string },+ accountId: string,+): Promise<{ account: Record<string, unknown>; toolkit: string } | null> {+ const account = await request(ctx, access.key, `/connected_accounts/${encodeURIComponent(accountId)}`);+ const toolkit = (account.toolkit as { slug?: string } | undefined)?.slug;+ return account.id === accountId &&+ typeof account.user_id === "string" &&+ composioUserIds(access.principal).includes(account.user_id) &&+ toolkit &&+ toolkit !== "composio"+ ? { account, toolkit }+ : null;+}++const SCOPES_TTL_MS = 5 * 60_000;+const scopeCache = new Map<string, { scopes: string[]; expiresAt: number }>();++async function configuredScopes(ctx: ApiCtx, key: string, authConfigId: string): Promise<string[]> {+ const cached = scopeCache.get(authConfigId);+ if (cached && cached.expiresAt > Date.now()) return cached.scopes;+ try {+ const config = await request(ctx, key, `/auth_configs/${encodeURIComponent(authConfigId)}`);+ const listed = (config.credentials as { scopes?: unknown } | undefined)?.scopes;+ const scopes = Array.isArray(listed) ? listed.filter((scope): scope is string => typeof scope === "string") : [];+ scopeCache.set(authConfigId, { scopes, expiresAt: Date.now() + SCOPES_TTL_MS });+ return scopes;+ } catch (error) {+ const mask = createExactSecretValueMasker([key]);+ reportFailure("composio: auth config scopes", new Error(mask(redactSecrets(errMessage(error)))), authConfigId);+ return [];+ }+}++function scopeName(scope: string): string {+ return scope.slice(scope.lastIndexOf("/") + 1) || scope;+}++function missingScopes(account: { state?: { val?: { scope?: unknown } } }, configured: string[]): string[] {+ const granted = account.state?.val?.scope;+ if (typeof granted !== "string" || !granted.trim()) return [];+ const held = new Set(granted.split(/[\s,]+/).map(scopeName));+ return configured.filter((scope) => !held.has(scopeName(scope)));+}+async function connections(ctx: ApiCtx): Promise<void> {const access = await credential(ctx);if (!access) return;@@ -309,20 +358,33 @@ async function connections(ctx: ApiCtx): Promise<void> {try {const data = await request(ctx, access.key, `/connected_accounts?${query}`);if (!Array.isArray(data.items)) throw new Error("Invalid accounts");- const items = data.items.flatMap((item) => {- if (- !item ||- !userIds.includes(item.user_id) ||- item.status !== "ACTIVE" ||- item.is_disabled === true ||- typeof item.id !== "string" ||- !/^ca_[a-zA-Z0-9_-]+$/.test(item.id) ||- typeof item.toolkit?.slug !== "string" ||- !/^[a-zA-Z0-9_-]{1,100}$/.test(item.toolkit.slug)- )- return [];- return [{ id: item.id, toolkit: item.toolkit.slug, userId: item.user_id }];- });+ const accounts = data.items.filter(+ (item) =>+ item &&+ userIds.includes(item.user_id) &&+ item.status === "ACTIVE" &&+ item.is_disabled !== true &&+ typeof item.id === "string" &&+ ACCOUNT_ID.test(item.id) &&+ typeof item.toolkit?.slug === "string" &&+ /^[a-zA-Z0-9_-]{1,100}$/.test(item.toolkit.slug),+ );+ const configIds = [+ ...new Set(+ accounts+ .map((item) => item.auth_config?.id)+ .filter((id): id is string => typeof id === "string" && /^ac_[a-zA-Z0-9_-]+$/.test(id)),+ ),+ ];+ const scopes = new Map(+ await Promise.all(configIds.map(async (id) => [id, await configuredScopes(ctx, access.key, id)] as const)),+ );+ const items = accounts.map((item) => ({+ id: item.id,+ toolkit: item.toolkit.slug,+ userId: item.user_id,+ missingScopes: missingScopes(item, scopes.get(item.auth_config?.id) ?? []),+ }));ctx.res.setHeader("Cache-Control", "no-store");return sendJson(ctx.res, 200, {items,@@ -336,6 +398,39 @@ async function connections(ctx: ApiCtx): Promise<void> {}}+async function disconnect(ctx: ApiCtx): Promise<void> {+ if ((ctx.capability && !livePersonCapability(ctx.capability)) || ctx.actor?.imp)+ return sendJson(ctx.res, 403, { error: "human_consent_required" });+ const access = await credential(ctx);+ if (!access) return;+ const accountId = (ctx.body as { accountId?: unknown } | null)?.accountId;+ if (typeof accountId !== "string" || !ACCOUNT_ID.test(accountId))+ return sendJson(ctx.res, 400, { error: "invalid_account" });+ try {+ const owned = await ownedAccount(ctx, access, accountId);+ if (!owned) return sendJson(ctx.res, 403, { error: "connection_not_authorized" });+ const { toolkit } = owned;+ if (!(await activeRun(ctx))) return;+ await request(ctx, access.key, `/connected_accounts/${encodeURIComponent(accountId)}`, undefined, 20_000, "DELETE");+ audit(ctx.deps, {+ principalId: access.principal,+ action: "composio.disconnected",+ resource: `${toolkit}/${accountId}`,+ scopeLabel: ctx.capability?.scopeId ?? scopeId("personal", access.principal),+ });+ return sendJson(ctx.res, 200, { disconnected: accountId, toolkit });+ } catch (error) {+ if (error instanceof ComposioHttpError && error.status === 404)+ return sendJson(ctx.res, 404, { error: "connection_not_found" });+ const mask = createExactSecretValueMasker([access.key]);+ reportFailure("composio: disconnect", new Error(mask(redactSecrets(errMessage(error)))));+ return sendJson(ctx.res, 502, {+ error: "composio_disconnect_failed",+ message: "Could not disconnect the app. Please try again.",+ });+ }+}+async function tools(ctx: ApiCtx): Promise<void> {const access = await credential(ctx);if (!access) return;@@ -379,7 +474,7 @@ async function execute(ctx: ApiCtx): Promise<void> {!/^[A-Z][A-Z0-9_]{1,199}$/.test(body.tool) ||body.tool.startsWith("COMPOSIO_") ||typeof body.accountId !== "string" ||- !/^ca_[a-zA-Z0-9_-]+$/.test(body.accountId) ||+ !ACCOUNT_ID.test(body.accountId) ||typeof body.version !== "string" ||!/^[a-zA-Z0-9_-]{1,100}$/.test(body.version) ||body.version === "latest" ||@@ -393,18 +488,10 @@ async function execute(ctx: ApiCtx): Promise<void> {});const resource = `${body.accountId}/${body.tool}@${body.version}`;try {- const account = await request(ctx, access.key, `/connected_accounts/${encodeURIComponent(body.accountId)}`);- const toolkit = (account.toolkit as { slug?: string } | undefined)?.slug;- if (- account.id !== body.accountId ||- typeof account.user_id !== "string" ||- !composioUserIds(access.principal).includes(account.user_id) ||- account.status !== "ACTIVE" ||- account.is_disabled === true ||- !toolkit ||- toolkit === "composio"- )+ const owned = await ownedAccount(ctx, access, body.accountId);+ if (!owned || owned.account.status !== "ACTIVE" || owned.account.is_disabled === true)return sendJson(ctx.res, 403, { error: "connection_not_authorized" });+ const { account, toolkit } = owned;const tool = await request(ctx,access.key,@@ -417,7 +504,7 @@ async function execute(ctx: ApiCtx): Promise<void> {)return sendJson(ctx.res, 403, { error: "tool_not_authorized" });if (!(await activeRun(ctx))) return;- if (!composioUserIds(access.principal).includes(account.user_id))+ if (!composioUserIds(access.principal).includes(String(account.user_id)))return sendJson(ctx.res, 403, { error: "connection_not_authorized" });audit(ctx.deps, {principalId: access.principal,@@ -494,7 +581,7 @@ async function completeAuth(ctx: ApiCtx): Promise<void> {session_uri: sessionUri,user_id: userId,});- if (typeof result.connected_account_id !== "string" || !/^ca_[a-zA-Z0-9_-]+$/.test(result.connected_account_id))+ if (typeof result.connected_account_id !== "string" || !ACCOUNT_ID.test(result.connected_account_id))throw new Error("Invalid account");accountId = result.connected_account_id;} catch (error) {@@ -619,7 +706,7 @@ async function completeSlack(ctx: ApiCtx): Promise<void> {typeof proof.exp !== "number" ||proof.exp <= Date.now() ||typeof proof.accountId !== "string" ||- !/^ca_[a-zA-Z0-9_-]+$/.test(proof.accountId)+ !ACCOUNT_ID.test(proof.accountId))return sendJson(res, 400, {error: "invalid_link",@@ -780,5 +867,6 @@ export const composioRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/composio/connections", auth: "either", handle: connections },{ method: "GET", path: "/v1/composio/toolkits", auth: "either", handle: catalog },{ method: "POST", path: "/v1/composio/authorize", auth: "either", handle: authorize },+ { method: "POST", path: "/v1/composio/disconnect", auth: "either", handle: disconnect },{ method: "GET", path: "/v1/composio/identity", auth: "either", handle: identity },];diff --git a/test/composio-route.test.ts b/test/composio-route.test.tsindex 5f145e71c..54fa87fab 100644--- a/test/composio-route.test.ts+++ b/test/composio-route.test.ts@@ -258,7 +258,7 @@ test("connections return only this actor's active accounts and strip credentialsconst r = await f.invoke("/v1/composio/connections?user_ids=bob&cursor=page-1");assert.equal(r.status, 200);assert.deepEqual(r.data, {- items: [{ id: "ca_gmail", toolkit: "gmail", userId: composioUserId(orgId(), "alice") }],+ items: [{ id: "ca_gmail", toolkit: "gmail", userId: composioUserId(orgId(), "alice"), missingScopes: [] }],nextCursor: "next-page",});const q = new URL(f.calls[0]!.url).searchParams;@@ -268,6 +268,139 @@ test("connections return only this actor's active accounts and strip credentialsassert.doesNotMatch(r.text, /secret-token|private-key|user_id/);});+test("connections report scopes the app's configuration grants that an older connection lacks", async () => {+ const f = fixture();+ await f.own();+ const account = (id: string, scope: string | undefined, config = "ac_x") => ({+ id,+ user_id: composioUserId(orgId(), "alice"),+ status: "ACTIVE",+ toolkit: { slug: "twitter" },+ auth_config: { id: config },+ state: { authScheme: "OAUTH2", val: { scope, access_token: "secret-token" } },+ });+ f.replies.push(+ {+ items: [+ account("ca_old", "tweet.read users.read offline.access"),+ account("ca_new", "tweet.read users.read offline.access dm.read dm.write"),+ account("ca_unknown", undefined),+ account("ca_unreadable", "tweet.read", "ac_gone"),+ ],+ },+ {+ credentials: {+ scopes: ["tweet.read", "users.read", "offline.access", "dm.read", "dm.write"],+ client_secret: "s3",+ },+ },+ new Response("missing", { status: 404 }),+ );+ const r = await f.invoke("/v1/composio/connections");+ assert.equal(r.status, 200);+ assert.deepEqual(+ r.data.items.map((item: { id: string; missingScopes: string[] }) => [item.id, item.missingScopes]),+ [+ ["ca_old", ["dm.read", "dm.write"]],+ ["ca_new", []],+ ["ca_unknown", []],+ ["ca_unreadable", []],+ ],+ );+ assert.deepEqual(+ f.calls.slice(1).map((call) => new URL(call.url).pathname),+ ["/api/v3.1/auth_configs/ac_x", "/api/v3.1/auth_configs/ac_gone"],+ );+ assert.doesNotMatch(r.text, /secret-token|s3|private-key/);+ f.replies.push({ items: [account("ca_old", "tweet.read"), account("ca_unreadable", "tweet.read", "ac_gone")] }, {});+ await f.invoke("/v1/composio/connections");+ assert.deepEqual(+ f.calls.slice(3).map((call) => new URL(call.url).pathname),+ ["/api/v3.1/connected_accounts", "/api/v3.1/auth_configs/ac_gone"],+ );+});++test("scopes granted in URL form match their short configured names", async () => {+ const f = fixture();+ await f.own();+ f.replies.push(+ {+ items: [+ {+ id: "ca_outlook",+ user_id: composioUserId(orgId(), "alice"),+ status: "ACTIVE",+ toolkit: { slug: "outlook" },+ auth_config: { id: "ac_outlook" },+ state: { val: { scope: "https://graph.microsoft.com/Mail.Read offline_access https://mail.google.com/" } },+ },+ ],+ },+ { credentials: { scopes: ["Mail.Read", "offline_access", "https://mail.google.com/", "Mail.Send"] } },+ );+ const r = await f.invoke("/v1/composio/connections");+ assert.deepEqual(r.data.items[0].missingScopes, ["Mail.Send"]);+});++test("people can disconnect only their own connections, on a turn they started", async () => {+ const f = fixture();+ await f.own();+ const mine = {+ id: "ca_mine",+ user_id: composioUserId(orgId(), "alice"),+ status: "EXPIRED",+ toolkit: { slug: "twitter" },+ };+ f.replies.push(mine, {});+ const r = await f.invoke("/v1/composio/disconnect", { accountId: "ca_mine" });+ assert.deepEqual([r.status, r.data], [200, { disconnected: "ca_mine", toolkit: "twitter" }]);+ assert.deepEqual(+ f.calls.map((call) => [call.init?.method, new URL(call.url).pathname]),+ [+ ["GET", "/api/v3.1/connected_accounts/ca_mine"],+ ["DELETE", "/api/v3.1/connected_accounts/ca_mine"],+ ],+ );+ assert.deepEqual(+ f.audits.filter((e) => e.action === "composio.disconnected").map((e) => e.resource),+ ["twitter/ca_mine"],+ );++ f.replies.push(mine, {});+ assert.equal((await f.invoke("/v1/composio/disconnect", { accountId: "ca_mine" }, null, privateCap)).status, 200);++ for (const account of [+ { ...mine, user_id: composioUserId(orgId(), "bob") },+ { ...mine, id: "ca_other" },+ { ...mine, toolkit: { slug: "composio" } },+ ]) {+ const g = fixture();+ await g.own();+ g.replies.push(account);+ assert.equal((await g.invoke("/v1/composio/disconnect", { accountId: "ca_mine" })).status, 403);+ assert.ok(g.calls.every((call) => call.init?.method === "GET"));+ }++ const g = fixture();+ await g.own();+ g.replies.push(new Response("gone", { status: 404 }));+ assert.equal((await g.invoke("/v1/composio/disconnect", { accountId: "ca_mine" })).status, 404);+});++test("disconnecting refuses automations, impersonation and malformed accounts before provider calls", async () => {+ for (const [body, actor, capability, impersonating, status] of [+ [{ accountId: "ca_mine" }, null, { ...privateCap, liveActor: false, triggered: true }, false, 403],+ [{ accountId: "ca_mine" }, "alice", undefined, true, 403],+ [{ accountId: "../ca_mine" }, "alice", undefined, false, 400],+ [{ accountId: "ca_mine" }, null, undefined, false, 401],+ ] as const) {+ const f = fixture();+ await f.own();+ assert.equal((await f.invoke("/v1/composio/disconnect", body, actor, capability, impersonating)).status, status);+ assert.equal(f.calls.length, 0);+ }+});+test("connections require credential access and fail visibly on upstream errors", async () => {const f = fixture();assert.equal((await f.invoke("/v1/composio/connections", undefined, null)).status, 401);@@ -618,6 +751,23 @@ test("ending the run during account lookup prevents execution", async () => {assert.ok(f.calls.every((call) => call.init?.method === "GET"));});+test("ending the run during account lookup prevents disconnecting", async () => {+ const f = fixture();+ await f.own();+ const original = f.deps.composioFetch!;+ f.deps.composioFetch = async (...args) => {+ const response = await original(...args);+ f.deps.runs = { get: async () => ({ status: "done" }) } as unknown as ServerDeps["runs"];+ return response;+ };+ f.replies.push(aliceAccount);+ assert.equal((await f.invoke("/v1/composio/disconnect", { accountId: "ca_alice" }, null, privateCap)).status, 403);+ assert.deepEqual(+ f.calls.map((call) => call.init?.method),+ ["GET"],+ );+});+test("shared org connections recheck grants for every audience member", async () => {const f = fixture();await f.shared(false);@@ -732,8 +882,8 @@ test("linked account discovery and Slack status preserve historical aliases withconst listed = await f.invoke("/v1/composio/connections?cursor=page");assert.equal(listed.status, 200);assert.deepEqual(listed.data.items, [- { id: "ca_legacy", toolkit: "slack", userId: composioUserId(orgId(), aliasId) },- { id: "ca_current", toolkit: "slack", userId: composioUserId(orgId(), "alice") },+ { id: "ca_legacy", toolkit: "slack", userId: composioUserId(orgId(), aliasId), missingScopes: [] },+ { id: "ca_current", toolkit: "slack", userId: composioUserId(orgId(), "alice"), missingScopes: [] },]);assert.equal(listed.data.nextCursor, "next");const query = new URL(f.calls.at(-1)!.url).searchParams;@@ -854,8 +1004,8 @@ test("linked identities retain provider accounts and Slack status until unlinkedconst listed = await f.invoke("/v1/composio/connections?cursor=page");assert.deepEqual(listed.data, {items: [- { id: "ca_old", toolkit: "slack", userId: alias },- { id: "ca_new", toolkit: "slack", userId: canonical },+ { id: "ca_old", toolkit: "slack", userId: alias, missingScopes: [] },+ { id: "ca_new", toolkit: "slack", userId: canonical, missingScopes: [] },],nextCursor: "next",});