Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(plugins): add Composio integrations (#157)

Leoe44a0f044d81
diff --git a/apps/server/package.json b/apps/server/package.json
index acf18952b..78a74cff0 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -28,6 +28,7 @@
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
"@chat-adapter/state-memory": "4.39.0",
"@chat-adapter/whatsapp": "4.39.0",
+ "@composio/core": "0.18.0",
"@daytona/sdk": "^0.207.0",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index a4edc1b31..071081079 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -37,6 +37,12 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.serverRemoveKeybinding]: AuthOrchestrationOperateScope,
[WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
[WS_METHODS.serverUpdateSettings]: AuthOrchestrationOperateScope,
+ [WS_METHODS.composioGetStatus]: AuthOrchestrationReadScope,
+ [WS_METHODS.composioConfigure]: AuthOrchestrationOperateScope,
+ [WS_METHODS.composioRemove]: AuthOrchestrationOperateScope,
+ [WS_METHODS.composioSearchToolkits]: AuthOrchestrationReadScope,
+ [WS_METHODS.composioAuthorize]: AuthOrchestrationOperateScope,
+ [WS_METHODS.composioDisconnect]: AuthOrchestrationOperateScope,
[WS_METHODS.subscriptionAuthList]: AuthOrchestrationReadScope,
[WS_METHODS.subscriptionAuthStart]: AuthOrchestrationOperateScope,
[WS_METHODS.subscriptionAuthPoll]: AuthOrchestrationOperateScope,
diff --git a/apps/server/src/composio/ComposioService.test.ts b/apps/server/src/composio/ComposioService.test.ts
new file mode 100644
index 000000000..3dcf0db75
--- /dev/null
+++ b/apps/server/src/composio/ComposioService.test.ts
@@ -0,0 +1,378 @@
+import { Composio } from "@composio/core";
+import { it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as Option from "effect/Option";
+import { describe, expect, vi } from "vite-plus/test";
+
+import type { ServerSecretStore } from "../auth/ServerSecretStore.ts";
+import { toClaudeMcpServers } from "../provider/McpServerConfig.ts";
+import { make } from "./ComposioService.ts";
+
+function makeSecretStore(initial: Readonly<Record<string, string>> = {}) {
+ const values = new Map(
+ Object.entries(initial).map(([name, value]) => [name, new TextEncoder().encode(value)]),
+ );
+ const store = {
+ get: (name: string) => Effect.sync(() => Option.fromNullishOr(values.get(name))),
+ set: (name: string, value: Uint8Array) =>
+ Effect.sync(() => void values.set(name, new Uint8Array(value))),
+ create: (name: string, value: Uint8Array) =>
+ Effect.sync(() => void values.set(name, new Uint8Array(value))),
+ getOrCreateRandom: (name: string, bytes: number) =>
+ Effect.sync(() => {
+ const existing = values.get(name);
+ if (existing) return existing;
+ const value = new Uint8Array(bytes).fill(7);
+ values.set(name, value);
+ return value;
+ }),
+ remove: (name: string) => Effect.sync(() => void values.delete(name)),
+ } satisfies ServerSecretStore["Service"];
+ return { store, values };
+}
+
+function fakeClient(input?: {
+ readonly accounts?: ReadonlyArray<{
+ readonly id: string;
+ readonly toolkit: { readonly slug: string };
+ readonly status: "ACTIVE" | "FAILED";
+ readonly alias?: string | null;
+ }>;
+ readonly authorize?: () => Promise<{
+ readonly id: string;
+ readonly redirectUrl?: string;
+ }>;
+ readonly deleteSession?: () => Promise<void>;
+ readonly sessionCreationGate?: Promise<void>;
+ readonly sessionCreationGates?: readonly Promise<void>[];
+}) {
+ const sessionDeletes: Array<ReturnType<typeof vi.fn<() => Promise<void>>>> = [];
+ const createSession = vi.fn(async () => {
+ await (input?.sessionCreationGates?.[createSession.mock.calls.length - 1] ??
+ input?.sessionCreationGate);
+ const deleteSession = vi.fn(input?.deleteSession ?? (async () => undefined));
+ sessionDeletes.push(deleteSession);
+ return {
+ mcp: {
+ url: "https://app.composio.dev/tool_router/v3/session/mcp",
+ headers: { "x-api-key": "project-key" },
+ },
+ authorize: vi.fn(
+ input?.authorize ??
+ (async () => ({
+ id: "connection-new",
+ redirectUrl: "https://connect.composio.dev/link",
+ })),
+ ),
+ delete: deleteSession,
+ };
+ });
+ const client = {
+ toolkits: { get: vi.fn(async () => []) },
+ connectedAccounts: {
+ list: vi.fn(async () => ({ items: input?.accounts ?? [], totalPages: 1 })),
+ delete: vi.fn(async () => ({})),
+ },
+ sessions: { create: createSession },
+ } as unknown as InstanceType<typeof Composio>;
+ return { client, createSession, sessionDeletes };
+}
+
+describe("ComposioService", () => {
+ it.effect("validates a key before storing it", () =>
+ Effect.gen(function* () {
+ const { store, values } = makeSecretStore();
+ const { client } = fakeClient();
+ const service = make(store, () => client);
+
+ expect(yield* service.configure(" project-key ")).toEqual({
+ configured: true,
+ connections: [],
+ });
+ expect(new TextDecoder().decode(values.get("composio-api-key"))).toBe("project-key");
+ }),
+ );
+
+ it.effect("does not store an invalid key", () =>
+ Effect.gen(function* () {
+ const { store, values } = makeSecretStore();
+ const { client } = fakeClient();
+ vi.mocked(client.toolkits.get).mockRejectedValueOnce(
+ Object.assign(new Error(), { status: 401 }),
+ );
+ const service = make(store, () => client);
+
+ const error = yield* Effect.flip(service.configure("bad-key"));
+ expect(error).toMatchObject({ message: "The Composio API key is invalid." });
+ expect(values.has("composio-api-key")).toBe(false);
+ }),
+ );
+
+ it.effect("deletes its hosted session after starting authorization", () =>
+ Effect.gen(function* () {
+ const { store } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, sessionDeletes } = fakeClient();
+ const service = make(store, () => client);
+
+ expect(yield* service.authorize({ toolkitSlug: "gmail" })).toEqual({
+ connectionId: "connection-new",
+ redirectUrl: "https://connect.composio.dev/link",
+ });
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(1);
+ }),
+ );
+
+ it.effect("deletes its hosted session when authorization fails", () =>
+ Effect.gen(function* () {
+ const { store } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, sessionDeletes } = fakeClient({
+ authorize: () => Promise.reject(new Error("authorization failed")),
+ });
+ const service = make(store, () => client);
+
+ expect(yield* Effect.flip(service.authorize({ toolkitSlug: "gmail" }))).toMatchObject({
+ operation: "start account authorization",
+ message: "Composio could not start account authorization.",
+ });
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(1);
+ }),
+ );
+
+ it.effect("deletes its hosted session when the authorization URL is missing", () =>
+ Effect.gen(function* () {
+ const { store } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, sessionDeletes } = fakeClient({
+ authorize: async () => ({ id: "connection-new" }),
+ });
+ const service = make(store, () => client);
+
+ expect(yield* Effect.flip(service.authorize({ toolkitSlug: "gmail" }))).toMatchObject({
+ operation: "start account authorization",
+ message: "Composio could not start account authorization.",
+ });
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(1);
+ }),
+ );
+
+ it.effect("retries failed authorization-session cleanup before authorizing again", () =>
+ Effect.gen(function* () {
+ let cleanupAttempt = 0;
+ const { store } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, createSession, sessionDeletes } = fakeClient({
+ deleteSession: async () => {
+ cleanupAttempt += 1;
+ if (cleanupAttempt === 1) throw new Error("cleanup response was lost");
+ if (cleanupAttempt === 2) {
+ throw Object.assign(new Error("session not found"), { status: 404 });
+ }
+ },
+ });
+ const service = make(store, () => client);
+
+ expect(yield* Effect.flip(service.authorize({ toolkitSlug: "gmail" }))).toMatchObject({
+ operation: "start account authorization",
+ message: "Composio could not start account authorization.",
+ });
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(1);
+
+ expect(yield* service.authorize({ toolkitSlug: "gmail" })).toEqual({
+ connectionId: "connection-new",
+ redirectUrl: "https://connect.composio.dev/link",
+ });
+ expect(createSession).toHaveBeenCalledTimes(2);
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(2);
+ expect(sessionDeletes[1]).toHaveBeenCalledTimes(1);
+ }),
+ );
+
+ it.effect("keeps multiple accounts and MCP headers in transient runtime state", () =>
+ Effect.gen(function* () {
+ const { store } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, createSession } = fakeClient({
+ accounts: [
+ { id: "gmail-work", toolkit: { slug: "gmail" }, status: "ACTIVE", alias: "Work" },
+ { id: "gmail-home", toolkit: { slug: "gmail" }, status: "ACTIVE", alias: "Home" },
+ { id: "slack-failed", toolkit: { slug: "slack" }, status: "FAILED" },
+ ],
+ });
+ const service = make(store, () => client);
+
+ const status = yield* service.getStatus;
+ expect(status.connections).toHaveLength(3);
+
+ const first = yield* service.resolveRuntimeMcpServer("thread-1");
+ const cached = yield* service.resolveRuntimeMcpServer("thread-1");
+ const secondThread = yield* service.resolveRuntimeMcpServer("thread-2");
+
+ expect(first).toBe(cached);
+ expect(secondThread).toBeDefined();
+ expect(createSession).toHaveBeenCalledTimes(2);
+ expect(createSession).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ connectedAccounts: { gmail: ["gmail-work", "gmail-home"] },
+ multiAccount: expect.objectContaining({ requireExplicitSelection: true }),
+ }),
+ );
+ expect(toClaudeMcpServers([first!])).toEqual({
+ "composio-session": {
+ type: "http",
+ url: "https://app.composio.dev/tool_router/v3/session/mcp",
+ headers: { "x-api-key": "project-key" },
+ },
+ });
+ expect(first).toEqual({
+ id: "composio-session",
+ name: "Composio",
+ transport: "url",
+ url: "https://app.composio.dev/tool_router/v3/session/mcp",
+ enabled: true,
+ createdAt: "1970-01-01T00:00:00.000Z",
+ updatedAt: "1970-01-01T00:00:00.000Z",
+ });
+ }),
+ );
+
+ it.effect("deletes a hosted session before replacing its cached runtime", () =>
+ Effect.gen(function* () {
+ const { store } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, createSession, sessionDeletes } = fakeClient({
+ accounts: [{ id: "gmail-work", toolkit: { slug: "gmail" }, status: "ACTIVE" }],
+ });
+ const service = make(store, () => client);
+
+ yield* service.resolveRuntimeMcpServer("thread-1");
+ vi.mocked(client.connectedAccounts.list).mockResolvedValue({
+ items: [{ id: "slack-work", toolkit: { slug: "slack" }, status: "ACTIVE" }],
+ totalPages: 1,
+ } as never);
+ yield* service.resolveRuntimeMcpServer("thread-1");
+
+ expect(createSession).toHaveBeenCalledTimes(2);
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(1);
+ expect(sessionDeletes[1]).not.toHaveBeenCalled();
+ }),
+ );
+
+ it.effect("keeps failed hosted-session cleanup retryable", () =>
+ Effect.gen(function* () {
+ const { store, values } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, sessionDeletes } = fakeClient({
+ accounts: [{ id: "gmail-work", toolkit: { slug: "gmail" }, status: "ACTIVE" }],
+ });
+ const service = make(store, () => client);
+
+ yield* service.resolveRuntimeMcpServer("thread-1");
+ sessionDeletes[0]!.mockRejectedValueOnce(new Error("cleanup failed"));
+
+ const error = yield* Effect.flip(service.remove);
+ expect(error).toMatchObject({
+ operation: "delete hosted tool sessions",
+ message: "Composio could not delete hosted tool sessions.",
+ });
+ expect(values.has("composio-api-key")).toBe(true);
+
+ expect(yield* service.remove).toEqual({ configured: false, connections: [] });
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(2);
+ expect(values.has("composio-api-key")).toBe(false);
+ }),
+ );
+
+ it.effect("deletes the oldest hosted session before LRU eviction", () =>
+ Effect.gen(function* () {
+ const { store } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, createSession, sessionDeletes } = fakeClient({
+ accounts: [{ id: "gmail-work", toolkit: { slug: "gmail" }, status: "ACTIVE" }],
+ });
+ const service = make(store, () => client);
+
+ for (let index = 0; index <= 100; index += 1) {
+ yield* service.resolveRuntimeMcpServer(`thread-${index}`);
+ }
+
+ expect(createSession).toHaveBeenCalledTimes(101);
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(1);
+ expect(sessionDeletes[1]).not.toHaveBeenCalled();
+ }),
+ );
+
+ it.effect("deletes a runtime session created while an account is disconnected", () =>
+ Effect.gen(function* () {
+ let releaseSessionCreation!: () => void;
+ const sessionCreationGate = new Promise<void>((resolve) => {
+ releaseSessionCreation = resolve;
+ });
+ const { store } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, createSession, sessionDeletes } = fakeClient({
+ accounts: [{ id: "gmail-work", toolkit: { slug: "gmail" }, status: "ACTIVE" }],
+ sessionCreationGate,
+ });
+ const service = make(store, () => client);
+
+ const resolving = yield* Effect.forkChild(service.resolveRuntimeMcpServer("thread-1"));
+ yield* Effect.promise(() => vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1)));
+ yield* service.disconnect("gmail-work");
+ releaseSessionCreation();
+
+ expect(yield* Fiber.join(resolving)).toBeUndefined();
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(1);
+ }),
+ );
+
+ it.effect("shares concurrent runtime resolution for the same resource", () =>
+ Effect.gen(function* () {
+ let releaseSessionCreation!: () => void;
+ const sessionCreationGate = new Promise<void>((resolve) => {
+ releaseSessionCreation = resolve;
+ });
+ const { store } = makeSecretStore({ "composio-api-key": "project-key" });
+ const { client, createSession, sessionDeletes } = fakeClient({
+ accounts: [{ id: "gmail-work", toolkit: { slug: "gmail" }, status: "ACTIVE" }],
+ sessionCreationGate,
+ });
+ const createClient = vi.fn(() => client);
+ const service = make(store, createClient);
+
+ const first = yield* Effect.forkChild(service.resolveRuntimeMcpServer("thread-1"));
+ yield* Effect.promise(() => vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1)));
+ const second = yield* Effect.forkChild(service.resolveRuntimeMcpServer("thread-1"));
+ yield* Effect.promise(() => vi.waitFor(() => expect(createClient).toHaveBeenCalledTimes(2)));
+ releaseSessionCreation();
+
+ expect(yield* Fiber.join(first)).toBe(yield* Fiber.join(second));
+ expect(createSession).toHaveBeenCalledTimes(1);
+ yield* service.remove;
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(1);
+ }),
+ );
+
+ it.effect("starts a new runtime resolution after configuration changes", () =>
+ Effect.gen(function* () {
+ let releaseOldSessionCreation!: () => void;
+ const oldSessionCreationGate = new Promise<void>((resolve) => {
+ releaseOldSessionCreation = resolve;
+ });
+ const { store } = makeSecretStore({ "composio-api-key": "old-key" });
+ const { client, createSession, sessionDeletes } = fakeClient({
+ accounts: [{ id: "gmail-work", toolkit: { slug: "gmail" }, status: "ACTIVE" }],
+ sessionCreationGates: [oldSessionCreationGate, Promise.resolve()],
+ });
+ const service = make(store, () => client);
+
+ const oldResolution = yield* Effect.forkChild(service.resolveRuntimeMcpServer("thread-1"));
+ yield* Effect.promise(() => vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1)));
+ yield* service.configure("new-key");
+
+ expect(yield* service.resolveRuntimeMcpServer("thread-1")).toBeDefined();
+ expect(createSession).toHaveBeenCalledTimes(2);
+ releaseOldSessionCreation();
+ expect(yield* Fiber.join(oldResolution)).toBeUndefined();
+
+ yield* service.remove;
+ expect(sessionDeletes).toHaveLength(2);
+ expect(sessionDeletes[0]).toHaveBeenCalledTimes(1);
+ expect(sessionDeletes[1]).toHaveBeenCalledTimes(1);
+ }),
+ );
+});
diff --git a/apps/server/src/composio/ComposioService.ts b/apps/server/src/composio/ComposioService.ts
new file mode 100644
index 000000000..de9cc77b5
--- /dev/null
+++ b/apps/server/src/composio/ComposioService.ts
@@ -0,0 +1,413 @@
+import { Composio } from "@composio/core";
+import {
+ ComposioOperationError,
+ type ComposioAuthorizeInput,
+ type ComposioAuthorizeResult,
+ type ComposioConnection,
+ type ComposioStatus,
+ type ComposioToolkit,
+ type McpServer,
+ McpServerId,
+} from "@t3tools/contracts";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+
+import { ServerSecretStore } from "../auth/ServerSecretStore.ts";
+import { withMcpRuntimeHeaders } from "../provider/McpServerConfig.ts";
+
+const API_KEY_SECRET = "composio-api-key";
+const USER_ID_SECRET = "composio-user-id";
+const COMPOSIO_MCP_SERVER_ID = McpServerId.make("composio-session");
+const textDecoder = new TextDecoder();
+const textEncoder = new TextEncoder();
+
+type ComposioClient = InstanceType<typeof Composio>;
+type ComposioClientFactory = (apiKey: string) => ComposioClient;
+
+export interface ComposioServiceShape {
+ readonly getStatus: Effect.Effect<ComposioStatus, ComposioOperationError>;
+ readonly configure: (apiKey: string) => Effect.Effect<ComposioStatus, ComposioOperationError>;
+ readonly remove: Effect.Effect<ComposioStatus, ComposioOperationError>;
+ readonly searchToolkits: (input: {
+ readonly query?: string | undefined;
+ readonly limit?: number | undefined;
+ }) => Effect.Effect<readonly ComposioToolkit[], ComposioOperationError>;
+ readonly authorize: (
+ input: ComposioAuthorizeInput,
+ ) => Effect.Effect<ComposioAuthorizeResult, ComposioOperationError>;
+ readonly disconnect: (
+ connectionId: string,
+ ) => Effect.Effect<ComposioStatus, ComposioOperationError>;
+ readonly resolveRuntimeMcpServer: (
+ resourceId: string,
+ ) => Effect.Effect<McpServer | undefined, ComposioOperationError>;
+}
+
+export class ComposioService extends Context.Service<ComposioService, ComposioServiceShape>()(
+ "akeru-bot/composio/ComposioService",
+) {}
+
+function operationError(operation: string, cause: unknown): ComposioOperationError {
+ const status =
+ typeof cause === "object" && cause !== null && "status" in cause
+ ? Number((cause as { readonly status?: unknown }).status)
+ : undefined;
+ const message =
+ status === 401
+ ? "The Composio API key is invalid."
+ : status === 403
+ ? "The Composio API key does not have permission for this operation."
+ : status === 429
+ ? "Composio rate-limited this request. Try again shortly."
+ : `Composio could not ${operation}.`;
+ return new ComposioOperationError({ operation, message });
+}
+
+function isNotFoundError(cause: unknown): boolean {
+ return (
+ typeof cause === "object" &&
+ cause !== null &&
+ "status" in cause &&
+ Number((cause as { readonly status?: unknown }).status) === 404
+ );
+}
+
+const tryComposio = <A>(operation: string, run: () => Promise<A>) =>
+ Effect.tryPromise({
+ try: run,
+ catch: (cause) => operationError(operation, cause),
+ });
+
+function bytesToId(bytes: Uint8Array): string {
+ return `akeru_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
+}
+
+function toConnection(input: {
+ readonly id: string;
+ readonly toolkit: { readonly slug: string };
+ readonly status: ComposioConnection["status"];
+ readonly alias?: string | null;
+}): ComposioConnection {
+ return {
+ id: input.id,
+ toolkitSlug: input.toolkit.slug,
+ status: input.status,
+ ...(input.alias ? { alias: input.alias } : {}),
+ };
+}
+
+export function make(
+ secretStore: ServerSecretStore["Service"],
+ createClient: ComposioClientFactory = (apiKey) => new Composio({ apiKey }),
+): ComposioServiceShape {
+ let runtimeConfigurationGeneration = 0;
+ const pendingHostedSessionDeletes = new Set<() => Promise<void>>();
+ const pendingRuntimeResolutions = new Map<
+ string,
+ {
+ readonly generation: number;
+ readonly promise: Promise<McpServer | undefined>;
+ }
+ >();
+ const runtimeCache = new Map<
+ string,
+ {
+ readonly fingerprint: string;
+ readonly server: McpServer;
+ readonly deleteSession: () => Promise<void>;
+ }
+ >();
+
+ const deleteCachedSession = async (resourceId: string) => {
+ const cached = runtimeCache.get(resourceId);
+ if (!cached) return;
+ try {
+ await cached.deleteSession();
+ } catch (cause) {
+ if (!isNotFoundError(cause)) throw cause;
+ }
+ if (runtimeCache.get(resourceId) === cached) runtimeCache.delete(resourceId);
+ };
+
+ const clearRuntimeCache = async () => {
+ for (const resourceId of runtimeCache.keys()) {
+ await deleteCachedSession(resourceId);
+ }
+ };
+
+ const deletePendingHostedSession = async (deleteSession: () => Promise<void>) => {
+ try {
+ await deleteSession();
+ } catch (cause) {
+ if (!isNotFoundError(cause)) throw cause;
+ }
+ pendingHostedSessionDeletes.delete(deleteSession);
+ };
+
+ const clearPendingHostedSessions = async () => {
+ for (const deleteSession of pendingHostedSessionDeletes) {
+ await deletePendingHostedSession(deleteSession);
+ }
+ };
+
+ const clearHostedSessions = async () => {
+ await clearRuntimeCache();
+ await clearPendingHostedSessions();
+ };
+
+ const invalidateHostedSessions = async () => {
+ runtimeConfigurationGeneration += 1;
+ await clearHostedSessions();
+ };
+
+ const readApiKey = secretStore.get(API_KEY_SECRET).pipe(
+ Effect.mapError((cause) => operationError("read its API key", cause)),
+ Effect.map(Option.map((bytes) => textDecoder.decode(bytes).trim())),
+ Effect.map(Option.filter((apiKey) => apiKey.length > 0)),
+ );
+
+ const readUserId = secretStore.getOrCreateRandom(USER_ID_SECRET, 16).pipe(
+ Effect.map(bytesToId),
+ Effect.mapError((cause) => operationError("prepare its local user", cause)),
+ );
+
+ const withClient = <A>(
+ operation: string,
+ run: (client: ComposioClient, userId: string) => Promise<A>,
+ ) =>
+ Effect.gen(function* () {
+ const apiKey = yield* readApiKey;
+ if (Option.isNone(apiKey)) {
+ return yield* new ComposioOperationError({
+ operation,
+ message: "Connect Composio in Settings first.",
+ });
+ }
+ const userId = yield* readUserId;
+ return yield* tryComposio(operation, () => run(createClient(apiKey.value), userId));
+ });
+
+ const listConnections = (client: ComposioClient, userId: string) =>
+ client.connectedAccounts
+ .list({ userIds: [userId], accountType: "ALL", limit: 100 })
+ .then((response) => response.items.map(toConnection));
+
+ const getStatus: ComposioServiceShape["getStatus"] = Effect.gen(function* () {
+ const apiKey = yield* readApiKey;
+ if (Option.isNone(apiKey)) return { configured: false, connections: [] };
+ const userId = yield* readUserId;
+ const connections = yield* tryComposio("load connected accounts", () =>
+ listConnections(createClient(apiKey.value), userId),
+ );
+ return { configured: true, connections };
+ });
+
+ const configure: ComposioServiceShape["configure"] = (apiKey) =>
+ Effect.gen(function* () {
+ const normalized = apiKey.trim();
+ if (!normalized) {
+ return yield* new ComposioOperationError({
+ operation: "save its API key",
+ message: "Enter a Composio API key.",
+ });
+ }
+ const client = createClient(normalized);
+ yield* tryComposio("validate its API key", () => client.toolkits.get({ limit: 1 }));
+ yield* tryComposio("delete hosted tool sessions", invalidateHostedSessions);
+ yield* secretStore
+ .set(API_KEY_SECRET, textEncoder.encode(normalized))
+ .pipe(Effect.mapError((cause) => operationError("save its API key", cause)));
+ yield* tryComposio("delete hosted tool sessions", invalidateHostedSessions);
+ return yield* getStatus;
+ });
+
+ const remove: ComposioServiceShape["remove"] = Effect.gen(function* () {
+ yield* tryComposio("delete hosted tool sessions", invalidateHostedSessions);
+ yield* secretStore
+ .remove(API_KEY_SECRET)
+ .pipe(Effect.mapError((cause) => operationError("remove its API key", cause)));
+ yield* tryComposio("delete hosted tool sessions", invalidateHostedSessions);
+ return { configured: false, connections: [] };
+ });
+
+ const searchToolkits: ComposioServiceShape["searchToolkits"] = (input) =>
+ withClient("load toolkits", async (client) => {
+ const limit = input.limit ?? 50;
+ const query = input.query?.trim().toLowerCase() ?? "";
+ const toolkits = await client.toolkits.get({ limit: 50, sortBy: "usage" });
+ return toolkits
+ .filter((toolkit) => {
+ if (!query) return true;
+ return [toolkit.name, toolkit.slug, toolkit.meta.description ?? ""]
+ .join(" ")
+ .toLowerCase()
+ .includes(query);
+ })
+ .slice(0, limit)
+ .map(
+ (toolkit): ComposioToolkit => ({
+ slug: toolkit.slug,
+ name: toolkit.name,
+ ...(toolkit.meta.description ? { description: toolkit.meta.description } : {}),
+ ...(toolkit.meta.logo ? { logoUrl: toolkit.meta.logo } : {}),
+ categories: toolkit.meta.categories?.map((category) => category.name) ?? [],
+ toolsCount: toolkit.meta.toolsCount ?? 0,
+ }),
+ );
+ });
+
+ const authorize: ComposioServiceShape["authorize"] = (input) =>
+ withClient("start account authorization", async (client, userId) => {
+ await invalidateHostedSessions();
+ const session = await client.sessions.create(userId, {
+ mcp: true,
+ toolkits: [input.toolkitSlug],
+ manageConnections: true,
+ multiAccount: { enable: true, maxAccountsPerToolkit: 10 },
+ });
+ const deleteSession = () => session.delete().then(() => undefined);
+ pendingHostedSessionDeletes.add(deleteSession);
+ const authorization = await session
+ .authorize(input.toolkitSlug, input.alias ? { alias: input.alias } : undefined)
+ .then((request) => {
+ if (!request.redirectUrl) {
+ throw new Error("Composio did not return an authorization URL.");
+ }
+ return { connectionId: request.id, redirectUrl: request.redirectUrl };
+ })
+ .then(
+ (value) => ({ ok: true as const, value }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+ const cleanup = await deletePendingHostedSession(deleteSession).then(
+ () => ({ ok: true as const }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+ if (!authorization.ok) {
+ if (!cleanup.ok) {
+ throw new AggregateError(
+ [authorization.error, cleanup.error],
+ "Composio authorization and hosted-session cleanup both failed.",
+ { cause: authorization.error },
+ );
+ }
+ throw authorization.error;
+ }
+ if (!cleanup.ok) {
+ throw cleanup.error;
+ }
+ return authorization.value;
+ });
+
+ const disconnect: ComposioServiceShape["disconnect"] = (connectionId) =>
+ withClient("disconnect an account", async (client) => {
+ await invalidateHostedSessions();
+ await client.connectedAccounts.delete(connectionId);
+ await invalidateHostedSessions();
+ }).pipe(Effect.flatMap(() => getStatus));
+
+ const resolveRuntimeMcpServer: ComposioServiceShape["resolveRuntimeMcpServer"] = (resourceId) =>
+ withClient("prepare connected tools", async (client, userId) => {
+ const configurationGeneration = runtimeConfigurationGeneration;
+ const pending = pendingRuntimeResolutions.get(resourceId);
+ if (pending?.generation === configurationGeneration) return pending.promise;
+ const resolving = (async () => {
+ const connections = (await listConnections(client, userId)).filter(
+ (connection) => connection.status === "ACTIVE",
+ );
+ if (connections.length === 0) {
+ await deleteCachedSession(resourceId);
+ return undefined;
+ }
+ const connectedAccounts = Object.groupBy(
+ connections,
+ (connection) => connection.toolkitSlug,
+ );
+ const accountMap = Object.fromEntries(
+ Object.entries(connectedAccounts).map(([toolkit, accounts]) => [
+ toolkit,
+ (accounts ?? []).map((account) => account.id),
+ ]),
+ );
+ const fingerprint = JSON.stringify(accountMap);
+ const cached = runtimeCache.get(resourceId);
+ if (cached?.fingerprint === fingerprint) return cached.server;
+ await deleteCachedSession(resourceId);
+ if (runtimeCache.size >= 100) {
+ const oldest = runtimeCache.keys().next().value;
+ if (oldest !== undefined) await deleteCachedSession(oldest);
+ }
+ const session = await client.sessions.create(userId, {
+ mcp: true,
+ toolkits: Object.keys(accountMap),
+ connectedAccounts: accountMap,
+ manageConnections: true,
+ multiAccount: {
+ enable: true,
+ maxAccountsPerToolkit: 10,
+ requireExplicitSelection: true,
+ },
+ });
+ const deleteSession = () => session.delete().then(() => undefined);
+ if (configurationGeneration !== runtimeConfigurationGeneration) {
+ pendingHostedSessionDeletes.add(deleteSession);
+ await deletePendingHostedSession(deleteSession);
+ return undefined;
+ }
+ const now = "1970-01-01T00:00:00.000Z";
+ const server = withMcpRuntimeHeaders(
+ {
+ id: COMPOSIO_MCP_SERVER_ID,
+ name: "Composio",
+ transport: "url",
+ url: session.mcp.url,
+ enabled: true,
+ createdAt: now,
+ updatedAt: now,
+ },
+ session.mcp.headers ?? {},
+ );
+ runtimeCache.set(resourceId, {
+ fingerprint,
+ server,
+ deleteSession,
+ });
+ return server;
+ })();
+ const pendingResolution = { generation: configurationGeneration, promise: resolving };
+ pendingRuntimeResolutions.set(resourceId, pendingResolution);
+ try {
+ return await resolving;
+ } finally {
+ if (pendingRuntimeResolutions.get(resourceId) === pendingResolution) {
+ pendingRuntimeResolutions.delete(resourceId);
+ }
+ }
+ }).pipe(
+ Effect.catch((error) =>
+ error.message === "Connect Composio in Settings first."
+ ? Effect.succeed<McpServer | undefined>(undefined)
+ : Effect.fail(error),
+ ),
+ );
+
+ return {
+ getStatus,
+ configure,
+ remove,
+ searchToolkits,
+ authorize,
+ disconnect,
+ resolveRuntimeMcpServer,
+ };
+}
+
+export const layer = Layer.effect(
+ ComposioService,
+ Effect.gen(function* () {
+ const secretStore = yield* ServerSecretStore;
+ return make(secretStore);
+ }),
+);
diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.test.ts b/apps/server/src/orchestration/ActivityPayloadProjection.test.ts
index c32843e93..62e2d20a9 100644
--- a/apps/server/src/orchestration/ActivityPayloadProjection.test.ts
+++ b/apps/server/src/orchestration/ActivityPayloadProjection.test.ts
@@ -268,4 +268,38 @@ describe("projectActivityPayload", () => {
const projected = projectActivityPayload(source);
expect(projected.payload).toEqual(source.payload);
});
+
+ it("keeps bounded plugin recommendations for the chat card", () => {
+ const projected = projectActivityPayload({
+ ...activity({
+ itemType: "dynamic_tool_call",
+ data: {
+ result: {
+ kind: "plugin-search-results",
+ query: "email",
+ total: 1,
+ sources: { directory: "available", composio: "available" },
+ recommendations: [
+ {
+ id: "composio:gmail",
+ source: "composio",
+ name: "Gmail",
+ description: "Read and send email.",
+ action: "connect",
+ logoUrl: "https://logos.composio.dev/api/gmail",
+ },
+ ],
+ },
+ },
+ }),
+ summary: "SearchPlugins",
+ });
+ const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
+
+ expect(data.result).toMatchObject({
+ kind: "plugin-search-results",
+ recommendations: [expect.objectContaining({ id: "composio:gmail" })],
+ });
+ expect(JSON.stringify(projected.payload).length).toBeLessThan(2_000);
+ });
});
diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.ts b/apps/server/src/orchestration/ActivityPayloadProjection.ts
index 19ea14362..590d24574 100644
--- a/apps/server/src/orchestration/ActivityPayloadProjection.ts
+++ b/apps/server/src/orchestration/ActivityPayloadProjection.ts
@@ -3,6 +3,10 @@ import type {
OrchestrationThreadActivity,
OrchestrationThreadDetailSnapshot,
} from "@t3tools/contracts";
+import { AkeruPluginSearchResult } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+
+const isPluginSearchResult = Schema.is(AkeruPluginSearchResult);
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value)
@@ -376,6 +380,14 @@ function projectAcpContent(value: unknown): Record<string, unknown> | undefined
return summary ? { content: summary } : undefined;
}
+function projectPluginSearchResult(value: unknown): AkeruPluginSearchResult | undefined {
+ if (!isPluginSearchResult(value)) return undefined;
+ return {
+ ...value,
+ recommendations: value.recommendations.slice(0, 6),
+ };
+}
+
/**
* Removes activity payload fields that no current client reads while retaining
* the full payload in persistence and the event store.
@@ -405,6 +417,22 @@ export function projectActivityPayload(
};
}
+ if (payload.itemType === "dynamic_tool_call" && activity.summary === "SearchPlugins") {
+ const result = projectPluginSearchResult(data.result);
+ if (result) {
+ return {
+ ...activity,
+ payload: {
+ ...projectedPayload,
+ data: {
+ result,
+ ...(data.toolCallId !== undefined ? { toolCallId: data.toolCallId } : {}),
+ },
+ },
+ };
+ }
+ }
+
const projectedData: Record<string, unknown> = {};
const item = projectCommandData(data);
if (item) {
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
index f71aa443e..ed475d27a 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
@@ -5,6 +5,8 @@ import * as NodePath from "node:path";
import {
ModelSelection,
+ ComposioOperationError,
+ type McpServer,
ProviderRuntimeEvent,
ProviderSession,
ProviderDriverKind,
@@ -71,6 +73,7 @@ import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import * as GitWorkflowService from "../../git/GitWorkflowService.ts";
import { BotUsageLedger, BotUsageLedgerLive } from "../../usage/BotUsageLedger.ts";
+import { ComposioService, type ComposioServiceShape } from "../../composio/ComposioService.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
@@ -170,6 +173,7 @@ describe("ProviderCommandReactor", () => {
readonly titleRegenerationCompletionDispatchFailures?: number;
readonly titleRegenerationBeforeStart?: "one" | "two";
readonly interruptTurnEffect?: () => Effect.Effect<void, ProviderAdapterRequestError>;
+ readonly interruptTurnRemovesSession?: boolean;
readonly stopSessionEffect?: () => Effect.Effect<void, ProviderAdapterRequestError>;
readonly startSessionEffect?: (
session: ProviderSession,
@@ -178,6 +182,7 @@ describe("ProviderCommandReactor", () => {
readonly botUsageCap?: { readonly unit: "tokens"; readonly limit: number } | null;
readonly bindTurnFailure?: boolean;
readonly unavailableEngine?: boolean;
+ readonly composioResolveRuntimeMcpServer?: ComposioServiceShape["resolveRuntimeMcpServer"];
}) {
const now = "2026-01-01T00:00:00.000Z";
const baseDir =
@@ -260,7 +265,30 @@ describe("ProviderCommandReactor", () => {
turnId: asTurnId("turn-1"),
}),
);
- const interruptTurn = vi.fn((_: unknown) => input?.interruptTurnEffect?.() ?? Effect.void);
+ const interruptTurn = vi.fn((interruptInput: unknown) =>
+ (input?.interruptTurnEffect?.() ?? Effect.void).pipe(
+ Effect.tap(() =>
+ Effect.sync(() => {
+ if (input?.interruptTurnRemovesSession !== true) {
+ return;
+ }
+ const threadId =
+ typeof interruptInput === "object" &&
+ interruptInput !== null &&
+ "threadId" in interruptInput
+ ? (interruptInput as { threadId?: ThreadId }).threadId
+ : undefined;
+ if (!threadId) {
+ return;
+ }
+ const index = runtimeSessions.findIndex((session) => session.threadId === threadId);
+ if (index >= 0) {
+ runtimeSessions.splice(index, 1);
+ }
+ }),
+ ),
+ ),
+ );
const respondToRequest = vi.fn<AgentControllerShape["respondToRequest"]>(() => Effect.void);
const respondToUserInput = vi.fn<AgentControllerShape["respondToUserInput"]>(() => Effect.void);
const stopSession = vi.fn((stopInput: unknown) =>
@@ -461,6 +489,13 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(ProjectionBotRepositoryLive.pipe(Layer.provide(SqlitePersistenceMemory))),
Layer.provideMerge(botUsageLedgerLayer),
Layer.provideMerge(Layer.succeed(AgentController, service)),
+ Layer.provideMerge(
+ Layer.mock(ComposioService, {
+ resolveRuntimeMcpServer:
+ input?.composioResolveRuntimeMcpServer ??
+ (() => Effect.succeed<McpServer | undefined>(undefined)),
+ }),
+ ),
Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)),
Layer.provideMerge(
Layer.mock(GitWorkflowService.GitWorkflowService)({
@@ -922,6 +957,51 @@ describe("ProviderCommandReactor", () => {
expect(harness.sendTurn).not.toHaveBeenCalled();
});
+ it("fails the turn before provider dispatch when Composio runtime preparation fails", async () => {
+ const harness = await createHarness({
+ composioResolveRuntimeMcpServer: () =>
+ Effect.fail(
+ new ComposioOperationError({
+ operation: "prepare connected tools",
+ message: "Composio could not prepare connected tools.",
+ }),
+ ),
+ });
+
+ await Effect.runPromise(
+ harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-turn-start-composio-failure"),
+ threadId: ThreadId.make("thread-1"),
+ message: {
+ messageId: asMessageId("user-message-composio-failure"),
+ role: "user",
+ text: "check my inbox",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ }),
+ );
+
+ await harness.drain();
+ const thread = (await harness.readModel()).threads.find(
+ (entry) => entry.id === ThreadId.make("thread-1"),
+ );
+ expect(thread?.activities).toContainEqual(
+ expect.objectContaining({
+ kind: "provider.turn.start.failed",
+ payload: {
+ detail: "Composio could not prepare connected tools.",
+ requestId: "user-message-composio-failure",
+ },
+ }),
+ );
+ expect(harness.startSession).not.toHaveBeenCalled();
+ expect(harness.sendTurn).not.toHaveBeenCalled();
+ });
+
effectIt.effect("projects starting before a slow provider session finishes", () =>
Effect.gen(function* () {
const releaseStart = yield* Deferred.make<void>();
@@ -2555,6 +2635,301 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
+ it("stops a full-access session when a restrictive runtime mode update fails", async () => {
+ let failComposioPreparation = false;
+ const harness = await createHarness({
+ composioResolveRuntimeMcpServer: () =>
+ failComposioPreparation
+ ? Effect.fail(
+ new ComposioOperationError({
+ operation: "prepare connected tools",
+ message: "Composio could not prepare connected tools.",
+ }),
+ )
+ : Effect.succeed<McpServer | undefined>(undefined),
+ });
+ const now = "2026-01-01T00:00:00.000Z";
+
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("cmd-runtime-mode-set-full-access-before-composio-failure"),
+ threadId: ThreadId.make("thread-1"),
+ runtimeMode: "full-access",
+ createdAt: now,
+ }),
+ );
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-turn-start-before-composio-mode-failure"),
+ threadId: ThreadId.make("thread-1"),
+ message: {
+ messageId: asMessageId("user-message-before-composio-mode-failure"),
+ role: "user",
+ text: "start with full access",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "full-access",
+ createdAt: now,
+ }),
+ );
+ await waitFor(() => harness.sendTurn.mock.calls.length === 1);
+
+ failComposioPreparation = true;
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("cmd-runtime-mode-set-restricted-after-composio-failure"),
+ threadId: ThreadId.make("thread-1"),
+ runtimeMode: "approval-required",
+ createdAt: now,
+ }),
+ );
+ await harness.drain();
+
+ expect(harness.interruptTurn).toHaveBeenCalledWith({ threadId: ThreadId.make("thread-1") });
+ expect(harness.stopSession).toHaveBeenCalledWith({ threadId: ThreadId.make("thread-1") });
+ expect(harness.runtimeSessions).toHaveLength(0);
+ const thread = (await harness.readModel()).threads.find(
+ (entry) => entry.id === ThreadId.make("thread-1"),
+ );
+ expect(thread?.runtimeMode).toBe("approval-required");
+ expect(thread?.session).toMatchObject({
+ status: "error",
+ activeTurnId: null,
+ lastError: "Composio could not prepare connected tools.",
+ });
+ expect(thread?.activities).toContainEqual(
+ expect.objectContaining({
+ kind: "provider.session.update.failed",
+ payload: {
+ detail: "Composio could not prepare connected tools.",
+ },
+ }),
+ );
+ });
+
+ it("quarantines a full-access session until restrictive cleanup is confirmed", async () => {
+ let failComposioPreparation = false;
+ let failSessionStop = true;
+ const providerFailure = (method: string, detail: string) =>
+ new ProviderAdapterRequestError({
+ provider: "codex",
+ method,
+ detail,
+ });
+ const harness = await createHarness({
+ composioResolveRuntimeMcpServer: () =>
+ failComposioPreparation
+ ? Effect.fail(
+ new ComposioOperationError({
+ operation: "prepare connected tools",
+ message: "Composio could not prepare connected tools.",
+ }),
+ )
+ : Effect.succeed<McpServer | undefined>(undefined),
+ interruptTurnEffect: () =>
+ Effect.fail(providerFailure("thread.turn.interrupt", "Interrupt failed.")),
+ stopSessionEffect: () =>
+ failSessionStop
+ ? Effect.fail(providerFailure("thread.session.stop", "Stop failed."))
+ : Effect.void,
+ });
+ const now = "2026-01-01T00:00:00.000Z";
+
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("cmd-quarantine-full-access"),
+ threadId: ThreadId.make("thread-1"),
+ runtimeMode: "full-access",
+ createdAt: now,
+ }),
+ );
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-quarantine-start"),
+ threadId: ThreadId.make("thread-1"),
+ message: {
+ messageId: asMessageId("user-message-quarantine-start"),
+ role: "user",
+ text: "start with full access",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "full-access",
+ createdAt: now,
+ }),
+ );
+ await waitFor(() => harness.sendTurn.mock.calls.length === 1);
+
+ failComposioPreparation = true;
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("cmd-quarantine-restrict"),
+ threadId: ThreadId.make("thread-1"),
+ runtimeMode: "approval-required",
+ createdAt: now,
+ }),
+ );
+ await harness.drain();
+
+ expect(harness.runtimeSessions).toHaveLength(1);
+ expect(harness.stopSession).toHaveBeenCalledTimes(1);
+
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-quarantine-blocked-turn"),
+ threadId: ThreadId.make("thread-1"),
+ message: {
+ messageId: asMessageId("user-message-quarantine-blocked-turn"),
+ role: "user",
+ text: "do not send this while cleanup is pending",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ createdAt: now,
+ }),
+ );
+ await harness.drain();
+
+ expect(harness.stopSession).toHaveBeenCalledTimes(2);
+ expect(harness.sendTurn).toHaveBeenCalledTimes(1);
+ expect(harness.startSession).toHaveBeenCalledTimes(1);
+
+ failSessionStop = false;
+ failComposioPreparation = false;
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.session.stop",
+ commandId: CommandId.make("cmd-quarantine-stop"),
+ threadId: ThreadId.make("thread-1"),
+ createdAt: now,
+ }),
+ );
+ await harness.drain();
+
+ expect(harness.runtimeSessions).toHaveLength(0);
+ expect(harness.stopSession).toHaveBeenCalledTimes(3);
+ expect(
+ (await harness.readModel()).threads.find((thread) => thread.id === ThreadId.make("thread-1"))
+ ?.session?.status,
+ ).toBe("stopped");
+
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-quarantine-reconciled-turn"),
+ threadId: ThreadId.make("thread-1"),
+ message: {
+ messageId: asMessageId("user-message-quarantine-reconciled-turn"),
+ role: "user",
+ text: "continue after cleanup",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ createdAt: now,
+ }),
+ );
+ await harness.drain();
+ await waitFor(() => harness.sendTurn.mock.calls.length === 2);
+
+ expect(harness.runtimeSessions).toHaveLength(1);
+ expect(harness.runtimeSessions[0]?.runtimeMode).toBe("approval-required");
+ expect(harness.stopSession).toHaveBeenCalledTimes(3);
+ expect(harness.startSession).toHaveBeenCalledTimes(2);
+ });
+
+ it("accepts an interrupt that already removed the unrestricted session", async () => {
+ let failComposioPreparation = false;
+ const harness = await createHarness({
+ composioResolveRuntimeMcpServer: () =>
+ failComposioPreparation
+ ? Effect.fail(
+ new ComposioOperationError({
+ operation: "prepare connected tools",
+ message: "Composio could not prepare connected tools.",
+ }),
+ )
+ : Effect.succeed<McpServer | undefined>(undefined),
+ interruptTurnRemovesSession: true,
+ });
+ const now = "2026-01-01T00:00:00.000Z";
+
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("cmd-interrupt-removes-full-access"),
+ threadId: ThreadId.make("thread-1"),
+ runtimeMode: "full-access",
+ createdAt: now,
+ }),
+ );
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-interrupt-removes-start"),
+ threadId: ThreadId.make("thread-1"),
+ message: {
+ messageId: asMessageId("user-message-interrupt-removes-start"),
+ role: "user",
+ text: "start with full access",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "full-access",
+ createdAt: now,
+ }),
+ );
+ await waitFor(() => harness.sendTurn.mock.calls.length === 1);
+
+ failComposioPreparation = true;
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("cmd-interrupt-removes-restrict"),
+ threadId: ThreadId.make("thread-1"),
+ runtimeMode: "approval-required",
+ createdAt: now,
+ }),
+ );
+ await harness.drain();
+
+ expect(harness.runtimeSessions).toHaveLength(0);
+ expect(harness.interruptTurn).toHaveBeenCalledTimes(1);
+ expect(harness.stopSession).not.toHaveBeenCalled();
+
+ failComposioPreparation = false;
+ await harness.runEffect(
+ harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-interrupt-removes-restricted-turn"),
+ threadId: ThreadId.make("thread-1"),
+ message: {
+ messageId: asMessageId("user-message-interrupt-removes-restricted-turn"),
+ role: "user",
+ text: "continue with approval required",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ createdAt: now,
+ }),
+ );
+ await harness.drain();
+ await waitFor(() => harness.sendTurn.mock.calls.length === 2);
+
+ expect(harness.runtimeSessions).toHaveLength(1);
+ expect(harness.runtimeSessions[0]?.runtimeMode).toBe("approval-required");
+ });
+
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
const harness = await createHarness({
threadModelSelection: {
@@ -2603,7 +2978,7 @@ describe("ProviderCommandReactor", () => {
});
});
- it("does not stop the active session when restart fails before rebind", async () => {
+ it("stops the active session when a restrictive restart fails before rebind", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2659,13 +3034,18 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 2);
await harness.drain();
- expect(harness.stopSession.mock.calls.length).toBe(0);
+ expect(harness.stopSession).toHaveBeenCalledWith({ threadId: ThreadId.make("thread-1") });
expect(harness.sendTurn.mock.calls.length).toBe(1);
+ expect(harness.runtimeSessions).toHaveLength(0);
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("full-access");
+ expect(thread?.session?.status).toBe("error");
+ expect(thread?.activities).toContainEqual(
+ expect.objectContaining({ kind: "provider.session.update.failed" }),
+ );
});
it("restarts the session when a turn changes provider", async () => {
@@ -3406,7 +3786,7 @@ describe("ProviderCommandReactor", () => {
),
);
- await Effect.runPromise(
+ await harness.runEffect(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-for-approval-error"),
@@ -3424,7 +3804,7 @@ describe("ProviderCommandReactor", () => {
}),
);
- await Effect.runPromise(
+ await harness.runEffect(
harness.engine.dispatch({
type: "thread.activity.append",
commandId: CommandId.make("cmd-approval-requested"),
@@ -3445,7 +3825,7 @@ describe("ProviderCommandReactor", () => {
}),
);
- await Effect.runPromise(
+ await harness.runEffect(
harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.make("cmd-approval-respond-stale"),
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
index 2563ffc94..a4927c30d 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
@@ -3,6 +3,7 @@ import {
AkeruMemoryUserId,
AkeruUsageReservationId,
type ChatAttachment,
+ ComposioOperationError,
CommandId,
EventId,
MessageId,
@@ -28,6 +29,7 @@ import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
+import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -71,9 +73,11 @@ import {
} from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
+import { ComposioService } from "../../composio/ComposioService.ts";
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
const isAgentControllerUnsupportedEngineError = Schema.is(AgentControllerUnsupportedEngineError);
const isBotUsageCapExceeded = Schema.is(BotUsageCapExceeded);
+const isComposioOperationError = Schema.is(ComposioOperationError);
const isProviderDriverKind = Schema.is(ProviderDriverKind);
export function resolveControllerBotId(
@@ -346,11 +350,29 @@ const make = Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const botUsageLedger = yield* BotUsageLedger;
+ const composio = yield* Effect.serviceOption(ComposioService);
const runPromise = Effect.runPromiseWith(yield* Effect.context<never>());
if (agentController.configurePluginRuntime) {
yield* agentController.configurePluginRuntime({
readSnapshot: () => runPromise(projectionSnapshotQuery.getCommandReadModel()),
dispatch: (command) => runPromise(orchestrationEngine.dispatch(command)),
+ ...(Option.isSome(composio)
+ ? {
+ searchComposioToolkits: async (input: {
+ readonly query?: string;
+ readonly limit?: number;
+ }) => {
+ const status = await runPromise(composio.value.getStatus);
+ if (!status.configured) {
+ return { status: "setup-required" as const, toolkits: [] };
+ }
+ return {
+ status: "available" as const,
+ toolkits: await runPromise(composio.value.searchToolkits(input)),
+ };
+ },
+ }
+ : {}),
});
}
const failDelegation = (threadId: ThreadId, error: string) =>
@@ -386,6 +408,7 @@ const make = Effect.gen(function* () {
const threadModelSelections = new Map<string, ModelSelection>();
const threadBotWorkspaceKeys = new Map<string, string>();
const threadMcpServers = new Map<string, readonly McpServer[]>();
+ const threadsAwaitingRestrictiveSessionCleanup = new Set<string>();
const appendProviderFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -394,6 +417,7 @@ const make = Effect.gen(function* () {
| "provider.turn.interrupt.failed"
| "provider.approval.respond.failed"
| "provider.user-input.respond.failed"
+ | "provider.session.update.failed"
| "provider.session.stop.failed";
readonly summary: string;
readonly detail: string;
@@ -501,6 +525,10 @@ const make = Effect.gen(function* () {
const failReason = cause.reasons.find(Cause.isFailReason);
const capError = isBotUsageCapExceeded(failReason?.error) ? failReason.error : undefined;
if (capError) return capError.message;
+ const composioError = isComposioOperationError(failReason?.error)
+ ? failReason.error
+ : undefined;
+ if (composioError) return composioError.message;
const providerError = isProviderAdapterRequestError(failReason?.error)
? failReason.error
: undefined;
@@ -616,6 +644,64 @@ const make = Effect.gen(function* () {
.pipe(Effect.map(Option.getOrUndefined));
});
+ const reconcileRestrictiveSessionCleanup = Effect.fn("reconcileRestrictiveSessionCleanup")(
+ function* (threadId: ThreadId) {
+ const thread = yield* resolveThread(threadId);
+ const persistedCleanupRequired =
+ thread?.runtimeMode === "approval-required" &&
+ thread.session?.runtimeMode === "full-access" &&
+ thread.session.status === "error";
+ if (!threadsAwaitingRestrictiveSessionCleanup.has(threadId) && !persistedCleanupRequired) {
+ return false;
+ }
+
+ threadsAwaitingRestrictiveSessionCleanup.add(threadId);
+ const activeSession = (yield* agentController.listSessions()).find(
+ (session) => session.threadId === threadId,
+ );
+ if (activeSession === undefined) {
+ threadsAwaitingRestrictiveSessionCleanup.delete(threadId);
+ return true;
+ }
+
+ yield* agentController.interruptTurn({ threadId }).pipe(
+ Effect.catchCause((cause) => {
+ if (Cause.hasInterruptsOnly(cause)) {
+ return Effect.interrupt;
+ }
+ return Effect.logWarning(
+ "provider command reactor failed to interrupt quarantined session",
+ {
+ threadId,
+ cause: Cause.pretty(cause),
+ },
+ );
+ }),
+ );
+ const sessionAfterInterrupt = (yield* agentController.listSessions()).find(
+ (session) => session.threadId === threadId,
+ );
+ if (sessionAfterInterrupt === undefined) {
+ threadsAwaitingRestrictiveSessionCleanup.delete(threadId);
+ return true;
+ }
+ yield* agentController.stopSession({ threadId });
+
+ const remainingSession = (yield* agentController.listSessions()).find(
+ (session) => session.threadId === threadId,
+ );
+ if (remainingSession !== undefined) {
+ return yield* new ProviderAdapterRequestError({
+ provider: providerErrorLabel(remainingSession.provider),
+ method: "thread.session.stop",
+ detail: `Provider session '${threadId}' is still active after a restrictive runtime mode update failed.`,
+ });
+ }
+ threadsAwaitingRestrictiveSessionCleanup.delete(threadId);
+ return true;
+ },
+ );
+
const inspectAvailableEngine = (modelSelection: ModelSelection) =>
agentController.inspectEngine(modelSelection);
@@ -650,7 +736,11 @@ const make = Effect.gen(function* () {
.getById({ botId: respondingBotId })
.pipe(Effect.map(Option.getOrUndefined));
const servers = yield* projectionMcpServerRepository.listAll();
- return resolveBotMcpServers(servers, bot?.disabledMcpServerIds ?? []);
+ const resolved = resolveBotMcpServers(servers, bot?.disabledMcpServerIds ?? []);
+ const composioServer = Option.isSome(composio)
+ ? yield* composio.value.resolveRuntimeMcpServer(thread.id)
+ : undefined;
+ return composioServer ? [...resolved, composioServer] : resolved;
});
const rejectStartedThreadModelChangeIfRequired = Effect.fnUntraced(function* (input: {
@@ -1755,6 +1845,7 @@ const make = Effect.gen(function* () {
const processSessionStopRequested = Effect.fn("processSessionStopRequested")(function* (
event: Extract<ProviderIntentEvent, { type: "thread.session-stop-requested" }>,
+ restrictiveSessionCleanupConfirmed: boolean,
) {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread) {
@@ -1762,7 +1853,11 @@ const make = Effect.gen(function* () {
}
const now = event.payload.createdAt;
- if (thread.session && thread.session.status !== "stopped") {
+ if (
+ thread.session &&
+ thread.session.status !== "stopped" &&
+ !restrictiveSessionCleanupConfirmed
+ ) {
yield* agentController.stopSession({ threadId: thread.id });
}
@@ -1787,6 +1882,7 @@ const make = Effect.gen(function* () {
const processDomainEvent = Effect.fn("processDomainEvent")(function* (
event: ProviderIntentEvent,
+ restrictiveSessionCleanupConfirmed: boolean,
) {
yield* Effect.annotateCurrentSpan({
"orchestration.event_type": event.type,
@@ -1817,11 +1913,51 @@ const make = Effect.gen(function* () {
if (!thread?.session || thread.session.status === "stopped") {
return;
}
+ const session = thread.session;
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
+ ).pipe(
+ Effect.catchCause((cause) => {
+ if (Cause.hasInterruptsOnly(cause)) {
+ return Effect.interrupt;
+ }
+ const detail = formatFailureDetail(cause);
+ const restrictsActiveSession =
+ session.runtimeMode === "full-access" && thread.runtimeMode === "approval-required";
+ if (restrictsActiveSession) {
+ threadsAwaitingRestrictiveSessionCleanup.add(thread.id);
+ }
+ const reportFailure = setThreadSessionErrorOnTurnStartFailure({
+ threadId: thread.id,
+ detail,
+ createdAt: event.occurredAt,
+ }).pipe(
+ Effect.andThen(
+ appendProviderFailureActivity({
+ threadId: thread.id,
+ kind: "provider.session.update.failed",
+ summary: "Provider session update failed",
+ detail,
+ turnId: session.activeTurnId,
+ createdAt: event.occurredAt,
+ }),
+ ),
+ );
+ return Effect.exit(
+ restrictsActiveSession ? reconcileRestrictiveSessionCleanup(thread.id) : Effect.void,
+ ).pipe(
+ Effect.flatMap((cleanupExit) =>
+ reportFailure.pipe(
+ Effect.andThen(
+ Exit.isFailure(cleanupExit) ? Effect.failCause(cleanupExit.cause) : Effect.void,
+ ),
+ ),
+ ),
+ );
+ }),
);
return;
}
@@ -1838,13 +1974,19 @@ const make = Effect.gen(function* () {
yield* processUserInputResponseRequested(event);
return;
case "thread.session-stop-requested":
- yield* processSessionStopRequested(event);
+ yield* processSessionStopRequested(event, restrictiveSessionCleanupConfirmed);
return;
}
});
const processDomainEventSafely = (event: ProviderIntentEvent) =>
- processDomainEvent(event).pipe(
+ (event.type === "delegation.updated"
+ ? event.payload.delegation.childThreadId === null
+ ? Effect.succeed(false)
+ : reconcileRestrictiveSessionCleanup(event.payload.delegation.childThreadId)
+ : reconcileRestrictiveSessionCleanup(event.payload.threadId)
+ ).pipe(
+ Effect.flatMap((cleanupConfirmed) => processDomainEvent(event, cleanupConfirmed)),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.interrupt;
diff --git a/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts b/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts
index eb3a53623..0597c8ec7 100644
--- a/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts
+++ b/apps/server/src/provider/AkeruCatalogToolHandlers.test.ts
@@ -186,6 +186,42 @@ describe("Akeru catalog MCP tool handlers", () => {
await expect(runtime.getPlugin("missing")).rejects.toThrow("was not found");
});
+ it("merges Composio toolkits into plugin search recommendations", async () => {
+ const runtime = createAkeruPluginRuntime({
+ readSnapshot: async () => snapshot(),
+ dispatch: async () => undefined,
+ searchComposioToolkits: async () => ({
+ status: "available" as const,
+ toolkits: [
+ {
+ slug: "gmail",
+ name: "Gmail",
+ description: "Read and send email.",
+ logoUrl: "https://logos.composio.dev/api/gmail",
+ categories: ["Productivity"],
+ toolsCount: 61,
+ },
+ ],
+ }),
+ } as never);
+
+ const result = await runtime.search({ query: "email", limit: 5 });
+
+ expect(result.kind).toBe("plugin-search-results");
+ expect(result.sources.composio).toBe("available");
+ expect(result.recommendations).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: "composio:gmail",
+ source: "composio",
+ name: "Gmail",
+ action: "connect",
+ logoUrl: "https://logos.composio.dev/api/gmail",
+ }),
+ ]),
+ );
+ });
+
it("installs catalog-owned recipes and enables an existing disabled plugin", async () => {
const dispatch = vi.fn<(command: OrchestrationCommand) => Promise<void>>(async () => undefined);
const runtime = createAkeruPluginRuntime({
diff --git a/apps/server/src/provider/AkeruCatalogToolHandlers.ts b/apps/server/src/provider/AkeruCatalogToolHandlers.ts
index a0f09dc64..60d6e19ad 100644
--- a/apps/server/src/provider/AkeruCatalogToolHandlers.ts
+++ b/apps/server/src/provider/AkeruCatalogToolHandlers.ts
@@ -4,8 +4,11 @@ import * as NodeFS from "node:fs";
import type { McpManager, McpServerStatus } from "@mastra/code-sdk/mcp/index";
import {
+ type AkeruPluginRecommendation,
+ type AkeruPluginSearchResult,
type BotId,
CommandId,
+ type ComposioToolkit,
McpServerId,
type AkeruToolId,
type AkeruToolInputSchemas,
@@ -91,6 +94,13 @@ type McpRuntimeStatus = ReturnType<McpManager["getServerStatuses"]>[number];
export interface AkeruPluginRuntimeOptions {
readonly readSnapshot: () => Promise<OrchestrationReadModel>;
readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;
+ readonly searchComposioToolkits?: (input: {
+ readonly query?: string;
+ readonly limit?: number;
+ }) => Promise<{
+ readonly status: "available" | "setup-required" | "unavailable";
+ readonly toolkits: readonly ComposioToolkit[];
+ }>;
readonly now?: () => string;
readonly id?: () => string;
}
@@ -167,6 +177,45 @@ function pluginMatches(plugin: PluginManifest, query: string): boolean {
.includes(query.trim().toLocaleLowerCase());
}
+function recommendationForPlugin(
+ plugin: PluginManifest,
+ snapshot: OrchestrationReadModel,
+): AkeruPluginRecommendation {
+ const server = snapshot.mcpServers?.find(
+ (candidate) => candidate.id === pluginServerId(plugin.id),
+ );
+ const composio =
+ plugin.connection.type === "brokered" && plugin.connection.broker.name === "Composio";
+ const action = server?.enabled
+ ? "open"
+ : composio
+ ? "connect"
+ : isInstallableManifest(plugin)
+ ? "install"
+ : "unavailable";
+ return {
+ id: composio ? `composio:${plugin.id}` : plugin.id,
+ source: composio ? "composio" : "directory",
+ name: plugin.name,
+ description: plugin.description,
+ category: plugin.primaryCategory,
+ ...(plugin.logo.url ? { logoUrl: plugin.logo.url } : {}),
+ action,
+ };
+}
+
+function recommendationForToolkit(toolkit: ComposioToolkit): AkeruPluginRecommendation {
+ return {
+ id: `composio:${toolkit.slug}`,
+ source: "composio",
+ name: toolkit.name,
+ description: toolkit.description ?? `${toolkit.toolsCount} tools through Composio.`,
+ ...(toolkit.categories[0] ? { category: toolkit.categories[0] } : {}),
+ ...(toolkit.logoUrl ? { logoUrl: toolkit.logoUrl } : {}),
+ action: "connect",
+ };
+}
+
function sameRecipe(server: McpServer, plugin: PluginManifest): boolean {
if (plugin.transport.type === "url") {
return (
@@ -207,11 +256,37 @@ export function createAkeruPluginRuntime(options: AkeruPluginRuntimeOptions) {
const matches = catalog.filter((plugin) => pluginMatches(plugin, query));
const limit = input.limit ?? 20;
const snapshot = await options.readSnapshot();
+ let composioSearch: {
+ readonly status: "available" | "setup-required" | "unavailable";
+ readonly toolkits: readonly ComposioToolkit[];
+ } = { status: "unavailable", toolkits: [] };
+ if (options.searchComposioToolkits) {
+ try {
+ composioSearch = await options.searchComposioToolkits({
+ ...(query ? { query } : {}),
+ limit,
+ });
+ } catch {
+ composioSearch = { status: "unavailable", toolkits: [] };
+ }
+ }
+ const recommendations = [
+ ...matches.map((plugin) => recommendationForPlugin(plugin, snapshot)),
+ ...composioSearch.toolkits.map(recommendationForToolkit),
+ ];
+ const uniqueRecommendations = [
+ ...new Map(
+ recommendations.map((recommendation) => [recommendation.id, recommendation]),
+ ).values(),
+ ].slice(0, limit);
return {
+ kind: "plugin-search-results",
query,
- total: matches.length,
+ total: uniqueRecommendations.length,
+ sources: { directory: "available", composio: composioSearch.status },
+ recommendations: uniqueRecommendations,
plugins: matches.slice(0, limit).map((plugin) => pluginView(plugin, snapshot, statuses)),
- };
+ } satisfies AkeruPluginSearchResult & { readonly plugins: readonly unknown[] };
};
const install = async (pluginId: string) => {
diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.ts
index 1a0c8c92e..dcc143344 100644
--- a/apps/server/src/provider/Layers/AgentController.test.ts
+++ b/apps/server/src/provider/Layers/AgentController.test.ts
@@ -64,6 +64,7 @@ import {
BotUsageLedger,
type BotUsageLedgerShape,
} from "../../usage/BotUsageLedger.ts";
+import { withMcpRuntimeHeaders } from "../McpServerConfig.ts";
const codexThreadId = ThreadId.make("thread-mastra-codex");
const claudeThreadId = ThreadId.make("thread-legacy-claude");
@@ -466,6 +467,29 @@ describe("toMcpServerConfigs", () => {
"local-tools": { command: "bunx", args: ["local-tools"] },
});
});
+
+ it("forwards transient MCP headers without adding them to the server record", () => {
+ const server = withMcpRuntimeHeaders(
+ {
+ id: McpServerId.make("composio-session"),
+ name: "Composio",
+ transport: "url" as const,
+ url: "https://app.composio.dev/tool_router/v3/session/mcp",
+ enabled: true,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ },
+ { "x-api-key": "project-key" },
+ );
+
+ expect(toMcpServerConfigs([server])).toEqual({
+ "composio-session": {
+ url: "https://app.composio.dev/tool_router/v3/session/mcp",
+ headers: { "x-api-key": "project-key" },
+ },
+ });
+ expect(server).not.toHaveProperty("headers");
+ });
});
describe("provider access health", () => {
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index fa4226053..e76d767dd 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -103,6 +103,7 @@ import {
createAkeruPluginRuntime,
type AkeruPluginRuntimeOptions,
} from "../AkeruCatalogToolHandlers.ts";
+import { getMcpRuntimeHeaders, sameMcpServerConfigurations } from "../McpServerConfig.ts";
import {
createAkeruToolRuntime,
isMemoryToolId,
@@ -198,6 +199,7 @@ interface ActiveSession {
readonly cwd: string | undefined;
readonly createdAt: string;
readonly mcpServerIds: readonly McpServer["id"][];
+ readonly mcpServers: readonly McpServer[];
runtimeMode: RuntimeMode;
model: string;
status: ProviderSession["status"];
@@ -335,6 +337,9 @@ export function toMcpServerConfigs(
server.transport === "url"
? {
url: server.url,
+ ...(Object.keys(getMcpRuntimeHeaders(server)).length > 0
+ ? { headers: getMcpRuntimeHeaders(server) }
+ : {}),
...(browser?.availableToHostedPlugins &&
BROWSER_AWARE_MCP_SERVER_IDS.has(String(server.id))
? {
@@ -1723,13 +1728,10 @@ const make = (options?: AgentControllerLiveOptions) =>
existing?.workspaceResourceKey === workspaceResourceKey &&
existing.cwd === input.cwd &&
existing.toolSession.workspaceType === workspaceType &&
- existing.mcpServerIds.length === mcpServers.length &&
- existing.mcpServerIds.every((id) => mcpServers.some((server) => server.id === id)) &&
+ sameMcpServerConfigurations(existing.mcpServers, mcpServers) &&
resolved &&
existing.provider === resolved.provider &&
- existing.providerInstanceId === resolved.providerInstanceId &&
- existing.mcpServerIds.length === (input.mcpServers?.length ?? 0) &&
- existing.mcpServerIds.every((id) => input.mcpServers?.some((server) => server.id === id))
+ existing.providerInstanceId === resolved.providerInstanceId
) {
existing.runtimeMode = access.runtimeMode;
yield* runMastra("state.set", () =>
@@ -2038,6 +2040,7 @@ const make = (options?: AgentControllerLiveOptions) =>
cwd: input.cwd,
createdAt: nowIso(),
mcpServerIds: mcpServers.map((server) => server.id),
+ mcpServers,
runtimeMode: access.runtimeMode,
model: resolved.modelSelection.model,
status: "ready" as const,
diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts
index 9bd64569e..7ed203eb2 100644
--- a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts
+++ b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts
@@ -16,6 +16,7 @@ import * as TestClock from "effect/testing/TestClock";
import { beforeEach } from "vite-plus/test";
import {
+ McpServerId,
OpenCodeSettings,
ProviderDriverKind,
ProviderInstanceId,
@@ -26,6 +27,7 @@ import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
+import { withMcpRuntimeHeaders } from "../McpServerConfig.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
@@ -74,6 +76,7 @@ const runtimeMock = {
sessionDirectoryById: new Map<string, string>(),
sessionUpdateCalls: [] as Array<{ sessionID: string; permission: unknown }>,
forkCalls: [] as Array<{ sessionID: string; directory?: string }>,
+ mcpAddCalls: [] as Array<{ name: string; config: unknown }>,
},
reset() {
this.state.startCalls.length = 0;
@@ -94,6 +97,7 @@ const runtimeMock = {
this.state.sessionDirectoryById.clear();
this.state.sessionUpdateCalls.length = 0;
this.state.forkCalls.length = 0;
+ this.state.mcpAddCalls.length = 0;
},
};
@@ -212,6 +216,12 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
})(),
}),
},
+ mcp: {
+ add: async (input: { name: string; config: unknown }) => {
+ runtimeMock.state.mcpAddCalls.push(input);
+ return { data: true };
+ },
+ },
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
loadOpenCodeInventory: () =>
Effect.fail(
@@ -324,6 +334,46 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
+ it.effect("forwards transient headers to remote MCP servers", () =>
+ Effect.gen(function* () {
+ const adapter = yield* OpenCodeAdapter;
+ const mcpServer = withMcpRuntimeHeaders(
+ {
+ id: McpServerId.make("composio-session"),
+ name: "Composio",
+ transport: "url" as const,
+ url: "https://app.composio.dev/tool_router/v3/session/mcp",
+ enabled: true,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ },
+ { "x-api-key": "project-key" },
+ );
+
+ const threadId = asThreadId("thread-opencode-composio");
+ yield* adapter.startSession({
+ provider: ProviderDriverKind.make("opencode"),
+ threadId,
+ runtimeMode: "full-access",
+ mcpServers: [mcpServer],
+ });
+
+ NodeAssert.deepEqual(runtimeMock.state.mcpAddCalls, [
+ {
+ name: "composio-session",
+ config: {
+ type: "remote",
+ url: "https://app.composio.dev/tool_router/v3/session/mcp",
+ headers: { "x-api-key": "project-key" },
+ oauth: false,
+ },
+ },
+ ]);
+ NodeAssert.equal("headers" in mcpServer, false);
+ yield* adapter.stopSession(threadId);
+ }),
+ );
+
it.effect("resumes the persisted OpenCode session instead of creating a new one", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts
index a428a3635..ee3b3f280 100644
--- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts
+++ b/apps/server/src/provider/Layers/OpenCodeAdapter.ts
@@ -37,6 +37,7 @@ import {
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
} from "../Errors.ts";
+import { getMcpRuntimeHeaders } from "../McpServerConfig.ts";
import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import {
buildOpenCodePermissionRules,
@@ -1241,6 +1242,9 @@ export function makeOpenCodeAdapter(
? {
type: "remote",
url: mcpServer.url,
+ ...(Object.keys(getMcpRuntimeHeaders(mcpServer)).length > 0
+ ? { headers: getMcpRuntimeHeaders(mcpServer) }
+ : {}),
oauth: false,
}
: {
diff --git a/apps/server/src/provider/McpServerConfig.test.ts b/apps/server/src/provider/McpServerConfig.test.ts
index 24b1d55e5..9d4233c98 100644
--- a/apps/server/src/provider/McpServerConfig.test.ts
+++ b/apps/server/src/provider/McpServerConfig.test.ts
@@ -1,7 +1,12 @@
import { McpServerId, type McpServer } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
-import { toAcpMcpServers, toClaudeMcpServers } from "./McpServerConfig.ts";
+import {
+ sameMcpServerConfigurations,
+ toAcpMcpServers,
+ toClaudeMcpServers,
+ withMcpRuntimeHeaders,
+} from "./McpServerConfig.ts";
const servers: readonly McpServer[] = [
{
@@ -39,4 +44,39 @@ describe("provider MCP configuration", () => {
local: { type: "stdio", command: "bunx", args: ["local-mcp"] },
});
});
+
+ it("forwards transient headers without adding them to the server record", () => {
+ const server = withMcpRuntimeHeaders({ ...servers[0]! }, { "x-api-key": "secret" });
+
+ expect(toAcpMcpServers([server])).toEqual([
+ {
+ type: "http",
+ name: "Search",
+ url: "https://mcp.example.com",
+ headers: [{ name: "x-api-key", value: "secret" }],
+ },
+ ]);
+ expect(toClaudeMcpServers([server])).toEqual({
+ search: {
+ type: "http",
+ url: "https://mcp.example.com",
+ headers: { "x-api-key": "secret" },
+ },
+ });
+ expect(JSON.stringify(server)).not.toContain("secret");
+ });
+
+ it("detects a changed transient URL or header for the same server id", () => {
+ const original = withMcpRuntimeHeaders({ ...servers[0]! }, { "x-api-key": "first" });
+ const changedUrl = withMcpRuntimeHeaders(
+ { ...servers[0]!, url: "https://mcp.example.com/new-session" },
+ { "x-api-key": "first" },
+ );
+ const changedHeader = withMcpRuntimeHeaders({ ...servers[0]! }, { "x-api-key": "second" });
+
+ expect(sameMcpServerConfigurations([original], [original])).toBe(true);
+ expect(sameMcpServerConfigurations([original], [{ ...original }])).toBe(false);
+ expect(sameMcpServerConfigurations([original], [changedUrl])).toBe(false);
+ expect(sameMcpServerConfigurations([original], [changedHeader])).toBe(false);
+ });
});
diff --git a/apps/server/src/provider/McpServerConfig.ts b/apps/server/src/provider/McpServerConfig.ts
index b96130bcb..a9743b3c4 100644
--- a/apps/server/src/provider/McpServerConfig.ts
+++ b/apps/server/src/provider/McpServerConfig.ts
@@ -1,6 +1,61 @@
import type { McpServer } from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
+const runtimeHeaders = new WeakMap<McpServer, Readonly<Record<string, string>>>();
+
+export function withMcpRuntimeHeaders<T extends McpServer>(
+ server: T,
+ headers: Readonly<Record<string, string>>,
+): T {
+ runtimeHeaders.set(server, headers);
+ return server;
+}
+
+export function getMcpRuntimeHeaders(server: McpServer): Readonly<Record<string, string>> {
+ return runtimeHeaders.get(server) ?? {};
+}
+
+function sameHeaders(left: McpServer, right: McpServer): boolean {
+ const leftHeaders = getMcpRuntimeHeaders(left);
+ const rightHeaders = getMcpRuntimeHeaders(right);
+ const names = Object.keys(leftHeaders);
+ return (
+ names.length === Object.keys(rightHeaders).length &&
+ names.every((name) => leftHeaders[name] === rightHeaders[name])
+ );
+}
+
+function sameServer(left: McpServer, right: McpServer): boolean {
+ if (
+ left.id !== right.id ||
+ left.name !== right.name ||
+ left.transport !== right.transport ||
+ !sameHeaders(left, right)
+ ) {
+ return false;
+ }
+ if (left.transport === "url" && right.transport === "url") return left.url === right.url;
+ if (left.transport !== "stdio" || right.transport !== "stdio") return false;
+ const leftArgs = left.args ?? [];
+ const rightArgs = right.args ?? [];
+ return (
+ left.command === right.command &&
+ leftArgs.length === rightArgs.length &&
+ leftArgs.every((argument, index) => argument === rightArgs[index])
+ );
+}
+
+export function sameMcpServerConfigurations(
+ left: readonly McpServer[],
+ right: readonly McpServer[],
+): boolean {
+ if (left.length !== right.length) return false;
+ return left.every((server) => {
+ const other = right.find((candidate) => candidate.id === server.id);
+ return other !== undefined && sameServer(server, other);
+ });
+}
+
export function toAcpMcpServers(
servers: readonly McpServer[],
): ReadonlyArray<EffectAcpSchema.McpServer> {
@@ -10,7 +65,10 @@ export function toAcpMcpServers(
type: "http" as const,
name: server.name,
url: server.url,
- headers: [],
+ headers: Object.entries(getMcpRuntimeHeaders(server)).map(([name, value]) => ({
+ name,
+ value,
+ })),
}
: {
name: server.name,
@@ -26,7 +84,7 @@ export function toClaudeMcpServers(servers: readonly McpServer[]) {
servers.map((server) => [
String(server.id),
server.transport === "url"
- ? { type: "http" as const, url: server.url, headers: {} }
+ ? { type: "http" as const, url: server.url, headers: getMcpRuntimeHeaders(server) }
: {
type: "stdio" as const,
command: server.command,
diff --git a/apps/server/src/provider/Services/AgentController.ts b/apps/server/src/provider/Services/AgentController.ts
index 7af6a92b4..dafb83fe0 100644
--- a/apps/server/src/provider/Services/AgentController.ts
+++ b/apps/server/src/provider/Services/AgentController.ts
@@ -1,6 +1,7 @@
import type {
AkeruConversationMemorySnapshot,
AkeruMemoryThreadAccess,
+ ComposioToolkit,
BotEngine,
BotId,
ModelSelection,
@@ -50,6 +51,13 @@ export interface AgentControllerShape {
readonly configurePluginRuntime?: (input: {
readonly readSnapshot: () => Promise<OrchestrationReadModel>;
readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;
+ readonly searchComposioToolkits?: (input: {
+ readonly query?: string;
+ readonly limit?: number;
+ }) => Promise<{
+ readonly status: "available" | "setup-required" | "unavailable";
+ readonly toolkits: readonly ComposioToolkit[];
+ }>;
}) => Effect.Effect<void>;
readonly configureDelegation?: (input: {
readonly readSnapshot: () => Promise<OrchestrationReadModel>;
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 592214721..bc4b55885 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -85,6 +85,7 @@ import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
+import * as Composio from "./composio/ComposioService.ts";
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
@@ -412,7 +413,12 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(ServerEnvironment.layer),
Layer.provideMerge(AuthLayerLive),
- Layer.provideMerge(ServerSecretStore.layer),
+ Layer.provideMerge(
+ Layer.mergeAll(
+ ServerSecretStore.layer,
+ Composio.layer.pipe(Layer.provide(ServerSecretStore.layer)),
+ ),
+ ),
);
const RuntimeCoreWithRoutinesLive = Layer.merge(
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 135b16130..dc4219084 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -150,6 +150,7 @@ import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
+import * as Composio from "./composio/ComposioService.ts";
import { requiredScopeForRpcMethod } from "./auth/RpcAuthorization.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
@@ -564,6 +565,8 @@ const makeWsRpcLayer = (
);
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
+ const composioService = yield* Effect.serviceOption(Composio.ComposioService);
+ const composio = Option.getOrElse(composioService, () => Composio.make(secretStore));
const channelDeliveryStore = yield* Effect.serviceOption(
ChannelDeliveryStore.ChannelDeliveryStore,
);
@@ -2209,6 +2212,30 @@ const makeWsRpcLayer = (
"rpc.aggregate": "server",
},
),
+ [WS_METHODS.composioGetStatus]: (_input) =>
+ observeRpcEffect(WS_METHODS.composioGetStatus, composio.getStatus, {
+ "rpc.aggregate": "composio",
+ }),
+ [WS_METHODS.composioConfigure]: ({ apiKey }) =>
+ observeRpcEffect(WS_METHODS.composioConfigure, composio.configure(apiKey), {
+ "rpc.aggregate": "composio",
+ }),
+ [WS_METHODS.composioRemove]: (_input) =>
+ observeRpcEffect(WS_METHODS.composioRemove, composio.remove, {
+ "rpc.aggregate": "composio",
+ }),
+ [WS_METHODS.composioSearchToolkits]: (input) =>
+ observeRpcEffect(WS_METHODS.composioSearchToolkits, composio.searchToolkits(input), {
+ "rpc.aggregate": "composio",
+ }),
+ [WS_METHODS.composioAuthorize]: (input) =>
+ observeRpcEffect(WS_METHODS.composioAuthorize, composio.authorize(input), {
+ "rpc.aggregate": "composio",
+ }),
+ [WS_METHODS.composioDisconnect]: ({ connectionId }) =>
+ observeRpcEffect(WS_METHODS.composioDisconnect, composio.disconnect(connectionId), {
+ "rpc.aggregate": "composio",
+ }),
[WS_METHODS.portabilityExport]: (_input) =>
observeRpcEffect(
WS_METHODS.portabilityExport,
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
index 71c679f0a..32f9114e2 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.test.tsx
@@ -35,24 +35,20 @@ function renderPanel() {
}
describe("ComposerPendingUserInputPanel", () => {
- it("renders the header as a disclosure control for the question body", () => {
+ it("renders a standalone question card with letter shortcuts", () => {
const markup = renderPanel();
- const toggle = markup.match(/<button[^>]*data-pending-user-input-toggle="[^"]*"[^>]*>/)?.[0];
- expect(toggle).toBeDefined();
- expect(toggle).toContain('data-pending-user-input-toggle="expanded"');
- expect(toggle).toContain('aria-expanded="true"');
- expect(toggle).toContain('type="button"');
-
- const controlledId = toggle?.match(/aria-controls="([^"]+)"/)?.[1];
- expect(controlledId).toBeDefined();
- expect(markup).toMatch(new RegExp(`<div[^>]*\\sid="${controlledId}"`));
+ expect(markup).toContain('data-testid="pending-user-input-card"');
+ expect(markup).toContain('aria-label="Which approach should the migration take?"');
+ expect(markup).toContain("<kbd");
+ expect(markup).toContain(">A</kbd>");
+ expect(markup).toContain(">B</kbd>");
+ expect(markup).not.toContain("data-pending-user-input-toggle");
});
it("starts expanded so the question and its options are visible", () => {
const markup = renderPanel();
- expect(markup).toContain("Approach");
expect(markup).toContain("Which approach should the migration take?");
expect(markup).toContain("Incremental");
expect(markup).toContain("Big bang");
@@ -75,5 +71,7 @@ describe("ComposerPendingUserInputPanel", () => {
);
expect(markup).toContain(">Submit</button>");
+ expect(markup).toContain('aria-pressed="true"');
+ expect(markup).toContain('aria-pressed="false"');
});
});
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
index 84fef3b17..e08e3d4a9 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
@@ -5,10 +5,8 @@ import {
derivePendingUserInputProgress,
type PendingUserInputDraftAnswer,
} from "../../pendingUserInput";
-import { CheckIcon, ChevronDownIcon } from "lucide-react";
-import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
+import { CheckIcon } from "lucide-react";
import { Button } from "../ui/button";
-import { Kbd } from "../ui/kbd";
import { cn } from "~/lib/utils";
interface PendingUserInputPanelProps {
@@ -19,6 +17,7 @@ interface PendingUserInputPanelProps {
onToggleOption: (questionId: string, optionLabel: string) => void;
onSelectSingleOption?: (questionId: string, optionLabel: string) => void;
onAdvance?: () => void;
+ className?: string;
}
export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
@@ -29,6 +28,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
onToggleOption,
onSelectSingleOption,
onAdvance,
+ className,
}: PendingUserInputPanelProps) {
if (pendingUserInputs.length === 0) return null;
const activePrompt = pendingUserInputs[0];
@@ -42,12 +42,12 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn
answers={answers}
questionIndex={questionIndex}
onToggleOption={onToggleOption}
+ {...(className ? { className } : {})}
{...(onSelectSingleOption ? { onSelectSingleOption } : {})}
{...(onAdvance ? { onAdvance } : {})}
/>
);
});
-
const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
prompt,
isResponding,
@@ -56,6 +56,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
onToggleOption,
onSelectSingleOption,
onAdvance,
+ className,
}: {
prompt: PendingUserInput;
isResponding: boolean;
@@ -64,6 +65,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
onToggleOption: (questionId: string, optionLabel: string) => void;
onSelectSingleOption?: (questionId: string, optionLabel: string) => void;
onAdvance?: () => void;
+ className?: string;
}) {
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
const activeQuestion = progress.activeQuestion;
@@ -72,15 +74,6 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
questionId: string;
optionLabel: string;
} | null>(null);
- // Collapsing hides everything but the header so a tall prompt stops covering
- // the thread the user is trying to read. Scoped to a single question: the card
- // is keyed by request id so the next prompt starts expanded, and storing the
- // collapsed question's id (rather than a bare flag) reopens the card when the
- // prompt advances to its next question, which can happen without a click —
- // sending from the composer advances the active question.
- const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
- const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
-
useEffect(
() => () => {
if (autoAdvanceTimerRef.current !== null) {
@@ -136,12 +129,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
[activeQuestion, onAdvance, onSelectSingleOption, onToggleOption],
);
- // Keyboard shortcut: number keys 1-9 select corresponding options when focus is
- // outside editable fields. Multi-select prompts toggle options in place; single-
- // select prompts keep the existing auto-advance behavior. Collapsed prompts opt
- // out, since the numbers they refer to are not on screen.
useEffect(() => {
- if (!activeQuestion || isResponding || isCollapsed) return;
+ if (!activeQuestion || isResponding) return;
const handler = (event: globalThis.KeyboardEvent) => {
if (event.metaKey || event.ctrlKey || event.altKey) return;
const target = event.target;
@@ -154,9 +143,13 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
) {
return;
}
- const digit = Number.parseInt(event.key, 10);
- if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
- const optionIndex = digit - 1;
+ const normalizedKey = event.key.toLocaleLowerCase();
+ const optionIndex = /^[1-9]$/.test(normalizedKey)
+ ? Number.parseInt(normalizedKey, 10) - 1
+ : /^[a-i]$/.test(normalizedKey)
+ ? normalizedKey.charCodeAt(0) - 97
+ : -1;
+ if (optionIndex < 0) return;
if (optionIndex >= activeQuestion.options.length) return;
const option = activeQuestion.options[optionIndex];
if (!option) return;
@@ -165,7 +158,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
- }, [activeQuestion, handleOptionSelection, isCollapsed, isResponding]);
+ }, [activeQuestion, handleOptionSelection, isResponding]);
if (!activeQuestion) {
return null;
@@ -174,133 +167,87 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
const customAnswerActive = progress.customAnswer.trim().length > 0;
return (
- <Collapsible
- className="pt-2 pb-2.5"
- open={!isCollapsed}
- onOpenChange={(open) => {
- setCollapsedQuestionId(open ? null : activeQuestion.id);
- }}
+ <section
+ aria-label={activeQuestion.question}
+ className={cn(
+ "w-full max-w-2xl rounded-2xl border border-border bg-foreground/5 p-3",
+ className,
+ )}
+ data-testid="pending-user-input-card"
>
- {/* The trigger's wrapper is inset less than the card's text column, and
- the trigger pays the difference back as padding: the hover background
- and focus ring bleed 10px past that column on both sides, while the
- header label and the chevron still line up with the left and right
- edges of the question text below. The negative block margin keeps the
- taller hit area from pushing the panel down. */}
- <div className="flex items-center px-3 sm:px-4">
- <CollapsibleTrigger
- title={
- isCollapsed ? "Show the question and its options" : "Hide the question and its options"
- }
- data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
- className="group -mx-1 flex min-w-0 flex-1 items-center gap-2 rounded-md px-1 py-1 text-left outline-none transition-colors duration-150 hover:text-foreground focus-visible:ring-1 focus-visible:ring-primary/25"
- >
- <span className="text-[11px] font-medium text-muted-foreground group-hover:text-foreground/85">
- {activeQuestion.header}
+ <div className="flex items-start gap-3">
+ <p className="min-w-0 flex-1 text-[15px] font-medium leading-6 text-foreground">
+ {activeQuestion.question}
+ </p>
+ {prompt.questions.length > 1 ? (
+ <span className="mt-1 shrink-0 text-[11px] text-muted-foreground tabular-nums">
+ {questionIndex + 1}/{prompt.questions.length}
</span>
- {prompt.questions.length > 1 ? (
- <span className="text-[10px] font-medium text-muted-foreground tabular-nums">
- {questionIndex + 1}/{prompt.questions.length}
- </span>
- ) : null}
- {/* Collapsed, the header is otherwise just a section label and a
- counter, so the question itself is echoed here as a one-line
- reminder of what is being asked. */}
- {isCollapsed ? (
- <span className="min-w-0 flex-1 truncate text-secondary-label text-xs">
- {activeQuestion.question}
- </span>
- ) : null}
- {/* The chevron points at the body: down while it is open below the
- header, up while it is collapsed into it. */}
- <ChevronDownIcon
- aria-hidden="true"
- className={cn(
- "ml-auto size-3.5 shrink-0 text-secondary-label transition-transform duration-150 group-hover:text-foreground",
- isCollapsed && "rotate-180",
- )}
- />
- </CollapsibleTrigger>
+ ) : null}
+ </div>
+ {activeQuestion.multiSelect ? (
+ <p className="mt-1 text-xs text-muted-foreground">Select one or more.</p>
+ ) : null}
+ <div className="mt-3 overflow-hidden rounded-xl border border-border/80 bg-background/25 divide-y divide-border/70">
+ {activeQuestion.options.map((option, index) => {
+ const isOptimisticallySelected =
+ optimisticSingleSelect?.questionId === activeQuestion.id &&
+ optimisticSingleSelect.optionLabel === option.label;
+ const isSelected =
+ isOptimisticallySelected ||
+ (!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
+ const shortcutKey = index < 9 ? String.fromCharCode(65 + index) : null;
+ const className = cn(
+ "group flex min-h-12 w-full items-center gap-3 px-3 py-2.5 text-left outline-none transition-colors duration-150 focus-visible:relative focus-visible:z-10 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/35",
+ isSelected
+ ? "bg-muted/70 text-foreground"
+ : "bg-transparent text-foreground/90 hover:bg-muted/35",
+ isResponding && "opacity-50 cursor-not-allowed",
+ !isResponding && "cursor-pointer",
+ );
+ const content = (
+ <>
+ {shortcutKey !== null ? (
+ <kbd className="flex size-6 shrink-0 items-center justify-center rounded-md border border-border bg-muted/70 text-[11px] font-medium text-muted-foreground">
+ {shortcutKey}
+ </kbd>
+ ) : null}
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-sm font-medium">{option.label}</span>
+ {option.description && option.description !== option.label ? (
+ <span className="text-secondary-label text-[11px]">{option.description}</span>
+ ) : null}
+ </div>
+ {isSelected ? <CheckIcon className="size-3.5 shrink-0 text-primary" /> : null}
+ </>
+ );
+ return (
+ <button
+ key={`${activeQuestion.id}:${option.label}`}
+ type="button"
+ aria-pressed={isSelected}
+ disabled={isResponding}
+ onClick={() => {
+ handleOptionSelection(activeQuestion.id, option.label);
+ }}
+ className={className}
+ >
+ {content}
+ </button>
+ );
+ })}
</div>
- {/* The panel carries the horizontal padding itself: it clips its content
- while the height animates, so the option buttons have to sit inside
- that padding or their focus rings get shaved off at the edges. */}
- <CollapsiblePanel className="px-3 sm:px-4">
- <div className="pt-1.5">
- <p className="text-[15px] font-medium leading-5 text-foreground">
- {activeQuestion.question}
- </p>
- {activeQuestion.multiSelect ? (
- <p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
- ) : null}
- <div className="mt-3 space-y-1.5">
- {activeQuestion.options.map((option, index) => {
- const isOptimisticallySelected =
- optimisticSingleSelect?.questionId === activeQuestion.id &&
- optimisticSingleSelect.optionLabel === option.label;
- const isSelected =
- isOptimisticallySelected ||
- (!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
- const shortcutKey = index < 9 ? index + 1 : null;
- const className = cn(
- "group flex w-full items-center gap-2.5 rounded-lg border px-2.5 py-2.5 text-left outline-none transition-[background-color,border-color,color] duration-150 focus-visible:ring-2 focus-visible:ring-primary/25",
- isSelected
- ? "border-primary/35 bg-primary/[0.08] text-foreground"
- : "border-border/55 bg-background/25 text-foreground/85 hover:border-border/80 hover:bg-muted/30",
- isResponding && "opacity-50 cursor-not-allowed",
- !isResponding && "cursor-pointer",
- );
- const content = (
- <>
- {shortcutKey !== null ? (
- <Kbd
- className={cn(
- "size-5 shrink-0 rounded-md bg-foreground/[0.06] px-0 text-[10px]",
- isSelected && "bg-primary/15 text-primary",
- )}
- >
- {shortcutKey}
- </Kbd>
- ) : null}
- <div className="min-w-0 flex-1 flex flex-col gap-0.5">
- <span className="text-[13px] font-medium leading-4">{option.label}</span>
- {option.description && option.description !== option.label ? (
- <span className="text-secondary-label text-[11px] leading-4">
- {option.description}
- </span>
- ) : null}
- </div>
- {isSelected ? <CheckIcon className="size-3.5 shrink-0 text-primary" /> : null}
- </>
- );
- return (
- <button
- key={`${activeQuestion.id}:${option.label}`}
- type="button"
- disabled={isResponding}
- onClick={() => {
- handleOptionSelection(activeQuestion.id, option.label);
- }}
- className={className}
- >
- {content}
- </button>
- );
- })}
- </div>
- {activeQuestion.multiSelect && onAdvance ? (
- <div className="mt-2 flex justify-end">
- <Button
- size="xs"
- disabled={isResponding || progress.selectedOptionLabels.length === 0}
- onClick={onAdvance}
- >
- {questionIndex < prompt.questions.length - 1 ? "Continue" : "Submit"}
- </Button>
- </div>
- ) : null}
+ {activeQuestion.multiSelect && onAdvance ? (
+ <div className="mt-3 flex justify-end">
+ <Button
+ size="xs"
+ disabled={isResponding || progress.selectedOptionLabels.length === 0}
+ onClick={onAdvance}
+ >
+ {questionIndex < prompt.questions.length - 1 ? "Continue" : "Submit"}
+ </Button>
</div>
- </CollapsiblePanel>
- </Collapsible>
+ ) : null}
+ </section>
);
});
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
index d39858343..31aaa9912 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
@@ -1,6 +1,7 @@
import * as Equal from "effect/Equal";
import {
formatDuration,
+ pluginSearchResultForWorkEntry,
workEntryDisplayIndicatesToolFailure,
workEntryIndicatesToolNeutralStatus,
workLogEntryIsToolLike,
@@ -856,6 +857,7 @@ export function deriveMessagesTimelineRows(input: {
const onlyToolEntries = visibleGroupedEntries.every(
(entry) =>
workLogEntryIsToolLike(entry) &&
+ pluginSearchResultForWorkEntry(entry) === null &&
entry.agentSpawn === undefined &&
entry.tone !== "error",
);
diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx
index 4556c5ae5..2e399eefd 100644
--- a/apps/web/src/components/chat/MessagesTimeline.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx
@@ -1063,6 +1063,53 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("live-activity-focus");
});
+ it("renders plugin search results as actionable chat cards", () => {
+ const markup = renderToStaticMarkup(
+ <MessagesTimeline
+ {...buildProps()}
+ timelineEntries={[
+ {
+ id: "entry-plugin-search",
+ kind: "work",
+ createdAt: MESSAGE_CREATED_AT,
+ entry: {
+ id: "work-plugin-search",
+ createdAt: MESSAGE_CREATED_AT,
+ label: "SearchPlugins",
+ toolTitle: "SearchPlugins",
+ tone: "tool",
+ itemType: "dynamic_tool_call",
+ toolLifecycleStatus: "completed",
+ sourceActivityKind: "tool.completed",
+ toolData: {
+ kind: "plugin-search-results",
+ query: "email",
+ total: 1,
+ sources: { directory: "available", composio: "available" },
+ recommendations: [
+ {
+ id: "composio:gmail",
+ source: "composio",
+ name: "Gmail",
+ description: "Read and send email.",
+ action: "connect",
+ logoUrl: "https://logos.composio.dev/api/gmail",
+ },
+ ],
+ },
+ },
+ },
+ ]}
+ />,
+ );
+
+ expect(markup).toContain("Gmail");
+ expect(markup).toContain("Composio");
+ expect(markup).toContain("Connect Gmail");
+ expect(markup).toContain("https://logos.composio.dev/api/gmail");
+ expect(markup).not.toContain("SearchPlugins</span>");
+ });
+
it("scopes a live row failure to the tool named by the row", () => {
const turnId = TurnId.make("turn-live");
const markup = renderToStaticMarkup(
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 8a8f75463..a5a2b403b 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -34,6 +34,7 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { FileDiff } from "@pierre/diffs/react";
import {
deriveTimelineEntries,
+ pluginSearchResultForWorkEntry,
workEntryDisplayIndicatesToolFailure,
workLogEntryIsToolLike,
} from "../../session-logic";
@@ -68,6 +69,7 @@ import { Button } from "../ui/button";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesCard } from "./ChangedFilesTree";
+import { PluginSearchResultCard } from "./PluginSearchResultCard";
import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation";
import { keepTimelineEndVisibleAfterOverlayGrowth } from "./timelineScrollAnchoring";
import { MessageControls } from "./MessageControls";
@@ -2622,6 +2624,10 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
isExpandedToolGroupEntry: boolean;
}) {
const { workEntry, workspaceRoot, isExpandedToolGroupEntry } = props;
+ const pluginSearchResult = pluginSearchResultForWorkEntry(workEntry);
+ if (pluginSearchResult) {
+ return <PluginSearchResultCard result={pluginSearchResult} className="ms-7" />;
+ }
// Before any hooks: spawn CTA rows render their own component.
if (workEntry.agentSpawn) {
return <AgentSpawnCtaRow workEntry={workEntry} />;
diff --git a/apps/web/src/components/chat/PluginSearchResultCard.test.tsx b/apps/web/src/components/chat/PluginSearchResultCard.test.tsx
new file mode 100644
index 000000000..1c4d07dae
--- /dev/null
+++ b/apps/web/src/components/chat/PluginSearchResultCard.test.tsx
@@ -0,0 +1,134 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vite-plus/test";
+
+import { PluginSearchResultCard } from "./PluginSearchResultCard";
+
+describe("PluginSearchResultCard", () => {
+ it("shows only the top matching plugin", () => {
+ const markup = renderToStaticMarkup(
+ <PluginSearchResultCard
+ result={{
+ kind: "plugin-search-results",
+ query: "email",
+ total: 3,
+ sources: { directory: "available", composio: "setup-required" },
+ recommendations: [
+ {
+ id: "gmail",
+ source: "directory",
+ name: "Gmail",
+ description: "Email and inbox",
+ action: "connect",
+ logoUrl: "https://logos.composio.dev/api/gmail",
+ },
+ {
+ id: "composio:slack",
+ source: "composio",
+ name: "Slack",
+ description: "Messages and channels",
+ action: "connect",
+ },
+ {
+ id: "composio:notion",
+ source: "composio",
+ name: "Notion",
+ description: "Pages and databases",
+ action: "connect",
+ logoUrl: "https://logos.composio.dev/api/notion",
+ },
+ ],
+ }}
+ />,
+ );
+
+ expect(markup).toContain("Gmail");
+ expect(markup).not.toContain("Slack");
+ expect(markup).not.toContain("Notion");
+ expect(markup).toContain("Composio");
+ expect(markup).not.toContain("Email and inbox");
+ expect(markup).toContain("Set up Gmail");
+ expect(markup).toContain("Set up Composio first");
+ expect(markup).toContain('aria-label="Gmail plugin"');
+ expect(markup).not.toContain("Suggested");
+ expect(markup).not.toContain("View all");
+ expect(markup).not.toContain("Browse plugins");
+ expect(markup).not.toContain(">Akeru<");
+ });
+
+ it("uses the Composio logo endpoint when the top result omits a logo", () => {
+ const markup = renderToStaticMarkup(
+ <PluginSearchResultCard
+ result={{
+ kind: "plugin-search-results",
+ query: "slack",
+ total: 1,
+ sources: { directory: "available", composio: "available" },
+ recommendations: [
+ {
+ id: "composio:slack",
+ source: "composio",
+ name: "Slack",
+ description: "Messages and channels",
+ action: "connect",
+ },
+ ],
+ }}
+ />,
+ );
+
+ expect(markup).toContain("https://logos.composio.dev/api/slack");
+ });
+
+ it("disables unavailable plugin cards", () => {
+ const markup = renderToStaticMarkup(
+ <PluginSearchResultCard
+ result={{
+ kind: "plugin-search-results",
+ query: "local only",
+ total: 1,
+ sources: { directory: "available", composio: "unavailable" },
+ recommendations: [
+ {
+ id: "local-only",
+ source: "directory",
+ name: "Local only",
+ description: "Requires a local service",
+ action: "unavailable",
+ },
+ ],
+ }}
+ />,
+ );
+
+ expect(markup).toContain('aria-label="Unavailable Local only"');
+ expect(markup).toContain("disabled");
+ expect(markup).not.toContain("Open Local only");
+ });
+
+ it("shows a connected plugin with a manage action", () => {
+ const markup = renderToStaticMarkup(
+ <PluginSearchResultCard
+ result={{
+ kind: "plugin-search-results",
+ query: "gmail",
+ total: 1,
+ sources: { directory: "available", composio: "available" },
+ recommendations: [
+ {
+ id: "composio:gmail",
+ source: "composio",
+ name: "Gmail",
+ description: "Email and inbox",
+ action: "open",
+ logoUrl: "https://logos.composio.dev/api/gmail",
+ },
+ ],
+ }}
+ />,
+ );
+
+ expect(markup).toContain("Connected");
+ expect(markup).toContain('aria-label="Manage Gmail"');
+ expect(markup).not.toContain("Email and inbox");
+ });
+});
diff --git a/apps/web/src/components/chat/PluginSearchResultCard.tsx b/apps/web/src/components/chat/PluginSearchResultCard.tsx
new file mode 100644
index 000000000..75e701bb2
--- /dev/null
+++ b/apps/web/src/components/chat/PluginSearchResultCard.tsx
@@ -0,0 +1,112 @@
+import type { AkeruPluginRecommendation, AkeruPluginSearchResult } from "@t3tools/contracts";
+import { CheckCircle2Icon, WrenchIcon } from "lucide-react";
+import { memo } from "react";
+
+import { loadDirectoryCatalog } from "../../../../../plugins";
+import { openPlugins } from "../../pluginsDialogStore";
+import { cn } from "~/lib/utils";
+import { Button } from "../ui/button";
+
+const DIRECTORY_PLUGINS = new Map(loadDirectoryCatalog().map((plugin) => [plugin.id, plugin]));
+
+function recommendationActionLabel(
+ recommendation: AkeruPluginRecommendation,
+ composioStatus: AkeruPluginSearchResult["sources"]["composio"],
+): string {
+ if (recommendation.action === "install") return "Install";
+ if (
+ recommendation.action === "connect" &&
+ recommendationUsesComposio(recommendation) &&
+ composioStatus === "setup-required"
+ ) {
+ return "Set up";
+ }
+ if (recommendation.action === "connect") return "Connect";
+ if (recommendation.action === "unavailable") return "Unavailable";
+ return "Manage";
+}
+
+function recommendationLogo(recommendation: AkeruPluginRecommendation): string | undefined {
+ if (recommendation.logoUrl) return recommendation.logoUrl;
+ if (recommendation.source === "composio") {
+ const slug = recommendation.id.replace(/^composio:/, "");
+ return `https://logos.composio.dev/api/${encodeURIComponent(slug)}`;
+ }
+ return recommendation.source === "directory"
+ ? DIRECTORY_PLUGINS.get(recommendation.id)?.logo.src
+ : undefined;
+}
+
+function recommendationProviderLabel(recommendation: AkeruPluginRecommendation): string {
+ if (recommendation.source === "composio") return "Composio";
+ const plugin = DIRECTORY_PLUGINS.get(recommendation.id);
+ return plugin?.connection.type === "brokered" ? plugin.connection.broker.name : "Akeru";
+}
+
+function recommendationUsesComposio(recommendation: AkeruPluginRecommendation): boolean {
+ return recommendationProviderLabel(recommendation) === "Composio";
+}
+
+export const PluginSearchResultCard = memo(function PluginSearchResultCard({
+ result,
+ className,
+}: {
+ readonly result: AkeruPluginSearchResult;
+ readonly className?: string;
+}) {
+ const recommendation = result.recommendations[0];
+ if (!recommendation) return null;
+
+ const logo = recommendationLogo(recommendation);
+ const action = recommendationActionLabel(recommendation, result.sources.composio);
+ const connected = recommendation.action === "open";
+ const setupRequired =
+ recommendation.action === "connect" &&
+ recommendationUsesComposio(recommendation) &&
+ result.sources.composio === "setup-required";
+ return (
+ <section
+ aria-label={`${recommendation.name} plugin`}
+ className={cn(
+ "flex max-w-xl min-w-0 items-center gap-3 rounded-xl border border-border/70 bg-card/55 px-3 py-2.5",
+ className,
+ )}
+ >
+ <span className="flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted p-1.5">
+ {logo ? (
+ <img alt="" className="size-full object-contain" src={logo} />
+ ) : (
+ <WrenchIcon aria-hidden="true" className="size-4 text-muted-foreground" />
+ )}
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <p className="truncate text-sm font-medium">{recommendation.name}</p>
+ <span className="shrink-0 text-[11px] text-muted-foreground">
+ {recommendationProviderLabel(recommendation)}
+ </span>
+ </div>
+ {connected ? (
+ <p className="flex items-center gap-1 text-xs text-emerald-500">
+ <CheckCircle2Icon aria-hidden="true" className="size-3" />
+ Connected
+ </p>
+ ) : (
+ <p className="truncate text-xs text-muted-foreground">
+ {setupRequired ? "Set up Composio first" : recommendation.description}
+ </p>
+ )}
+ </div>
+ <Button
+ aria-label={`${action} ${recommendation.name}`}
+ className="h-8 rounded-full px-3.5 text-xs"
+ disabled={recommendation.action === "unavailable"}
+ size="sm"
+ variant="secondary"
+ onClick={() => openPlugins(recommendation.name)}
+ >
+ {action}
+ </Button>
+ </section>
+ );
+});
diff --git a/apps/web/src/components/plugins/PluginDetails.tsx b/apps/web/src/components/plugins/PluginDetails.tsx
index f777f42ee..57b475bff 100644
--- a/apps/web/src/components/plugins/PluginDetails.tsx
+++ b/apps/web/src/components/plugins/PluginDetails.tsx
@@ -1,11 +1,13 @@
import type { McpServer, ProviderAccessStatus } from "@t3tools/contracts";
import { ArrowUpRightIcon, ChevronLeftIcon } from "lucide-react";
import type { PluginDirectoryDefinition, PluginSkill } from "../../../../../plugins";
+import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { DialogHeader, DialogPanel, DialogTitle } from "../ui/dialog";
import { PluginLogoImage } from "./PluginsCatalog";
import {
pluginBlocker,
+ pluginBrokerName,
pluginConnectionLabel,
pluginExecutionLabel,
pluginPrimaryAction,
@@ -44,6 +46,28 @@ export function PluginDetailsContent({
}: PluginDetailsContentProps) {
const action = pluginPrimaryAction(plugin, server);
const blocker = pluginBlocker(plugin);
+ const brokerName = pluginBrokerName(plugin);
+ const connectionDetails = brokerName
+ ? [
+ ["Provider", brokerName],
+ ["Sign-in", `${plugin.publisher.name} ${pluginConnectionLabel(plugin)}`],
+ ["Status", server ? (server.enabled ? "Connected" : "Disabled") : "Not connected"],
+ ]
+ : [
+ ["Authentication", pluginConnectionLabel(plugin)],
+ ["Execution", pluginExecutionLabel(plugin)],
+ ["Transport", transportLabel(plugin)],
+ ["Status", server ? (server.enabled ? "Connected" : "Disabled") : "Not installed"],
+ [
+ "Health",
+ accessStatus
+ ? `${accessStatus.health.charAt(0).toUpperCase()}${accessStatus.health.slice(1).replaceAll("-", " ")}`
+ : "Not checked",
+ ],
+ ...(accessStatus?.repairAction ? [["Repair", accessStatus.repairAction]] : []),
+ ["Platforms", plugin.platforms.join(", ")],
+ ["License", plugin.license],
+ ];
return (
<DialogPanel className="px-6 pt-6! pb-6 sm:px-8">
<div className="mx-auto max-w-3xl space-y-6">
@@ -56,6 +80,15 @@ export function PluginDetailsContent({
<span className="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">
{plugin.category}
</span>
+ {brokerName ? (
+ <Badge
+ className="border-border/60 bg-background/60 text-muted-foreground"
+ size="sm"
+ variant="outline"
+ >
+ {brokerName}
+ </Badge>
+ ) : null}
</div>
<p className="mt-2 max-w-2xl text-sm leading-6 text-muted-foreground">
{plugin.description}
@@ -113,32 +146,13 @@ export function PluginDetailsContent({
Connection
</h3>
<dl className="grid grid-cols-2 gap-px overflow-hidden rounded-xl border bg-border text-sm sm:grid-cols-3">
- {[
- ["Authentication", pluginConnectionLabel(plugin)],
- ["Execution", pluginExecutionLabel(plugin)],
- ["Transport", transportLabel(plugin)],
- ["Status", server ? (server.enabled ? "Enabled" : "Disabled") : "Not installed"],
- [
- "Health",
- accessStatus
- ? `${accessStatus.health.charAt(0).toUpperCase()}${accessStatus.health.slice(1).replaceAll("-", " ")}`
- : "Not checked",
- ],
- ...(accessStatus?.repairAction ? [["Repair", accessStatus.repairAction]] : []),
- ["Platforms", plugin.platforms.join(", ")],
- ["License", plugin.license],
- ].map(([label, value]) => (
+ {connectionDetails.map(([label, value]) => (
<div className="bg-background px-4 py-3" key={label}>
<dt className="text-xs text-muted-foreground">{label}</dt>
<dd className="mt-1 font-medium">{value}</dd>
</div>
))}
</dl>
- {plugin.connection.type === "brokered" ? (
- <p className="mt-2 px-1 text-xs text-muted-foreground">
- Brokered by {plugin.connection.broker.name}
- </p>
- ) : null}
</section>
<section aria-labelledby="plugin-dependents-title">
diff --git a/apps/web/src/components/plugins/PluginsCatalog.tsx b/apps/web/src/components/plugins/PluginsCatalog.tsx
index 2cfe279c1..6eb2eba69 100644
--- a/apps/web/src/components/plugins/PluginsCatalog.tsx
+++ b/apps/web/src/components/plugins/PluginsCatalog.tsx
@@ -1,9 +1,11 @@
-import type { McpServer } from "@t3tools/contracts";
+import type { ComposioToolkit, McpServer } from "@t3tools/contracts";
import { CheckIcon, ChevronRightIcon, PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
import type { PluginDirectoryDefinition } from "../../../../../plugins";
+import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { findPluginServer, pluginMcpServerId } from "./pluginRegistry";
import {
+ pluginBrokerName,
pluginConnectionLabel,
pluginPrimaryAction,
type PluginSection,
@@ -59,6 +61,7 @@ function PluginRow({
readonly onOpen: () => void;
}) {
const action = pluginPrimaryAction(plugin, server);
+ const brokerName = pluginBrokerName(plugin);
return (
<article
className="group flex min-w-0 items-center rounded-xl pe-2.5 transition-colors hover:bg-muted/45"
@@ -75,6 +78,15 @@ function PluginRow({
<div className="flex min-w-0 items-center gap-2">
<h3 className="truncate text-sm font-medium leading-5">{plugin.title}</h3>
<span className="shrink-0 text-[11px] text-muted-foreground">{plugin.category}</span>
+ {brokerName ? (
+ <Badge
+ className="border-border/60 bg-background/60 px-1.5 text-muted-foreground"
+ size="sm"
+ variant="outline"
+ >
+ {brokerName}
+ </Badge>
+ ) : null}
{plugin.connection.type === "approval-pending" ||
plugin.connection.type === "verification-pending" ? (
<span className="shrink-0 text-[11px] text-warning-foreground">
@@ -145,6 +157,75 @@ export function PluginsCatalog({
);
}
+export function ComposioToolkitResults({
+ toolkits,
+ connectedToolkitIds,
+ pendingToolkitId,
+ onConnect,
+}: {
+ readonly toolkits: readonly ComposioToolkit[];
+ readonly connectedToolkitIds: ReadonlySet<string>;
+ readonly pendingToolkitId: string | null;
+ readonly onConnect: (toolkit: ComposioToolkit) => void;
+}) {
+ if (toolkits.length === 0) return null;
+ return (
+ <section aria-label="From Composio">
+ <div className="mb-2 flex items-center justify-between px-2">
+ <h2 className="text-xs font-medium text-muted-foreground">From Composio</h2>
+ <span className="text-xs text-muted-foreground">{toolkits.length}</span>
+ </div>
+ <div className="grid grid-cols-1 gap-x-7 md:grid-cols-2">
+ {toolkits.map((toolkit) => {
+ const connected = connectedToolkitIds.has(toolkit.slug);
+ return (
+ <article
+ className="flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5 transition-colors hover:bg-muted/45"
+ data-composio-toolkit={toolkit.slug}
+ key={toolkit.slug}
+ >
+ <span className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted p-2">
+ {toolkit.logoUrl ? (
+ <img alt="" className="size-full object-contain" src={toolkit.logoUrl} />
+ ) : (
+ <span aria-hidden="true" className="text-sm font-medium text-muted-foreground">
+ {toolkit.name.slice(0, 1).toUpperCase()}
+ </span>
+ )}
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 items-center gap-2">
+ <h3 className="truncate text-sm font-medium leading-5">{toolkit.name}</h3>
+ <Badge
+ className="border-border/60 bg-background/60 px-1.5 text-muted-foreground"
+ size="sm"
+ variant="outline"
+ >
+ Composio
+ </Badge>
+ </div>
+ <p className="truncate text-xs leading-5 text-muted-foreground">
+ {toolkit.description ?? `${toolkit.toolsCount} tools`}
+ </p>
+ </div>
+ <Button
+ aria-label={`${connected ? "Connected" : "Connect"} ${toolkit.name}`}
+ className="h-7 min-w-14 rounded-full px-3 text-xs"
+ disabled={connected || pendingToolkitId === toolkit.slug}
+ size="sm"
+ variant="secondary"
+ onClick={() => onConnect(toolkit)}
+ >
+ {connected ? "Connected" : "Connect"}
+ </Button>
+ </article>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
+
export function RemovedBuiltinServers({
servers,
pendingServerId,
diff --git a/apps/web/src/components/plugins/PluginsDialog.test.tsx b/apps/web/src/components/plugins/PluginsDialog.test.tsx
index 445dbac90..4388361ab 100644
--- a/apps/web/src/components/plugins/PluginsDialog.test.tsx
+++ b/apps/web/src/components/plugins/PluginsDialog.test.tsx
@@ -10,6 +10,7 @@ import {
import { PluginDetailsContent } from "./PluginDetails";
import {
EMPTY_MCP_SERVER_DRAFT,
+ COMPOSIO_APPS,
PLUGIN_DIRECTORY_FILTERS,
PLUGIN_DIALOG_CLASS_NAME,
PLUGIN_DIRECTORY_HEADER_CLASS_NAME,
@@ -17,7 +18,12 @@ import {
resolvePluginDialogServers,
validateMcpServerDraft,
} from "./PluginsDialog";
-import { CustomMcpServers, PluginsCatalog, RemovedBuiltinServers } from "./PluginsCatalog";
+import {
+ ComposioToolkitResults,
+ CustomMcpServers,
+ PluginsCatalog,
+ RemovedBuiltinServers,
+} from "./PluginsCatalog";
import { buildPluginSections } from "./pluginPresentation";
import { planPluginToggle, pluginMcpServerId } from "./pluginRegistry";
@@ -77,6 +83,81 @@ const removedBuiltinServer: McpServer = {
const noop = () => undefined;
describe("Plugins dialog content", () => {
+ it("lists Gmail as an app connected through Composio", () => {
+ const gmail = COMPOSIO_APPS[0];
+ const markup = renderToStaticMarkup(
+ <PluginsCatalog
+ sections={buildPluginSections({ plugins: COMPOSIO_APPS, query: "gmail", filter: "All" })}
+ servers={[]}
+ pendingServerId={null}
+ onToggle={noop}
+ onOpen={noop}
+ />,
+ );
+
+ expect(gmail.id).toBe("gmail");
+ expect(markup).toContain("Gmail");
+ expect(markup).toContain("Composio");
+ expect(markup).toContain("Connect Gmail");
+ });
+
+ it("renders Composio search results with a neutral fallback when no logo exists", () => {
+ const markup = renderToStaticMarkup(
+ <ComposioToolkitResults
+ toolkits={[
+ {
+ slug: "google-calendar",
+ name: "Google Calendar",
+ description: "Manage calendars and events.",
+ categories: ["Productivity"],
+ toolsCount: 12,
+ },
+ ]}
+ connectedToolkitIds={new Set()}
+ pendingToolkitId={null}
+ onConnect={noop}
+ />,
+ );
+
+ expect(markup).toContain('data-composio-toolkit="google-calendar"');
+ expect(markup).toContain("Google Calendar");
+ expect(markup).toContain("Manage calendars and events.");
+ expect(markup).toContain("Connect Google Calendar");
+ expect(markup).toMatch(/aria-hidden="true"[^>]*>G<\/span>/);
+ });
+
+ it("presents Composio once as Gmail's connection provider", () => {
+ const gmail = COMPOSIO_APPS[0];
+ const markup = renderToStaticMarkup(
+ <PluginDetailsContent
+ plugin={gmail}
+ server={undefined}
+ activeDependentBotNames={[]}
+ pending={false}
+ onToggle={noop}
+ onRemove={noop}
+ onViewDocumentation={noop}
+ onViewSource={noop}
+ onOpenSkill={noop}
+ />,
+ );
+
+ expect(gmail.logo.src).toBe("https://logos.composio.dev/api/gmail");
+ expect(markup).toContain('src="https://logos.composio.dev/api/gmail"');
+ expect(markup).not.toContain("/plugin-logos/gmail.svg");
+ expect(markup).toContain("Provider");
+ expect(markup).toContain("Composio");
+ expect(markup).toContain("Sign-in");
+ expect(markup).toContain("Google OAuth");
+ expect(markup).toContain("Not connected");
+ expect(markup).not.toContain("Authentication");
+ expect(markup).not.toContain("Execution");
+ expect(markup).not.toContain("Health");
+ expect(markup).not.toContain("Transport");
+ expect(markup).not.toContain("Platforms");
+ expect(markup).not.toContain("License");
+ });
+
it("keeps the directory and details at one fixed size", () => {
expect(PLUGIN_DIALOG_CLASS_NAME).toContain("h-[min(48rem,90dvh)]");
expect(PLUGIN_DIRECTORY_HEADER_CLASS_NAME).not.toContain("border-b");
diff --git a/apps/web/src/components/plugins/PluginsDialog.tsx b/apps/web/src/components/plugins/PluginsDialog.tsx
index 5ea86390a..95b8b56db 100644
--- a/apps/web/src/components/plugins/PluginsDialog.tsx
+++ b/apps/web/src/components/plugins/PluginsDialog.tsx
@@ -5,12 +5,13 @@ import {
} from "@t3tools/client-runtime/state/runtime";
import {
McpServerId,
+ type ComposioToolkit,
type EnvironmentId,
type McpServer,
type ProviderAccessStatus,
} from "@t3tools/contracts";
import { SearchIcon } from "lucide-react";
-import { useState } from "react";
+import { useDeferredValue, useEffect, useState } from "react";
import {
isInstallablePlugin,
loadDirectoryCatalog,
@@ -41,7 +42,13 @@ import { Input } from "../ui/input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Textarea } from "../ui/textarea";
import { toastManager } from "../ui/toast";
-import { CustomMcpServers, PluginsCatalog, RemovedBuiltinServers } from "./PluginsCatalog";
+import {
+ CustomMcpServers,
+ ComposioToolkitResults,
+ PluginLogoImage,
+ PluginsCatalog,
+ RemovedBuiltinServers,
+} from "./PluginsCatalog";
import { PluginDetails } from "./PluginDetails";
import {
findPluginServer,
@@ -57,6 +64,9 @@ import {
} from "./pluginPresentation";
const CATALOG = loadDirectoryCatalog();
+const gmailPlugin = CATALOG.find((plugin) => plugin.id === "gmail");
+if (!gmailPlugin) throw new TypeError("Gmail is missing from the plugin directory.");
+export const COMPOSIO_APPS = [gmailPlugin] as const;
export const PLUGIN_DIRECTORY_FILTERS = buildPluginFilters(CATALOG);
export function resolvePluginDialogServers(
@@ -134,35 +144,96 @@ export function validateMcpServerDraft(draft: McpServerDraft): string | null {
}
function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId: EnvironmentId }) {
+ const requestedQuery = usePluginsDialogStore((state) => state.requestedQuery);
const servers = useAtomValue(environmentMcpServersAtom(environmentId));
const bots = useAtomValue(environmentBotsAtom(environmentId));
const subscriptionAuth = useEnvironmentQuery(
serverEnvironment.subscriptionAuth({ environmentId, input: {} }),
);
+ const composioStatus = useEnvironmentQuery(
+ serverEnvironment.composioStatus({ environmentId, input: {} }),
+ );
+ const configureComposio = useAtomCommand(serverEnvironment.configureComposio, {
+ reportFailure: false,
+ });
+ const authorizeComposio = useAtomCommand(serverEnvironment.authorizeComposio, {
+ reportFailure: false,
+ });
+ const disconnectComposio = useAtomCommand(serverEnvironment.disconnectComposio, {
+ reportFailure: false,
+ });
const createServer = useAtomCommand(mcpServerEnvironment.create, { reportFailure: false });
const updateServer = useAtomCommand(mcpServerEnvironment.update, { reportFailure: false });
const deleteServer = useAtomCommand(mcpServerEnvironment.delete, { reportFailure: false });
const enableServer = useAtomCommand(mcpServerEnvironment.enable, { reportFailure: false });
const disableServer = useAtomCommand(mcpServerEnvironment.disable, { reportFailure: false });
const [query, setQuery] = useState("");
+ const deferredQuery = useDeferredValue(query.trim());
const [filter, setFilter] = useState<PluginFilter>("All");
const [selectedPlugin, setSelectedPlugin] = useState<PluginDirectoryDefinition | null>(null);
const [editorTarget, setEditorTarget] = useState<EditorTarget | null>(null);
const [draft, setDraft] = useState(EMPTY_MCP_SERVER_DRAFT);
const [submitAttempted, setSubmitAttempted] = useState(false);
const [pendingServerId, setPendingServerId] = useState<string | null>(null);
+ const [composioSetupPlugin, setComposioSetupPlugin] = useState<PluginDirectoryDefinition | null>(
+ null,
+ );
+ const [composioApiKey, setComposioApiKey] = useState("");
+ const composioToolkits = useEnvironmentQuery(
+ composioStatus.data?.configured === true && deferredQuery.length >= 2
+ ? serverEnvironment.composioToolkits({
+ environmentId,
+ input: { query: deferredQuery, limit: 12 },
+ })
+ : null,
+ );
const { customServers, installedPlugins, removedBuiltinServers } =
resolvePluginDialogServers(servers);
+ const connectedComposioPluginIds = new Set(
+ (composioStatus.data?.connections ?? [])
+ .filter((connection) => connection.status === "ACTIVE")
+ .map((connection) => connection.toolkitSlug),
+ );
+ const composioViewServers: readonly McpServer[] = CATALOG.filter(
+ (plugin) => plugin.connection.type === "brokered" && connectedComposioPluginIds.has(plugin.id),
+ ).map((plugin) => ({
+ id: pluginMcpServerId(plugin),
+ name: plugin.title,
+ transport: "url" as const,
+ url: "https://composio.dev",
+ enabled: true,
+ createdAt: "1970-01-01T00:00:00.000Z",
+ updatedAt: "1970-01-01T00:00:00.000Z",
+ }));
+ const displayServers = [...servers, ...composioViewServers];
+ const brokeredCatalogIds = new Set(
+ CATALOG.filter((plugin) => plugin.connection.type === "brokered").map((plugin) => plugin.id),
+ );
+ const composioSearchResults = (composioToolkits.data ?? []).filter(
+ (toolkit) => !brokeredCatalogIds.has(toolkit.slug),
+ );
const sections = buildPluginSections({
plugins: CATALOG,
query,
filter,
- installedPluginIds: new Set(installedPlugins.map((plugin) => plugin.id)),
+ installedPluginIds: new Set([
+ ...installedPlugins.map((plugin) => plugin.id),
+ ...connectedComposioPluginIds,
+ ]),
});
const validationError = validateMcpServerDraft(draft);
const selectedPluginServer = selectedPlugin
- ? findPluginServer(selectedPlugin, servers)
+ ? findPluginServer(selectedPlugin, displayServers)
: undefined;
+
+ useEffect(() => {
+ const refresh = () => composioStatus.refresh();
+ window.addEventListener("focus", refresh);
+ return () => window.removeEventListener("focus", refresh);
+ }, [composioStatus.refresh]);
+ useEffect(() => {
+ if (requestedQuery !== null) setQuery(requestedQuery);
+ }, [requestedQuery]);
const selectedPluginAccess: ProviderAccessStatus | undefined = selectedPlugin
? subscriptionAuth.data?.access.find((status) => status.pluginId === selectedPlugin.id)
: undefined;
@@ -199,6 +270,63 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId
};
const togglePlugin = async (plugin: PluginDirectoryDefinition, enabled: boolean) => {
+ if (plugin.connection.type === "brokered" && plugin.connection.broker.name === "Composio") {
+ const mcpServerId = pluginMcpServerId(plugin);
+ if (enabled && composioStatus.data?.configured !== true) {
+ setComposioSetupPlugin(plugin);
+ return;
+ }
+ setPendingServerId(mcpServerId);
+ if (enabled) {
+ const result = await authorizeComposio({
+ environmentId,
+ input: { toolkitSlug: plugin.id },
+ });
+ setPendingServerId(null);
+ if (result._tag === "Failure") {
+ if (!isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ toastManager.add({
+ type: "error",
+ title: `Could not connect ${plugin.title}`,
+ description: error instanceof Error ? error.message : "The command failed.",
+ });
+ }
+ return;
+ }
+ openExternal(result.value.redirectUrl, `Could not open ${plugin.title} sign-in`);
+ return;
+ }
+ const connections = (composioStatus.data?.connections ?? []).filter(
+ (connection) => connection.toolkitSlug === plugin.id,
+ );
+ const confirmed = await ensureLocalApi().dialogs.confirm(
+ `Disconnect ${connections.length} ${plugin.title} account${connections.length === 1 ? "" : "s"}?`,
+ { variant: "destructive" },
+ );
+ if (!confirmed) {
+ setPendingServerId(null);
+ return;
+ }
+ for (const connection of connections) {
+ const result = await disconnectComposio({
+ environmentId,
+ input: { connectionId: connection.id },
+ });
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ toastManager.add({
+ type: "error",
+ title: `Could not disconnect ${plugin.title}`,
+ description: error instanceof Error ? error.message : "The command failed.",
+ });
+ break;
+ }
+ }
+ setPendingServerId(null);
+ composioStatus.refresh();
+ return;
+ }
let plan;
if (enabled) {
if (!isInstallablePlugin(plugin)) return;
@@ -234,6 +362,67 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId
);
};
+ const connectComposioToolkit = async (toolkit: ComposioToolkit) => {
+ setPendingServerId(`composio:${toolkit.slug}`);
+ const result = await authorizeComposio({
+ environmentId,
+ input: { toolkitSlug: toolkit.slug },
+ });
+ setPendingServerId(null);
+ if (result._tag === "Failure") {
+ if (!isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ toastManager.add({
+ type: "error",
+ title: `Could not connect ${toolkit.name}`,
+ description: error instanceof Error ? error.message : "The command failed.",
+ });
+ }
+ return;
+ }
+ openExternal(result.value.redirectUrl, `Could not open ${toolkit.name} sign-in`);
+ };
+
+ const saveComposioAndConnect = async () => {
+ const plugin = composioSetupPlugin;
+ const apiKey = composioApiKey.trim();
+ if (!plugin || !apiKey) return;
+ setPendingServerId(pluginMcpServerId(plugin));
+ const configured = await configureComposio({ environmentId, input: { apiKey } });
+ if (configured._tag === "Failure") {
+ setPendingServerId(null);
+ if (!isAtomCommandInterrupted(configured)) {
+ const error = squashAtomCommandFailure(configured);
+ toastManager.add({
+ type: "error",
+ title: "Could not connect Composio",
+ description: error instanceof Error ? error.message : "The command failed.",
+ });
+ }
+ return;
+ }
+ const authorized = await authorizeComposio({
+ environmentId,
+ input: { toolkitSlug: plugin.id },
+ });
+ setPendingServerId(null);
+ if (authorized._tag === "Failure") {
+ if (!isAtomCommandInterrupted(authorized)) {
+ const error = squashAtomCommandFailure(authorized);
+ toastManager.add({
+ type: "error",
+ title: `Could not connect ${plugin.title}`,
+ description: error instanceof Error ? error.message : "The command failed.",
+ });
+ }
+ return;
+ }
+ setComposioApiKey("");
+ setComposioSetupPlugin(null);
+ composioStatus.refresh();
+ openExternal(authorized.value.redirectUrl, `Could not open ${plugin.title} sign-in`);
+ };
+
const toggleCustom = async (server: McpServer, enabled: boolean) => {
setPendingServerId(server.id);
const result = await (enabled ? enableServer : disableServer)({
@@ -312,6 +501,10 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId
onBack={() => setSelectedPlugin(null)}
onToggle={(enabled) => void togglePlugin(selectedPlugin, enabled)}
onRemove={() => {
+ if (selectedPlugin.connection.type === "brokered") {
+ void togglePlugin(selectedPlugin, false);
+ return;
+ }
const server = findPluginServer(selectedPlugin, servers);
if (server) void removeServer(server);
}}
@@ -365,11 +558,21 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId
<DialogPanel className={PLUGIN_DIRECTORY_PANEL_CLASS_NAME}>
<PluginsCatalog
sections={sections}
- servers={servers}
+ servers={displayServers}
pendingServerId={pendingServerId}
onToggle={(plugin, enabled) => void togglePlugin(plugin, enabled)}
onOpen={openPlugin}
/>
+ <ComposioToolkitResults
+ toolkits={composioSearchResults}
+ connectedToolkitIds={connectedComposioPluginIds}
+ pendingToolkitId={
+ pendingServerId?.startsWith("composio:")
+ ? pendingServerId.slice("composio:".length)
+ : null
+ }
+ onConnect={(toolkit) => void connectComposioToolkit(toolkit)}
+ />
{filter === "Installed" ? (
<>
<RemovedBuiltinServers
@@ -467,6 +670,65 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId
</DialogFooter>
</DialogPopup>
</Dialog>
+ <Dialog
+ open={composioSetupPlugin !== null}
+ onOpenChange={(open) => {
+ if (!open) setComposioSetupPlugin(null);
+ }}
+ >
+ <DialogPopup className="max-w-md">
+ <DialogHeader className="pb-4">
+ <div className="flex items-center gap-3 pe-8">
+ {composioSetupPlugin ? (
+ <PluginLogoImage className="size-11 rounded-xl" plugin={composioSetupPlugin} />
+ ) : null}
+ <div className="min-w-0">
+ <DialogTitle>Connect {composioSetupPlugin?.title}</DialogTitle>
+ <DialogDescription>Sign-in handled by Composio</DialogDescription>
+ </div>
+ </div>
+ </DialogHeader>
+ <div className="space-y-4 border-t px-6 py-5">
+ <Field>
+ <FieldLabel>Composio API key</FieldLabel>
+ <Input
+ autoFocus
+ autoComplete="off"
+ type="password"
+ value={composioApiKey}
+ onChange={(event) => setComposioApiKey(event.currentTarget.value)}
+ />
+ <p className="text-xs leading-5 text-muted-foreground">
+ Stored only on this Akeru Bot server.
+ </p>
+ </Field>
+ <Button
+ className="px-0"
+ size="sm"
+ variant="link"
+ onClick={() =>
+ openExternal(
+ "https://app.composio.dev/settings/api-keys",
+ "Could not open Composio",
+ )
+ }
+ >
+ Create a Composio API key
+ </Button>
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => setComposioSetupPlugin(null)}>
+ Cancel
+ </Button>
+ <Button
+ disabled={!composioApiKey.trim() || pendingServerId !== null}
+ onClick={() => void saveComposioAndConnect()}
+ >
+ Connect
+ </Button>
+ </DialogFooter>
+ </DialogPopup>
+ </Dialog>
</>
);
}
diff --git a/apps/web/src/components/plugins/pluginPresentation.test.ts b/apps/web/src/components/plugins/pluginPresentation.test.ts
index 4d5fdd3ca..d78223a5d 100644
--- a/apps/web/src/components/plugins/pluginPresentation.test.ts
+++ b/apps/web/src/components/plugins/pluginPresentation.test.ts
@@ -9,6 +9,7 @@ import {
buildPluginFilters,
buildPluginSections,
pluginActiveDependentBotNames,
+ pluginBrokerName,
pluginConnectionLabel,
pluginMatchesQuery,
pluginPrimaryAction,
@@ -43,7 +44,7 @@ const verificationPlugin = {
type: "verification-pending",
blocker: "The connection lifecycle still needs verification.",
},
- catalogStatus: "verification-pending",
+ catalogStatus: "available",
} satisfies PluginDirectoryDefinition;
const apiKeyPlugin = {
...firecrawl,
@@ -54,6 +55,23 @@ const apiKeyPlugin = {
connection: { type: "api-key" },
requiredCredentials: ["key-vendor-api-key"],
} satisfies PluginDirectoryDefinition;
+const brokeredPlugin = {
+ ...pendingBase,
+ id: "gmail",
+ name: "Gmail",
+ title: "Gmail",
+ description: "Read, draft, and send Gmail messages.",
+ tags: ["email", "inbox"],
+ authentication: "oauth",
+ requiredCredentials: [],
+ kind: "mcp-unavailable",
+ transport: { type: "unavailable" },
+ connection: {
+ type: "brokered",
+ broker: { name: "Composio", url: "https://composio.dev" },
+ },
+ catalogStatus: "verification-pending",
+} satisfies PluginDirectoryDefinition;
function server(enabled: boolean): McpServer {
return {
@@ -92,7 +110,7 @@ describe("plugin presentation", () => {
buildPluginSections({ plugins: catalog, query: "", filter: "All" }).flatMap((section) =>
section.plugins.map((plugin) => plugin.id),
),
- ).toHaveLength(53);
+ ).toHaveLength(54);
expect(
buildPluginSections({
plugins: catalog,
@@ -105,7 +123,7 @@ describe("plugin presentation", () => {
buildPluginSections({ plugins: catalog, query: "", filter: "Featured" })[0]?.plugins.map(
(plugin) => plugin.id,
),
- ).toEqual(["context", "zernio", "hoplite"]);
+ ).toEqual(["context", "gmail", "zernio", "hoplite"]);
expect(
buildPluginSections({ plugins: catalog, query: "", filter: "Web" })[0]?.plugins.map(
(plugin) => plugin.id,
@@ -135,6 +153,7 @@ describe("plugin presentation", () => {
expect(sections.every((section) => section.plugins.length > 0)).toBe(true);
expect(sections[0]?.plugins.map((plugin) => plugin.id)).toEqual([
"context",
+ "gmail",
"zernio",
"hoplite",
]);
@@ -221,4 +240,18 @@ describe("plugin presentation", () => {
});
expect(pluginConnectionLabel(verificationPlugin)).toBe("Verification pending");
});
+
+ it("names the broker without hiding the app it stands for", () => {
+ expect(pluginBrokerName(brokeredPlugin)).toBe("Composio");
+ expect(pluginBrokerName(firecrawl)).toBeNull();
+ for (const query of ["Gmail", "email", "inbox", "Composio"]) {
+ expect(pluginMatchesQuery(brokeredPlugin, query)).toBe(true);
+ }
+ expect(pluginMatchesQuery(firecrawl, "Composio")).toBe(false);
+ expect(pluginPrimaryAction(brokeredPlugin, undefined)).toEqual({
+ label: "Connect",
+ enable: true,
+ });
+ expect(pluginConnectionLabel(brokeredPlugin)).toBe("OAuth");
+ });
});
diff --git a/apps/web/src/components/plugins/pluginPresentation.ts b/apps/web/src/components/plugins/pluginPresentation.ts
index 662acd553..3e6169123 100644
--- a/apps/web/src/components/plugins/pluginPresentation.ts
+++ b/apps/web/src/components/plugins/pluginPresentation.ts
@@ -46,6 +46,7 @@ export function pluginMatchesQuery(plugin: PluginDirectoryDefinition, query: str
...plugin.tags,
...plugin.capabilities,
plugin.publisher.name,
+ ...(plugin.connection.type === "brokered" ? [plugin.connection.broker.name] : []),
]
.join("\n")
.toLocaleLowerCase()
@@ -89,6 +90,7 @@ export function buildPluginSections(input: {
}
export function pluginBlocker(plugin: PluginDirectoryDefinition): string | null {
+ if (plugin.connection.type === "brokered") return null;
if (
plugin.connection.type === "approval-pending" ||
plugin.connection.type === "verification-pending"
@@ -125,7 +127,17 @@ export function pluginConnectionLabel(plugin: PluginDirectoryDefinition): string
return "No sign-in";
}
+/**
+ * Names the broker that holds a plugin's accounts. Catalog rows and details use
+ * it so an app such as Gmail reads as its own entry while still saying who
+ * actually carries the connection.
+ */
+export function pluginBrokerName(plugin: PluginDirectoryDefinition): string | null {
+ return plugin.connection.type === "brokered" ? plugin.connection.broker.name : null;
+}
+
export function pluginExecutionLabel(plugin: PluginDirectoryDefinition): string {
+ if (plugin.connection.type === "brokered") return "Hosted";
if (plugin.kind === "mcp-unavailable") return "Unavailable";
return plugin.kind === "mcp-stdio" || plugin.connection.type === "local" ? "Local" : "Hosted";
}
diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsx
index fa804839d..144f45a72 100644
--- a/apps/web/src/components/roster/BotThreadLanding.tsx
+++ b/apps/web/src/components/roster/BotThreadLanding.tsx
@@ -5,6 +5,7 @@ import {
type EnvironmentId,
type MessageId,
type ThreadId,
+ type TurnId,
} from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
@@ -35,7 +36,6 @@ import ChatMarkdown from "../ChatMarkdown";
import { WorkspacePageHeader } from "../WorkspacePageHeader";
import { BotActivityStatus } from "./BotActivityStatus";
import { BotApprovalPrompt } from "./BotApprovalPrompt";
-import { BotUserInputPrompt } from "./BotUserInputPrompt";
import { BotInboxAlertStack } from "./BotInboxAlertStack";
import { BotAvatarView } from "./BotAvatarView";
import { BotConversationScrollArea } from "./BotConversationScrollArea";
@@ -52,6 +52,8 @@ import { BotMessageAttachments } from "./BotMessageAttachments";
import { BotStepMeter } from "./BotStepMeter";
import { buildBotStepMeters } from "./botStepMeter.logic";
import { ThreadErrorBanner } from "../chat/ThreadErrorBanner";
+import { ComposerPendingUserInputPanel } from "../chat/ComposerPendingUserInputPanel";
+import { PluginSearchResultCard } from "../chat/PluginSearchResultCard";
import {
buildReplyPrompt,
MessageControls,
@@ -65,6 +67,7 @@ import { useBotPresence } from "./botPresence";
import { useRosterStore } from "./rosterStore";
import { useBotThreadRuntime } from "./useBotThreadRuntime";
import { useRosterPendingApproval } from "./useRosterPendingApproval";
+import { deriveWorkLogEntries, pluginSearchResultForWorkEntry } from "../../session-logic";
const NO_ENVIRONMENT = "" as EnvironmentId;
@@ -159,6 +162,23 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
const approvalState = useRosterPendingApproval(runtime.linkedThreadRef);
const activities = useThreadActivities(runtime.linkedThreadRef);
const stepMeters = useMemo(() => buildBotStepMeters(activities), [activities]);
+ const pluginResultsByTurn = useMemo(() => {
+ const results = new Map<
+ TurnId,
+ {
+ readonly id: string;
+ readonly result: NonNullable<ReturnType<typeof pluginSearchResultForWorkEntry>>;
+ }[]
+ >();
+ for (const entry of deriveWorkLogEntries(activities)) {
+ const result = pluginSearchResultForWorkEntry(entry);
+ if (!result || !entry.turnId) continue;
+ const turnResults = results.get(entry.turnId) ?? [];
+ turnResults.push({ id: entry.id, result });
+ results.set(entry.turnId, turnResults);
+ }
+ return results;
+ }, [activities]);
const voiceCall = useVoiceCall();
const presence = useBotPresence(botId);
const inboxQuery = useEnvironmentQuery(
@@ -187,8 +207,15 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
presence,
});
const messages = visibleBotChatMessages(runtime.messages, working);
+ const assistantTurnIds = new Set(
+ messages.flatMap((message) =>
+ message.role === "assistant" && message.turnId !== null ? [message.turnId] : [],
+ ),
+ );
+ const pendingPluginResults = [...pluginResultsByTurn.entries()].filter(
+ ([turnId]) => !assistantTurnIds.has(turnId),
+ );
const pendingApproval = approvalState.pendingApproval;
- const pendingUserInput = runtime.pendingUserInputs[0] ?? null;
const inboxItems = selectOpenBotInboxItems(inboxQuery.data?.inbox ?? [], new Set([bot.id]));
const delegations = runtime.linkedThreadRef
? (snapshot?.delegations.filter(
@@ -278,6 +305,13 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
text={message.text}
threadRef={runtime.linkedThreadRef ?? undefined}
/>
+ {message.turnId === null
+ ? null
+ : pluginResultsByTurn
+ .get(message.turnId)
+ ?.map(({ id, result }) => (
+ <PluginSearchResultCard className="mt-3" key={id} result={result} />
+ ))}
<div className="mt-1 flex opacity-0 transition-opacity focus-within:opacity-100 group-hover/message:opacity-100 max-md:opacity-100">
<MessageControls
copyText={message.text || "Attachment"}
@@ -381,6 +415,44 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
),
)
)}
+ {pendingPluginResults.map(([turnId, results]) => (
+ <div className="flex items-start gap-3" key={`${turnId}:plugins`}>
+ <BotAvatarView
+ avatar={bot.avatar}
+ name={bot.name}
+ className="mt-0.5 size-7 shrink-0"
+ />
+ <div className="min-w-0 flex-1 space-y-3">
+ <div className="text-sm font-medium">{bot.name}</div>
+ {results.map(({ id, result }) => (
+ <PluginSearchResultCard key={id} result={result} />
+ ))}
+ </div>
+ </div>
+ ))}
+ {runtime.pendingUserInputs.length > 0 ? (
+ <div className="flex items-start gap-3">
+ <BotAvatarView
+ avatar={bot.avatar}
+ name={bot.name}
+ className="mt-0.5 size-7 shrink-0"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="mb-2 text-sm font-medium">{bot.name}</div>
+ <ComposerPendingUserInputPanel
+ pendingUserInputs={runtime.pendingUserInputs}
+ respondingRequestIds={runtime.respondingRequestIds}
+ answers={runtime.pendingUserInputAnswers}
+ questionIndex={runtime.pendingUserInputQuestionIndex}
+ onToggleOption={runtime.selectPendingUserInputOption}
+ onSelectSingleOption={runtime.selectPendingUserInputOption}
+ onAdvance={() => {
+ void runtime.advancePendingUserInput();
+ }}
+ />
+ </div>
+ </div>
+ ) : null}
{delegations.map((delegation) => (
<DelegationCard
key={delegation.delegationId}
@@ -418,19 +490,8 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
approvalState.respond(pendingApproval.requestId, decision)
}
/>
- ) : pendingUserInput ? (
- <BotUserInputPrompt
- pendingUserInputs={runtime.pendingUserInputs}
- respondingRequestIds={runtime.respondingRequestIds}
- answers={runtime.pendingUserInputAnswers}
- questionIndex={runtime.pendingUserInputQuestionIndex}
- onToggleOption={runtime.selectPendingUserInputOption}
- onSelectSingleOption={runtime.selectPendingUserInputOption}
- onAdvance={runtime.advancePendingUserInput}
- />
) : null
}
- {...(pendingUserInput ? { placeholder: "Write a custom answer..." } : {})}
disabled={
pendingApproval !== null ||
runtime.respondingRequestIds.length > 0 ||
diff --git a/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
index 7dd293323..839ff0e55 100644
--- a/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
+++ b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
@@ -1,10 +1,16 @@
import type { ReactElement } from "react";
import {
AkeruDelegationRecord,
+ ApprovalRequestId,
BotId,
EnvironmentId,
+ EventId,
+ MessageId,
ThreadId,
+ TurnId,
+ type OrchestrationMessage,
type OrchestrationShellSnapshot,
+ type OrchestrationThreadActivity,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -21,6 +27,9 @@ const mocks = vi.hoisted(() => ({
snapshot: null as OrchestrationShellSnapshot | null,
bots: [] as Bot[],
groups: [] as Group[],
+ activities: [] as OrchestrationThreadActivity[],
+ messages: [] as OrchestrationMessage[],
+ pendingUserInputs: [] as PendingUserInput[],
groupPendingUserInputs: [] as PendingUserInput[],
}));
@@ -66,6 +75,9 @@ vi.mock("../../state/bots", () => ({
vi.mock("../../state/environments", () => ({
usePrimaryEnvironmentId: () => EnvironmentId.make("environment-1"),
}));
+vi.mock("../../state/entities", () => ({
+ useThreadActivities: () => mocks.activities,
+}));
vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: { inbox: [] } }) }));
vi.mock("../../state/server", () => ({
primaryServerProvidersAtom: mocks.providersAtom,
@@ -96,15 +108,15 @@ vi.mock("./useBotThreadRuntime", () => ({
useBotThreadRuntime: () => ({
sending: false,
respondingRequestIds: [],
- messages: [],
- error: null,
- latestTurn: null,
- defaultProject: null,
- pendingUserInputs: [],
+ pendingUserInputs: mocks.pendingUserInputs,
pendingUserInputAnswers: {},
pendingUserInputQuestionIndex: 0,
selectPendingUserInputOption: vi.fn(),
advancePendingUserInput: vi.fn(),
+ messages: mocks.messages,
+ error: null,
+ latestTurn: null,
+ defaultProject: null,
botReady: true,
bootstrapped: true,
linkedThreadRef: {
@@ -138,6 +150,8 @@ vi.mock("./useGroupThreadRuntime", () => ({
}));
import { BotThreadLanding } from "./BotThreadLanding";
+import { ComposerPendingUserInputPanel } from "../chat/ComposerPendingUserInputPanel";
+import { PluginSearchResultCard } from "../chat/PluginSearchResultCard";
import { DelegationCard } from "./DelegationCard";
import { GroupThreadLanding } from "./GroupThreadLanding";
import { BotUserInputPrompt } from "./BotUserInputPrompt";
@@ -217,6 +231,9 @@ describe("thread landing delegations", () => {
hooks.reset();
mocks.bots = [parentBot, childBot];
mocks.groups = [group];
+ mocks.activities = [];
+ mocks.messages = [];
+ mocks.pendingUserInputs = [];
mocks.groupPendingUserInputs = [];
mocks.snapshot = {
snapshotSequence: 1,
@@ -243,6 +260,105 @@ describe("thread landing delegations", () => {
expect(card?.props.childBot).toBe(childBot);
});
+ it("renders plugin recommendations inside the bot conversation", () => {
+ const turnId = TurnId.make("turn-plugins");
+ const timestamp = "2026-09-02T20:00:00.000Z";
+ mocks.messages = [
+ {
+ id: MessageId.make("message-user"),
+ role: "user",
+ text: "Can you connect my email?",
+ turnId,
+ streaming: false,
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ },
+ {
+ id: MessageId.make("message-assistant"),
+ role: "assistant",
+ text: "I found Gmail.",
+ turnId,
+ respondingBotId: BotId.make(parentBot.id),
+ streaming: false,
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ },
+ ];
+ mocks.activities = [
+ {
+ id: EventId.make("activity-plugin-search"),
+ tone: "tool",
+ kind: "tool.completed",
+ summary: "SearchPlugins",
+ turnId,
+ createdAt: timestamp,
+ payload: {
+ itemType: "dynamic_tool_call",
+ title: "SearchPlugins",
+ data: {
+ result: {
+ kind: "plugin-search-results",
+ query: "email",
+ total: 1,
+ sources: { directory: "available", composio: "available" },
+ recommendations: [
+ {
+ id: "composio:gmail",
+ source: "composio",
+ name: "Gmail",
+ description: "Read and send email.",
+ action: "connect",
+ logoUrl: "https://logos.composio.dev/api/gmail",
+ },
+ ],
+ },
+ },
+ },
+ },
+ ];
+
+ hooks.beginRender();
+ const card = visitElements(
+ BotThreadLanding({ botId: parentBot.id }),
+ (element) => element.type === PluginSearchResultCard,
+ ) as ReactElement<Parameters<typeof PluginSearchResultCard>[0]> | null;
+
+ expect(card?.props.result.query).toBe("email");
+ expect(card?.props.result.recommendations[0]?.name).toBe("Gmail");
+ });
+
+ it("renders provider questions inside the bot conversation", () => {
+ mocks.pendingUserInputs = [
+ {
+ requestId: ApprovalRequestId.make("question-request"),
+ createdAt: "2026-09-02T20:00:00.000Z",
+ questions: [
+ {
+ id: "snack",
+ header: "Question",
+ question: "If you had to pick a snack right now, which one?",
+ options: [
+ { label: "Chips", description: "Chips" },
+ { label: "Fruit", description: "Fruit" },
+ { label: "Chocolate", description: "Chocolate" },
+ ],
+ multiSelect: false,
+ },
+ ],
+ },
+ ];
+
+ hooks.beginRender();
+ const card = visitElements(
+ BotThreadLanding({ botId: parentBot.id }),
+ (element) => element.type === ComposerPendingUserInputPanel,
+ ) as ReactElement<Parameters<typeof ComposerPendingUserInputPanel>[0]> | null;
+
+ expect(card?.props.pendingUserInputs[0]?.questions[0]?.question).toBe(
+ "If you had to pick a snack right now, which one?",
+ );
+ });
+
it("renders pending provider questions in group threads", () => {
mocks.groupPendingUserInputs = [
{
diff --git a/apps/web/src/components/settings/PluginsSettings.tsx b/apps/web/src/components/settings/PluginsSettings.tsx
index a9a9bf69a..e51e031d5 100644
--- a/apps/web/src/components/settings/PluginsSettings.tsx
+++ b/apps/web/src/components/settings/PluginsSettings.tsx
@@ -4,15 +4,18 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { McpServerId, type EnvironmentId, type McpServer } from "@t3tools/contracts";
-import { PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
+import { ExternalLinkIcon, PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useState } from "react";
import { ensureLocalApi } from "../../localApi";
import { randomUUID } from "../../lib/utils";
-import { usePrimaryEnvironmentId } from "../../state/environments";
+import { serverEnvironment } from "../../state/server";
+import { useEnvironmentQuery } from "../../state/query";
import { environmentMcpServersAtom, mcpServerEnvironment } from "../../state/mcpServers";
import { useAtomCommand } from "../../state/use-atom-command";
+import { useSettingsEnvironmentId } from "../../settingsDialogStore";
import { Button } from "../ui/button";
+import { Badge } from "../ui/badge";
import {
Dialog,
DialogDescription,
@@ -97,6 +100,20 @@ function PluginsSettingsForEnvironment({
const deleteServer = useAtomCommand(mcpServerEnvironment.delete, { reportFailure: false });
const enableServer = useAtomCommand(mcpServerEnvironment.enable, { reportFailure: false });
const disableServer = useAtomCommand(mcpServerEnvironment.disable, { reportFailure: false });
+ const composioStatus = useEnvironmentQuery(
+ serverEnvironment.composioStatus({ environmentId, input: {} }),
+ );
+ const configureComposio = useAtomCommand(serverEnvironment.configureComposio, {
+ reportFailure: false,
+ });
+ const removeComposio = useAtomCommand(serverEnvironment.removeComposio, {
+ reportFailure: false,
+ });
+ const disconnectComposio = useAtomCommand(serverEnvironment.disconnectComposio, {
+ reportFailure: false,
+ });
+ const [composioApiKey, setComposioApiKey] = useState("");
+ const [composioPending, setComposioPending] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [editingServer, setEditingServer] = useState<McpServer | null>(null);
const [draft, setDraft] = useState<McpServerDraft>(EMPTY_DRAFT);
@@ -104,6 +121,51 @@ function PluginsSettingsForEnvironment({
const [pendingServerId, setPendingServerId] = useState<string | null>(null);
const validationError = validateMcpServerDraft(draft);
+ const reportComposioFailure = (
+ title: string,
+ result: Awaited<ReturnType<typeof configureComposio>>,
+ ): boolean => {
+ if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return false;
+ const error = squashAtomCommandFailure(result);
+ toastManager.add({
+ type: "error",
+ title,
+ description: error instanceof Error ? error.message : "The command failed.",
+ });
+ return true;
+ };
+
+ const saveComposio = async () => {
+ const apiKey = composioApiKey.trim();
+ if (!apiKey) return;
+ setComposioPending("key");
+ const result = await configureComposio({ environmentId, input: { apiKey } });
+ setComposioPending(null);
+ if (!reportComposioFailure("Could not connect Composio", result)) {
+ setComposioApiKey("");
+ composioStatus.refresh();
+ }
+ };
+
+ const removeComposioKey = async () => {
+ const confirmed = await ensureLocalApi().dialogs.confirm(
+ "Remove the Composio API key from this environment?",
+ { variant: "destructive" },
+ );
+ if (!confirmed) return;
+ setComposioPending("key");
+ const result = await removeComposio({ environmentId, input: {} });
+ setComposioPending(null);
+ if (!reportComposioFailure("Could not remove Composio", result)) composioStatus.refresh();
+ };
+
+ const disconnectComposioAccount = async (connectionId: string) => {
+ setComposioPending(connectionId);
+ const result = await disconnectComposio({ environmentId, input: { connectionId } });
+ setComposioPending(null);
+ if (!reportComposioFailure("Could not disconnect account", result)) composioStatus.refresh();
+ };
+
const openCreate = () => {
setEditingServer(null);
setDraft(EMPTY_DRAFT);
@@ -194,6 +256,93 @@ function PluginsSettingsForEnvironment({
return (
<SettingsPageContainer>
+ <SettingsSection
+ title="Composio"
+ headerAction={
+ <Badge variant={composioStatus.data?.configured ? "success" : "secondary"}>
+ {composioStatus.data?.configured ? "Connected" : "Not connected"}
+ </Badge>
+ }
+ >
+ <SettingsRow title="API key" description="Stored only on this Akeru Bot server.">
+ <form
+ className="flex items-center gap-2 pt-3"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void saveComposio();
+ }}
+ >
+ <Input
+ aria-label="Composio API key"
+ autoComplete="off"
+ placeholder={
+ composioStatus.data?.configured ? "Enter a new key to replace" : "Composio API key"
+ }
+ spellCheck={false}
+ type="password"
+ value={composioApiKey}
+ onChange={(event) => setComposioApiKey(event.currentTarget.value)}
+ />
+ <Button
+ disabled={!composioApiKey.trim() || composioPending !== null}
+ size="sm"
+ type="submit"
+ >
+ {composioStatus.data?.configured ? "Replace" : "Save"}
+ </Button>
+ {composioStatus.data?.configured ? (
+ <Button
+ disabled={composioPending !== null}
+ size="sm"
+ type="button"
+ variant="outline"
+ onClick={() => void removeComposioKey()}
+ >
+ Remove
+ </Button>
+ ) : null}
+ </form>
+ <Button
+ className="mt-2 px-0"
+ size="sm"
+ type="button"
+ variant="link"
+ onClick={() =>
+ void ensureLocalApi().shell.openExternal("https://app.composio.dev/settings/api-keys")
+ }
+ >
+ Create a Composio API key
+ <ExternalLinkIcon className="size-3.5" />
+ </Button>
+ </SettingsRow>
+ {(composioStatus.data?.connections ?? []).length === 0 ? (
+ <SettingsRow
+ title="Connected accounts"
+ description="Connect Gmail or another app from Plugins."
+ status="No accounts"
+ />
+ ) : null}
+ {(composioStatus.data?.connections ?? []).map((connection) => (
+ <SettingsRow
+ key={connection.id}
+ title={connection.alias ?? connection.toolkitSlug}
+ description={`${connection.toolkitSlug === "gmail" ? "Gmail" : connection.toolkitSlug} account`}
+ status={connection.status}
+ control={
+ <Button
+ aria-label={`Disconnect ${connection.alias ?? connection.toolkitSlug}`}
+ disabled={composioPending !== null}
+ size="sm"
+ variant="outline"
+ onClick={() => void disconnectComposioAccount(connection.id)}
+ >
+ Disconnect
+ </Button>
+ }
+ />
+ ))}
+ </SettingsSection>
+
<SettingsSection
title="MCP servers"
headerAction={
@@ -337,7 +486,7 @@ function PluginsSettingsForEnvironment({
}
export function PluginsSettingsPanel() {
- const environmentId = usePrimaryEnvironmentId();
+ const environmentId = useSettingsEnvironmentId();
if (environmentId === null) {
return (
<SettingsPageContainer>
diff --git a/apps/web/src/components/settings/SettingsDialog.tsx b/apps/web/src/components/settings/SettingsDialog.tsx
index 2965b5ebd..a90585bd7 100644
--- a/apps/web/src/components/settings/SettingsDialog.tsx
+++ b/apps/web/src/components/settings/SettingsDialog.tsx
@@ -35,6 +35,9 @@ const ProvidersPanel = lazy(async () => ({
const BrowserSettingsPanel = lazy(async () => ({
default: (await import("./BrowserSettings")).BrowserSettingsPanel,
}));
+const PluginsSettingsPanel = lazy(async () => ({
+ default: (await import("./PluginsSettings")).PluginsSettingsPanel,
+}));
const BotChannelsSettingsPanel = lazy(async () => ({
default: (await import("./BotChannelsSettings")).BotChannelsSettingsPanel,
}));
@@ -66,6 +69,7 @@ const SECTION_PANELS: Readonly<Record<SettingsSection, ComponentType>> = {
appearance: AppearanceSettingsPanel,
providers: ProvidersPanel,
browser: BrowserSettingsPanel,
+ plugins: PluginsSettingsPanel,
channels: BotChannelsSettingsPanel,
sandbox: SandboxSettingsPanel,
voice: VoiceSettingsPanel,
@@ -87,6 +91,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
{ section: "providers", label: "Providers", icon: BotIcon },
{ section: "channels", label: "Bot channels", icon: Message01Icon },
{ section: "browser", label: "Browser", icon: BrowserIcon },
+ { section: "plugins", label: "Plugins", icon: Link02Icon },
{ section: "sandbox", label: "Sandbox", icon: HardDriveIcon },
{ section: "voice", label: "Voice", icon: CallIcon },
{ section: "privacy", label: "Privacy", icon: SecurityCheckIcon },
diff --git a/apps/web/src/pluginsDialogStore.test.ts b/apps/web/src/pluginsDialogStore.test.ts
index a3436ff08..73de2c9fe 100644
--- a/apps/web/src/pluginsDialogStore.test.ts
+++ b/apps/web/src/pluginsDialogStore.test.ts
@@ -17,6 +17,15 @@ describe("plugins dialog store", () => {
expect(usePluginsDialogStore.getState().open).toBe(false);
});
+ it("opens with a search from an inline recommendation", () => {
+ openPlugins("Gmail");
+
+ expect(usePluginsDialogStore.getState()).toMatchObject({
+ open: true,
+ requestedQuery: "Gmail",
+ });
+ });
+
it("recognizes the old Settings plugins path", () => {
expect(isLegacyPluginsPath("/settings/plugins")).toBe(true);
expect(isLegacyPluginsPath("/settings/providers")).toBe(false);
diff --git a/apps/web/src/pluginsDialogStore.ts b/apps/web/src/pluginsDialogStore.ts
index 54cdeedba..2de25166d 100644
--- a/apps/web/src/pluginsDialogStore.ts
+++ b/apps/web/src/pluginsDialogStore.ts
@@ -2,18 +2,20 @@ import { create } from "zustand";
interface PluginsDialogState {
readonly open: boolean;
- readonly openPlugins: () => void;
+ readonly requestedQuery: string | null;
+ readonly openPlugins: (query?: string) => void;
readonly closePlugins: () => void;
}
export const usePluginsDialogStore = create<PluginsDialogState>((set) => ({
open: false,
- openPlugins: () => set({ open: true }),
- closePlugins: () => set({ open: false }),
+ requestedQuery: null,
+ openPlugins: (query) => set({ open: true, requestedQuery: query?.trim() || null }),
+ closePlugins: () => set({ open: false, requestedQuery: null }),
}));
-export function openPlugins(): void {
- usePluginsDialogStore.getState().openPlugins();
+export function openPlugins(query?: string): void {
+ usePluginsDialogStore.getState().openPlugins(query);
}
export function closePlugins(): void {
diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts
index 5d331227d..970beaa88 100644
--- a/apps/web/src/session-logic.test.ts
+++ b/apps/web/src/session-logic.test.ts
@@ -1269,6 +1269,39 @@ describe("deriveWorkLogEntries", () => {
expect(entry?.toolData).toEqual(item);
});
+ it("preserves plugin search results for inline recommendations", () => {
+ const result = {
+ kind: "plugin-search-results",
+ query: "email",
+ total: 1,
+ sources: { directory: "available", composio: "available" },
+ recommendations: [
+ {
+ id: "composio:gmail",
+ source: "composio",
+ name: "Gmail",
+ description: "Read and send email.",
+ action: "connect",
+ logoUrl: "https://logos.composio.dev/api/gmail",
+ },
+ ],
+ };
+ const [entry] = deriveWorkLogEntries([
+ makeActivity({
+ id: "plugin-search-done",
+ kind: "tool.completed",
+ summary: "SearchPlugins",
+ payload: {
+ itemType: "dynamic_tool_call",
+ title: "SearchPlugins",
+ data: { result },
+ },
+ }),
+ ]);
+
+ expect(entry?.toolData).toEqual(result);
+ });
+
it("keeps MCP payloads while collapsing lifecycle updates", () => {
const item = {
type: "mcpToolCall",
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index 940fa5c41..3059994e4 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -3,6 +3,7 @@ import * as Arr from "effect/Array";
import * as Schema from "effect/Schema";
import { isBackgroundTaskActivity } from "@t3tools/client-runtime/state/subagentRuntime";
import {
+ AkeruPluginSearchResult,
ApprovalRequestId,
isToolLifecycleItemType,
type OrchestrationLatestTurn,
@@ -122,6 +123,7 @@ const derivedWorkLogEntryByActivity = new WeakMap<
OrchestrationThreadActivity,
DerivedWorkLogEntry
>();
+const isPluginSearchResult = Schema.is(AkeruPluginSearchResult);
export interface PendingApproval {
requestId: ApprovalRequestId;
@@ -203,6 +205,12 @@ export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
}
+export function pluginSearchResultForWorkEntry(
+ entry: WorkLogEntry,
+): AkeruPluginSearchResult | null {
+ return isPluginSearchResult(entry.toolData) ? entry.toolData : null;
+}
+
/** Heuristic: providers often emit successful lifecycle status while error text lives in `detail` / `command`. */
function toolDetailTextLooksLikeFailure(text: string): boolean {
const t = text.toLowerCase();
@@ -1001,6 +1009,11 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
if (data?.item !== undefined) {
entry.toolData = data.item;
}
+ } else if (itemType === "dynamic_tool_call") {
+ const data = asRecord(payload?.data);
+ if (isPluginSearchResult(data?.result)) {
+ entry.toolData = data.result;
+ }
}
if (itemType) {
entry.itemType = itemType;
diff --git a/apps/web/src/settingsDialogStore.test.ts b/apps/web/src/settingsDialogStore.test.ts
index 9c17b3ce7..949da7a4e 100644
--- a/apps/web/src/settingsDialogStore.test.ts
+++ b/apps/web/src/settingsDialogStore.test.ts
@@ -72,6 +72,7 @@ describe("legacy settings deep links", () => {
expect(settingsSectionFromPathname("/settings/inbox")).toBe("inbox");
expect(settingsSectionFromPathname("/settings/voice")).toBe("voice");
expect(settingsSectionFromPathname("/settings/browser")).toBe("browser");
+ expect(settingsSectionFromPathname("/settings/plugins")).toBe("plugins");
expect(settingsSectionFromPathname("/settings/channels")).toBe("channels");
expect(settingsSectionFromPathname("/settings/bots")).toBe("channels");
expect(settingsSectionFromPathname("/settings/sandbox")).toBe("sandbox");
diff --git a/apps/web/src/settingsDialogStore.ts b/apps/web/src/settingsDialogStore.ts
index 0e1843db2..332d4b3d4 100644
--- a/apps/web/src/settingsDialogStore.ts
+++ b/apps/web/src/settingsDialogStore.ts
@@ -18,6 +18,7 @@ export const SETTINGS_SECTIONS = [
"appearance",
"providers",
"browser",
+ "plugins",
"channels",
"sandbox",
"voice",
diff --git a/docs/internals/providers.md b/docs/internals/providers.md
index 5b9b8dd87..48c3b4592 100644
--- a/docs/internals/providers.md
+++ b/docs/internals/providers.md
@@ -60,6 +60,25 @@ the active runtime and starts the selected provider without reusing an incompati
bridge is not the Codex turn path, and AgentController never falls back to the legacy Codex loop when
a Mastra session is absent.
+## Composio runtime
+
+Composio is an integration provider. Its toolkits appear as named plugins such as Gmail, but Akeru
+does not create one durable MCP server for every toolkit. `ComposioService` stores the user-provided
+API key in `ServerSecretStore` and creates one transient Composio MCP session for each Akeru thread.
+
+The session includes only toolkits with active connected accounts. It enables Composio's search and
+connection tools, so providers discover tool schemas when they need them. Multi-account mode requires
+an explicit account choice when a toolkit has more than one account.
+
+The MCP session URL and `x-api-key` header never enter orchestration events or MCP registry records.
+`McpServerConfig` keeps headers in a runtime-only sidecar and adds them at each provider adapter
+boundary. A change to the connected-account set invalidates the thread cache. The next turn gets a new
+session URL and restarts the provider session through the existing MCP configuration check.
+
+Akeru's approval middleware still controls tool execution. Composio handles hosted account sign-in,
+but it does not replace Akeru's approval rules for send, delete, account-wide, or unknown mutating
+actions.
+
`BotEngine.provider` stores the selected provider instance ID. AgentController keeps that instance
when it creates a runtime session, so selecting a model keeps the subscription and custom instance
that supplied it. Runtime ingestion reads the merged Mastra and adapter event stream once.
diff --git a/docs/user/plugins.md b/docs/user/plugins.md
index 2e900a03e..4fd328257 100644
--- a/docs/user/plugins.md
+++ b/docs/user/plugins.md
@@ -29,6 +29,22 @@ removed from the public directory stays under **Installed** until you remove it.
Akeru enables a new plugin for every bot by default. Open the bot's **Tools** setting to disable it
for that bot. Changing the bot's provider starts a fresh provider session with the same enabled tools.
+## Composio integrations
+
+Gmail appears as a normal plugin with a **Composio** provider badge. Select **Connect**, then enter a
+Composio API key. Akeru opens Composio's hosted sign-in page for the Gmail account.
+
+Get a key from [Composio API keys](https://app.composio.dev/settings/api-keys). You can also save or
+replace the key under **Settings > Plugins**. Akeru stores the key on the environment server, not in
+the plugin catalog or MCP registry.
+
+Connect more than one Gmail account when you need separate work and personal accounts. Manage each
+account under **Settings > Plugins**. The agent asks you to select an account when a tool call could
+use more than one.
+
+Composio tools work in threads opened from web, desktop, or mobile after an environment has a key and
+at least one connected account. Configure accounts from the web or desktop client.
+
## Custom MCP servers
Use **Add server** under **Custom MCP servers** when a connector is not in the directory. Installed
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index 2f6c7c7b2..9f10387d0 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -740,6 +740,16 @@ export function createServerEnvironmentAtoms<R, E>(
tag: WS_METHODS.subscriptionAuthList,
staleTimeMs: 5_000,
}),
+ composioStatus: createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: "environment-data:server:composio-status",
+ tag: WS_METHODS.composioGetStatus,
+ staleTimeMs: 2_000,
+ }),
+ composioToolkits: createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: "environment-data:server:composio-toolkits",
+ tag: WS_METHODS.composioSearchToolkits,
+ staleTimeMs: 30_000,
+ }),
voiceCall: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:server:voice-call",
tag: WS_METHODS.voiceCallGet,
@@ -787,6 +797,22 @@ export function createServerEnvironmentAtoms<R, E>(
scheduler: configScheduler,
concurrency: configConcurrency,
}),
+ configureComposio: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:composio-configure",
+ tag: WS_METHODS.composioConfigure,
+ }),
+ removeComposio: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:composio-remove",
+ tag: WS_METHODS.composioRemove,
+ }),
+ authorizeComposio: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:composio-authorize",
+ tag: WS_METHODS.composioAuthorize,
+ }),
+ disconnectComposio: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:composio-disconnect",
+ tag: WS_METHODS.composioDisconnect,
+ }),
startSubscriptionAuth: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:subscription-auth:start",
tag: WS_METHODS.subscriptionAuthStart,
diff --git a/packages/contracts/src/akeruTools.ts b/packages/contracts/src/akeruTools.ts
index 77f183e1a..0a01cf28c 100644
--- a/packages/contracts/src/akeruTools.ts
+++ b/packages/contracts/src/akeruTools.ts
@@ -23,6 +23,29 @@ export const AKERU_PATH_MAX_CHARS = 512;
export const AkeruAwaitHandleId = TrimmedNonEmptyString.pipe(Schema.brand("AkeruAwaitHandleId"));
export type AkeruAwaitHandleId = typeof AkeruAwaitHandleId.Type;
+export const AkeruPluginRecommendation = Schema.Struct({
+ id: TrimmedNonEmptyString,
+ source: Schema.Literals(["directory", "composio"]),
+ name: TrimmedNonEmptyString,
+ description: Schema.String,
+ category: Schema.optional(TrimmedNonEmptyString),
+ logoUrl: Schema.optional(TrimmedNonEmptyString),
+ action: Schema.Literals(["open", "install", "connect", "unavailable"]),
+});
+export type AkeruPluginRecommendation = typeof AkeruPluginRecommendation.Type;
+
+export const AkeruPluginSearchResult = Schema.Struct({
+ kind: Schema.Literal("plugin-search-results"),
+ query: Schema.String,
+ total: NonNegativeInt,
+ sources: Schema.Struct({
+ directory: Schema.Literal("available"),
+ composio: Schema.Literals(["available", "setup-required", "unavailable"]),
+ }),
+ recommendations: Schema.Array(AkeruPluginRecommendation),
+});
+export type AkeruPluginSearchResult = typeof AkeruPluginSearchResult.Type;
+
export const AkeruComputerBoundary = Schema.Literals(["bot-workspace", "user-computer"]);
export type AkeruComputerBoundary = typeof AkeruComputerBoundary.Type;
@@ -315,7 +338,11 @@ export const AKERU_TOOL_CATALOG = [
define("SendToUser", "bot-workspace", "Send a message into the current Akeru thread.", {
approval: "send",
}),
- define("SearchPlugins", "bot-workspace", "Search the curated plugin directory."),
+ define(
+ "SearchPlugins",
+ "bot-workspace",
+ "Search available plugins and connected integration providers when the user needs a capability that is not installed.",
+ ),
define(
"GetPlugin",
"bot-workspace",
diff --git a/packages/contracts/src/composio.ts b/packages/contracts/src/composio.ts
new file mode 100644
index 000000000..50cdff248
--- /dev/null
+++ b/packages/contracts/src/composio.ts
@@ -0,0 +1,74 @@
+import * as Schema from "effect/Schema";
+
+import { TrimmedNonEmptyString } from "./baseSchemas.ts";
+
+export const ComposioConnectionStatus = Schema.Literals([
+ "INITIALIZING",
+ "INITIATED",
+ "ACTIVE",
+ "FAILED",
+ "EXPIRED",
+ "INACTIVE",
+ "REVOKED",
+]);
+export type ComposioConnectionStatus = typeof ComposioConnectionStatus.Type;
+
+export const ComposioConnection = Schema.Struct({
+ id: TrimmedNonEmptyString,
+ toolkitSlug: TrimmedNonEmptyString,
+ status: ComposioConnectionStatus,
+ alias: Schema.optional(TrimmedNonEmptyString),
+});
+export type ComposioConnection = typeof ComposioConnection.Type;
+
+export const ComposioStatus = Schema.Struct({
+ configured: Schema.Boolean,
+ connections: Schema.Array(ComposioConnection),
+});
+export type ComposioStatus = typeof ComposioStatus.Type;
+
+export const ComposioToolkit = Schema.Struct({
+ slug: TrimmedNonEmptyString,
+ name: TrimmedNonEmptyString,
+ description: Schema.optional(Schema.String),
+ logoUrl: Schema.optional(TrimmedNonEmptyString),
+ categories: Schema.Array(TrimmedNonEmptyString),
+ toolsCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
+});
+export type ComposioToolkit = typeof ComposioToolkit.Type;
+
+export const ComposioToolkitSearchInput = Schema.Struct({
+ query: Schema.optional(Schema.String),
+ limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }))),
+});
+export type ComposioToolkitSearchInput = typeof ComposioToolkitSearchInput.Type;
+
+export const ComposioConfigureInput = Schema.Struct({
+ apiKey: TrimmedNonEmptyString,
+});
+export type ComposioConfigureInput = typeof ComposioConfigureInput.Type;
+
+export const ComposioAuthorizeInput = Schema.Struct({
+ toolkitSlug: TrimmedNonEmptyString,
+ alias: Schema.optional(TrimmedNonEmptyString),
+});
+export type ComposioAuthorizeInput = typeof ComposioAuthorizeInput.Type;
+
+export const ComposioAuthorizeResult = Schema.Struct({
+ connectionId: TrimmedNonEmptyString,
+ redirectUrl: TrimmedNonEmptyString,
+});
+export type ComposioAuthorizeResult = typeof ComposioAuthorizeResult.Type;
+
+export const ComposioDisconnectInput = Schema.Struct({
+ connectionId: TrimmedNonEmptyString,
+});
+export type ComposioDisconnectInput = typeof ComposioDisconnectInput.Type;
+
+export class ComposioOperationError extends Schema.TaggedErrorClass<ComposioOperationError>()(
+ "ComposioOperationError",
+ {
+ operation: TrimmedNonEmptyString,
+ message: TrimmedNonEmptyString,
+ },
+) {}
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index 1c403f1ca..67680d7fe 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -19,6 +19,7 @@ export * from "./providerInstance.ts";
export * from "./providerRuntime.ts";
export * from "./model.ts";
export * from "./mcpServer.ts";
+export * from "./composio.ts";
export * from "./keybindings.ts";
export * from "./server.ts";
export * from "./settings.ts";
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 6e11b9464..8c9a48330 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -218,6 +218,16 @@ import {
PortabilityPreviewImportInput,
} from "./portability.ts";
import { RoutineListRunsInput, RoutineListRunsResult, RoutineReadError } from "./routines.ts";
+import {
+ ComposioAuthorizeInput,
+ ComposioAuthorizeResult,
+ ComposioConfigureInput,
+ ComposioDisconnectInput,
+ ComposioOperationError,
+ ComposioStatus,
+ ComposioToolkit,
+ ComposioToolkitSearchInput,
+} from "./composio.ts";
export const WS_METHODS = {
// Project registry methods
@@ -293,6 +303,12 @@ export const WS_METHODS = {
serverRemoveKeybinding: "server.removeKeybinding",
serverGetSettings: "server.getSettings",
serverUpdateSettings: "server.updateSettings",
+ composioGetStatus: "composio.getStatus",
+ composioConfigure: "composio.configure",
+ composioRemove: "composio.remove",
+ composioSearchToolkits: "composio.searchToolkits",
+ composioAuthorize: "composio.authorize",
+ composioDisconnect: "composio.disconnect",
subscriptionAuthList: "subscriptionAuth.list",
subscriptionAuthStart: "subscriptionAuth.start",
subscriptionAuthPoll: "subscriptionAuth.poll",
@@ -417,6 +433,42 @@ export const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSetting
error: Schema.Union([ServerSettingsError, EnvironmentAuthorizationError]),
});
+export const WsComposioGetStatusRpc = Rpc.make(WS_METHODS.composioGetStatus, {
+ payload: Schema.Struct({}),
+ success: ComposioStatus,
+ error: Schema.Union([ComposioOperationError, EnvironmentAuthorizationError]),
+});
+
+export const WsComposioConfigureRpc = Rpc.make(WS_METHODS.composioConfigure, {
+ payload: ComposioConfigureInput,
+ success: ComposioStatus,
+ error: Schema.Union([ComposioOperationError, EnvironmentAuthorizationError]),
+});
+
+export const WsComposioRemoveRpc = Rpc.make(WS_METHODS.composioRemove, {
+ payload: Schema.Struct({}),
+ success: ComposioStatus,
+ error: Schema.Union([ComposioOperationError, EnvironmentAuthorizationError]),
+});
+
+export const WsComposioSearchToolkitsRpc = Rpc.make(WS_METHODS.composioSearchToolkits, {
+ payload: ComposioToolkitSearchInput,
+ success: Schema.Array(ComposioToolkit),
+ error: Schema.Union([ComposioOperationError, EnvironmentAuthorizationError]),
+});
+
+export const WsComposioAuthorizeRpc = Rpc.make(WS_METHODS.composioAuthorize, {
+ payload: ComposioAuthorizeInput,
+ success: ComposioAuthorizeResult,
+ error: Schema.Union([ComposioOperationError, EnvironmentAuthorizationError]),
+});
+
+export const WsComposioDisconnectRpc = Rpc.make(WS_METHODS.composioDisconnect, {
+ payload: ComposioDisconnectInput,
+ success: ComposioStatus,
+ error: Schema.Union([ComposioOperationError, EnvironmentAuthorizationError]),
+});
+
export const WsSubscriptionAuthListRpc = Rpc.make(WS_METHODS.subscriptionAuthList, {
payload: Schema.Struct({}),
success: SubscriptionAuthStatuses,
@@ -1035,6 +1087,12 @@ export const WsRpcGroup = RpcGroup.make(
WsServerRemoveKeybindingRpc,
WsServerGetSettingsRpc,
WsServerUpdateSettingsRpc,
+ WsComposioGetStatusRpc,
+ WsComposioConfigureRpc,
+ WsComposioRemoveRpc,
+ WsComposioSearchToolkitsRpc,
+ WsComposioAuthorizeRpc,
+ WsComposioDisconnectRpc,
WsSubscriptionAuthListRpc,
WsSubscriptionAuthStartRpc,
WsSubscriptionAuthPollRpc,
diff --git a/plugins/catalog.test.ts b/plugins/catalog.test.ts
index 9451353ea..3e34759ef 100644
--- a/plugins/catalog.test.ts
+++ b/plugins/catalog.test.ts
@@ -32,6 +32,7 @@ const EXPECTED_DIRECTORY_IDS = [
"firecrawl",
"framer",
"github",
+ "gmail",
"help-scout",
"hoplite",
"hubspot",
@@ -173,7 +174,7 @@ describe("plugin catalog loader", () => {
const directory = loadDirectoryCatalog();
const catalog = loadCatalog();
expect(directory.map((plugin) => plugin.id).toSorted()).toEqual(EXPECTED_DIRECTORY_IDS);
- expect(new Set(directory.map((plugin) => plugin.id)).size).toBe(53);
+ expect(new Set(directory.map((plugin) => plugin.id)).size).toBe(54);
expect(catalog.map((plugin) => plugin.id)).toEqual(EXPECTED_INSTALLABLE_IDS);
expect(catalog.map((plugin) => `builtin-${plugin.id}`)).toEqual(
EXPECTED_INSTALLABLE_IDS.map((id) => `builtin-${id}`),
@@ -187,6 +188,7 @@ describe("plugin catalog loader", () => {
.map((plugin) => ({ id: plugin.id, rank: plugin.featuredRank })),
).toEqual([
{ id: "context", rank: 1 },
+ { id: "gmail", rank: 1 },
{ id: "zernio", rank: 2 },
{ id: "hoplite", rank: 3 },
]);
@@ -231,7 +233,9 @@ describe("plugin catalog loader", () => {
it("keeps every unverified entry pending with complete approval coverage", () => {
const pending = loadDirectoryCatalog().filter(
- (plugin) => !EXPECTED_INSTALLABLE_IDS.some((id) => id === plugin.id),
+ (plugin) =>
+ plugin.catalogStatus === "approval-pending" ||
+ plugin.catalogStatus === "verification-pending",
);
expect(pending).toHaveLength(48);
expect(pending.filter((plugin) => plugin.catalogStatus === "approval-pending")).toHaveLength(
diff --git a/plugins/catalog.ts b/plugins/catalog.ts
index 46ec9e251..324044624 100644
--- a/plugins/catalog.ts
+++ b/plugins/catalog.ts
@@ -94,10 +94,11 @@ function toPluginDefinition(
manifest: PluginManifest,
assets: AssetModules,
): PluginDirectoryDefinition {
+ const remoteLogoUrl = manifest.logo.url;
const logo = {
- ...manifest.logo,
- src: assetUrl(assets, manifest.id, "logo.svg", manifest.id),
- darkSrc: assetUrl(assets, manifest.id, "logo-dark.svg", manifest.id),
+ provenance: manifest.logo.provenance,
+ src: remoteLogoUrl ?? assetUrl(assets, manifest.id, "logo.svg", manifest.id),
+ darkSrc: remoteLogoUrl ?? assetUrl(assets, manifest.id, "logo-dark.svg", manifest.id),
};
const base = {
...manifest,
diff --git a/plugins/entries/gmail/plugin.json b/plugins/entries/gmail/plugin.json
new file mode 100644
index 000000000..fa1f0bc96
--- /dev/null
+++ b/plugins/entries/gmail/plugin.json
@@ -0,0 +1,43 @@
+{
+ "schemaVersion": 1,
+ "id": "gmail",
+ "name": "Gmail",
+ "description": "Search mail, draft replies, and send messages.",
+ "primaryCategory": "Work",
+ "tags": ["email", "inbox", "google"],
+ "capabilities": ["search email", "read email", "draft email", "send email"],
+ "featuredRank": 1,
+ "publisher": { "name": "Google", "url": "https://gmail.com" },
+ "maintainer": { "name": "Composio", "url": "https://composio.dev" },
+ "documentationUrl": "https://composio.dev/toolkits/gmail",
+ "sourceUrl": "https://composio.dev/toolkits/gmail",
+ "license": "Proprietary",
+ "logo": {
+ "url": "https://logos.composio.dev/api/gmail",
+ "provenance": {
+ "sourceUrl": "https://composio.dev/toolkits/gmail",
+ "license": "Google brand asset served by Composio"
+ }
+ },
+ "platforms": ["web", "desktop", "mobile"],
+ "transport": { "type": "unavailable" },
+ "connection": {
+ "type": "brokered",
+ "broker": { "name": "Composio", "url": "https://composio.dev" }
+ },
+ "authentication": "oauth",
+ "requiredCredentials": [],
+ "setup": ["Connect a Gmail account through Composio."],
+ "permissions": [
+ { "id": "read-email", "description": "Read Gmail messages.", "approval": "read" },
+ { "id": "send-email", "description": "Send Gmail messages.", "approval": "send" },
+ { "id": "delete-email", "description": "Delete Gmail messages.", "approval": "delete" },
+ {
+ "id": "change-email-settings",
+ "description": "Change Gmail settings.",
+ "approval": "account-wide"
+ }
+ ],
+ "approvals": ["send", "delete", "account-wide"],
+ "catalogStatus": "available"
+}
diff --git a/plugins/lifecycle-matrix.test.ts b/plugins/lifecycle-matrix.test.ts
index bb6d96418..d649ff5ea 100644
--- a/plugins/lifecycle-matrix.test.ts
+++ b/plugins/lifecycle-matrix.test.ts
@@ -9,7 +9,7 @@ import {
} from "./catalog";
const EXPECTED_IDS =
- "ahrefs apify apollo asana atlassian attio canva cloudflare coda computer-use context customer-io datadog docusign dropbox exa executor figma firecrawl framer github help-scout hoplite hubspot intercom lemon-squeezy linear mobbin monday netlify notion paddle paper parallel-search paypal pipedrive posthog railway render salesforce semrush sentry sequenzy shopify slack stripe superside tavily typefully vercel webflow zendesk zernio".split(
+ "ahrefs apify apollo asana atlassian attio canva cloudflare coda computer-use context customer-io datadog docusign dropbox exa executor figma firecrawl framer github gmail help-scout hoplite hubspot intercom lemon-squeezy linear mobbin monday netlify notion paddle paper parallel-search paypal pipedrive posthog railway render salesforce semrush sentry sequenzy shopify slack stripe superside tavily typefully vercel webflow zendesk zernio".split(
" ",
);
const INSTALLABLE_IDS = ["context", "hoplite", "exa", "firecrawl", "parallel-search"];
@@ -31,11 +31,16 @@ describe("milestone 13 plugin lifecycle matrix", () => {
.map((plugin) => [plugin.id, plugin.featuredRank]),
).toEqual([
["context", 1],
+ ["gmail", 1],
["zernio", 2],
["hoplite", 3],
]);
- const pending = directory.filter((plugin) => !INSTALLABLE_IDS.includes(plugin.id));
+ const pending = directory.filter(
+ (plugin) =>
+ plugin.catalogStatus === "approval-pending" ||
+ plugin.catalogStatus === "verification-pending",
+ );
expect(pending).toHaveLength(48);
expect(pending.filter((plugin) => plugin.catalogStatus === "approval-pending")).toHaveLength(
16,
diff --git a/plugins/schema.test.ts b/plugins/schema.test.ts
index 8ee9332a0..b2afb8409 100644
--- a/plugins/schema.test.ts
+++ b/plugins/schema.test.ts
@@ -221,4 +221,21 @@ describe("plugin catalog schema", () => {
parsePluginManifest({ ...pending, connection: { type: "approval-pending" } }),
).toThrow("blocker");
});
+
+ it("allows a broker to supply the runtime transport", () => {
+ const brokered = {
+ ...VALID_MANIFEST,
+ transport: { type: "unavailable" },
+ connection: {
+ type: "brokered",
+ broker: { name: "Example Broker", url: "https://broker.example.com" },
+ },
+ } as const;
+
+ expect(parsePluginManifest(brokered)).toMatchObject({
+ transport: { type: "unavailable" },
+ connection: { type: "brokered", broker: { name: "Example Broker" } },
+ catalogStatus: "available",
+ });
+ });
});
diff --git a/plugins/schema.ts b/plugins/schema.ts
index c924b8e2f..aa614f518 100644
--- a/plugins/schema.ts
+++ b/plugins/schema.ts
@@ -17,6 +17,7 @@ interface Party {
}
interface PluginLogoManifest {
+ readonly url?: string;
readonly provenance: { readonly sourceUrl: string; readonly license: string };
}
@@ -181,10 +182,11 @@ function party(value: unknown, path: string): Party {
function logo(value: unknown, path: string): PluginLogoManifest {
const input = object(value, path);
- exactKeys(input, ["provenance"], path);
+ exactKeys(input, ["provenance", "url"], path);
const provenance = object(input.provenance, `${path}.provenance`);
exactKeys(provenance, ["sourceUrl", "license"], `${path}.provenance`);
return {
+ ...(input.url === undefined ? {} : { url: secureUrl(input.url, `${path}.url`) }),
provenance: {
sourceUrl: secureUrl(provenance.sourceUrl, `${path}.provenance.sourceUrl`),
license: nonEmptyString(provenance.license, `${path}.provenance.license`),
@@ -402,13 +404,18 @@ function validateManifest(manifest: PluginManifest): PluginManifest {
}
if (
manifest.transport.type === "unavailable" &&
- manifest.connection.type !== "approval-pending"
+ manifest.connection.type !== "approval-pending" &&
+ manifest.connection.type !== "brokered"
) {
throw new TypeError(
- `Plugin '${manifest.id}' unavailable transport requires an approval blocker.`,
+ `Plugin '${manifest.id}' unavailable transport requires an approval blocker or a broker.`,
);
}
- if (manifest.catalogStatus === "available" && manifest.transport.type === "unavailable") {
+ if (
+ manifest.catalogStatus === "available" &&
+ manifest.transport.type === "unavailable" &&
+ manifest.connection.type !== "brokered"
+ ) {
throw new TypeError(`Plugin '${manifest.id}' cannot be available without a transport recipe.`);
}
if (
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index edbe9e894..f3e0f23f3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -468,6 +468,9 @@ importers:
'@chat-adapter/whatsapp':
specifier: 4.39.0
+ '@composio/core':
+ specifier: 0.18.0
'@daytona/sdk':
specifier: ^0.207.0
@@ -2235,6 +2238,21 @@ packages:
'@cloudflare/[email protected]':
resolution: {integrity: sha512-fKgRSm3sDmOdak1LGWehS4vSPSj7/zeu0NfmE62VPjBMqWgODcOGljYvq6A75sL+7YfY3iGFGb0jVEDYq+hlmw==}
+ '@composio/[email protected]':
+ resolution: {integrity: sha512-MXC5JGRVdiQ4EgLricy9o/mqBa1+1T7wHFZ6Q4ZJkrjzZqOMvxTgy21Zlb5J/1oGkB2bg9UDzpH8PkXCp/D4zA==}
+
+ '@composio/[email protected]':
+ resolution: {integrity: sha512-u8dfSDJV+BYiQYJBxbk6xRI8o8f7O6nb8xE0rJmvC+8zKNJdY/M119R8a30grLh07a6fcLeVFYCJlTRpCjwKyg==}
+ engines: {node: '>=22.22.3'}
+ peerDependencies:
+ zod: '>=3.25.76 <5'
+
+ '@composio/[email protected]':
+ resolution: {integrity: sha512-ZmDksfKZrkJZj6XCgR+AmjsxqvFnfc4XDEQPfJJZMYxIqhE3MBZ2KimLuPT+YGahO4h9uzT2EYi9asMF4qR4+g==}
+ engines: {node: '>=22.22.3'}
+ peerDependencies:
+ zod: '>=3.25.76 <5'
+
'@connectrpc/[email protected]':
resolution: {integrity: sha512-1tfaK85MU+gJjwwmL31d2rzdf0XCYX99chZf63uG89SGBUd4XuZ4ZzhGo2u79TPXOE6nLIZQ2okrpyey42PYdg==}
peerDependencies:
@@ -9414,6 +9432,9 @@ packages:
resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-JoCsyGITdYPM+pUbeMQ4IiEuQ4wjPdeWORlG7n644isewbcxiQIr+9gmF5k7UabTP/jLBRkbgydEamR7JZBKHA==}
+
resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
engines: {node: '>=8'}
@@ -10872,6 +10893,30 @@ packages:
zod:
optional: true
+ resolution: {integrity: sha512-/2g9JzdnXNcjX1W/UlSNu+OdSFDAaAVt0n9Onom0kPenH54o59G2WrX/xjTnr26UHNSh6hxcAf58doGYRme2rw==}
+ engines: {node: '>=22.0.0'}
+ peerDependencies:
+ '@aws-sdk/credential-provider-node': '>=3.972.0 <4'
+ '@smithy/hash-node': '>=4.3.0 <5'
+ '@smithy/signature-v4': '>=5.4.0 <6'
+ undici: '>=5 <9'
+ ws: ^8.21.0
+ zod: ^3.25 || ^4.0
+ peerDependenciesMeta:
+ '@aws-sdk/credential-provider-node':
+ optional: true
+ '@smithy/hash-node':
+ optional: true
+ '@smithy/signature-v4':
+ optional: true
+ undici:
+ optional: true
+ ws:
+ optional: true
+ zod:
+ optional: true
+
resolution: {integrity: sha512-l7RarRHxlEZYjMLd/PR0slfMVse2/vvIAGm75/F7J6MlQ8/b9uUQmUF2kCPrQhJqMXSxmYWObVgeYXbFYzZR+A==}
@@ -11388,6 +11433,9 @@ packages:
resolution: {integrity: sha512-IoM8YF/jY0hiugFo/wOWqfmarlE6J0wc6fDK1PhftMk7MGhVZl88sZimmqBBFomLOCSmcCCpsfj7wXASCpvK9A==}
+ resolution: {integrity: sha512-wShJPfCS/kYkCBVzVW67wa9cnQIgHTszEK2XHNrFkOgGruuGw081aERAxfRjfdFU+WcIt8x6dvbwkTW4iZuQ8Q==}
+
resolution: {integrity: sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==}
@@ -12592,6 +12640,9 @@ packages:
resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==}
+ resolution: {integrity: sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==}
+
resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==}
engines: {node: '>=10'}
@@ -15061,6 +15112,31 @@ snapshots:
'@cloudflare/[email protected]': {}
+ '@composio/[email protected]': {}
+
+ dependencies:
+ '@composio/client': 0.1.0-alpha.76
+ '@composio/json-schema-to-zod': 0.3.1([email protected])
+ '@types/json-schema': 7.0.15
+ is-fs-case-sensitive: 2.0.0
+ picocolors: 1.1.1
+ pusher-js: 8.6.0
+ semver: 7.8.5
+ undici: 7.29.0
+ zod: 4.4.3
+ zod-to-json-schema: 3.25.2([email protected])
+ transitivePeerDependencies:
+ - '@aws-sdk/credential-provider-node'
+ - '@smithy/hash-node'
+ - '@smithy/signature-v4'
+ - ws
+
+ dependencies:
+ zod: 4.4.3
+
'@connectrpc/[email protected](@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))':
dependencies:
'@bufbuild/protobuf': 2.14.0
@@ -23609,6 +23685,8 @@ snapshots:
+
@@ -25253,6 +25331,14 @@ snapshots:
transitivePeerDependencies:
- encoding
+ optionalDependencies:
+ '@aws-sdk/credential-provider-node': 3.972.81
+ '@smithy/signature-v4': 5.7.3
+ undici: 7.29.0
+ zod: 4.4.3
+
dependencies:
openapi-typescript-helpers: 0.0.15
@@ -25835,6 +25921,10 @@ snapshots:
+ dependencies:
+ tweetnacl: 1.0.3
+
dependencies:
tslib: 2.8.1
@@ -27503,6 +27593,8 @@ snapshots:
safe-buffer: 5.2.1
optional: true
+
optional: true
diff --git a/scripts/validate-plugin-catalog.test.ts b/scripts/validate-plugin-catalog.test.ts
index 3ee9d12b1..a853d5d20 100644
--- a/scripts/validate-plugin-catalog.test.ts
+++ b/scripts/validate-plugin-catalog.test.ts
@@ -29,7 +29,7 @@ afterEach(() => {
describe("plugin catalog validation", () => {
it("validates the live plugin directory", () => {
- expect(validatePluginCatalog()).toHaveLength(53);
+ expect(validatePluginCatalog()).toHaveLength(54);
});
it("validates isolated manifests and official local assets", () => {
@@ -91,4 +91,15 @@ describe("plugin catalog validation", () => {
NodeFS.writeFileSync(new URL("catalog.generated.json", entry), "[]");
expect(() => validatePluginCatalog(root)).toThrow("has undeclared files");
});
+
+ it("accepts a remote logo without local assets and still rejects stray files", () => {
+ const root = fixtureRoot();
+ copyEntry("gmail", root);
+ expect(validatePluginCatalog(root).map((entry) => entry.directory)).toEqual(["gmail"]);
+
+ const strayRoot = fixtureRoot();
+ const stray = copyEntry("gmail", strayRoot);
+ NodeFS.writeFileSync(new URL("logo.svg", stray), "<svg></svg>");
+ expect(() => validatePluginCatalog(strayRoot)).toThrow("has undeclared files");
+ });
});
diff --git a/scripts/validate-plugin-catalog.ts b/scripts/validate-plugin-catalog.ts
index 1383cf7d9..c78d0693a 100644
--- a/scripts/validate-plugin-catalog.ts
+++ b/scripts/validate-plugin-catalog.ts
@@ -74,7 +74,8 @@ export function validatePluginCatalog(
if (ids.has(manifest.id)) throw new TypeError(`Duplicate plugin id '${manifest.id}'.`);
ids.add(manifest.id);
- const logos = ["logo.svg", "logo-dark.svg"];
+ // A manifest with a remote logo URL ships no local artwork.
+ const logos = manifest.logo.url ? [] : ["logo.svg", "logo-dark.svg"];
for (const filename of logos) validateLogo(directoryUrl, directory, filename, hashes);
const expectedFiles = new Set(["plugin.json", ...logos]);
const unexpected = NodeFS.readdirSync(directoryUrl).filter((file) => !expectedFiles.has(file));