🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(connector): agent-scoped connectors — backend + profile UI (LOBE-10787) (#16971)
LiJiane904961ec70f
diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.tsindex d70ecb9aa54..20f2c8dfd69 100644--- a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts+++ b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts@@ -177,6 +177,7 @@ describe('connectorRouter.create — sourceType handling on existing rows', () =vi.clearAllMocks();connectorModelMock = {create: vi.fn().mockResolvedValue({ id: 'conn-new' }),+ findScopedByIdentifier: vi.fn().mockResolvedValue(null),queryByIdentifiers: vi.fn().mockResolvedValue([]),update: vi.fn().mockResolvedValue(undefined),};@@ -205,9 +206,11 @@ describe('connectorRouter.create — sourceType handling on existing rows', () =it('promotes an existing marketplace row to custom when the input asks for it', async () => {// Pre-existing half-baked row from the old syncPluginTools code path.- connectorModelMock.queryByIdentifiers.mockResolvedValueOnce([- { id: 'conn-existing', identifier: 'legacy-mcp', sourceType: 'marketplace' },- ]);+ connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce({+ id: 'conn-existing',+ identifier: 'legacy-mcp',+ sourceType: 'marketplace',+ });const result = await caller().create(baseCustomInput);@@ -224,9 +227,11 @@ describe('connectorRouter.create — sourceType handling on existing rows', () =// A normal re-save / re-authorize of an already-custom connector — the// update still includes sourceType, but the value stays the same. This// documents that the promotion path is safe for the no-op case.- connectorModelMock.queryByIdentifiers.mockResolvedValueOnce([- { id: 'conn-existing', identifier: 'legacy-mcp', sourceType: 'custom' },- ]);+ connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce({+ id: 'conn-existing',+ identifier: 'legacy-mcp',+ sourceType: 'custom',+ });await caller().create(baseCustomInput);@@ -237,7 +242,7 @@ describe('connectorRouter.create — sourceType handling on existing rows', () =});it('still creates a fresh row when no existing identifier matches', async () => {- connectorModelMock.queryByIdentifiers.mockResolvedValueOnce([]);+ connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce(null);const result = await caller().create(baseCustomInput);diff --git a/apps/server/src/routers/lambda/composio.test.ts b/apps/server/src/routers/lambda/composio.test.tsindex 538c00635c1..7e6250cef66 100644--- a/apps/server/src/routers/lambda/composio.test.ts+++ b/apps/server/src/routers/lambda/composio.test.ts@@ -11,7 +11,7 @@ const mocks = vi.hoisted(() => ({connectedAccountsLink: vi.fn(),connectorCreate: vi.fn(),connectorDelete: vi.fn(),- connectorQueryByIdentifiers: vi.fn(),+ connectorFindScopedByIdentifier: vi.fn(),connectorToolDeleteToolsNotIn: vi.fn(),connectorToolUpsertMany: vi.fn(),connectorUpdate: vi.fn(),@@ -44,7 +44,7 @@ vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(() => ({create: mocks.connectorCreate,delete: mocks.connectorDelete,- queryByIdentifiers: mocks.connectorQueryByIdentifiers,+ findScopedByIdentifier: mocks.connectorFindScopedByIdentifier,update: mocks.connectorUpdate,})),}));@@ -68,7 +68,7 @@ const caller = () => composioRouter.createCaller({ userId: 'user-1' } as any);beforeEach(() => {vi.clearAllMocks();- mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.connectorFindScopedByIdentifier.mockResolvedValue(null);mocks.connectorCreate.mockResolvedValue({ id: 'conn-new' });mocks.pluginFindById.mockResolvedValue(undefined);});@@ -113,7 +113,7 @@ describe('composioRouter.updateComposioPlugin dual-write', () => {};it('creates the connector projection (ACTIVE) + tools when none exists', async () => {- mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.connectorFindScopedByIdentifier.mockResolvedValue(null);const res = await caller().updateComposioPlugin(input);@@ -131,7 +131,7 @@ describe('composioRouter.updateComposioPlugin dual-write', () => {});it('updates an existing connector projection instead of duplicating it', async () => {- mocks.connectorQueryByIdentifiers.mockResolvedValue([{ id: 'conn-existing' }]);+ mocks.connectorFindScopedByIdentifier.mockResolvedValue({ id: 'conn-existing' });await caller().updateComposioPlugin(input);@@ -152,7 +152,7 @@ describe('composioRouter.updateComposioPlugin dual-write', () => {});it('prunes all connector tools when the refreshed list is empty', async () => {- mocks.connectorQueryByIdentifiers.mockResolvedValue([{ id: 'conn-existing' }]);+ mocks.connectorFindScopedByIdentifier.mockResolvedValue({ id: 'conn-existing' });await caller().updateComposioPlugin({ ...input, tools: [] });@@ -164,7 +164,7 @@ describe('composioRouter.updateComposioPlugin dual-write', () => {describe('composioRouter delete paths clean up the connector projection', () => {it('removeComposioPlugin deletes the connector row when present', async () => {- mocks.connectorQueryByIdentifiers.mockResolvedValue([{ id: 'conn-existing' }]);+ mocks.connectorFindScopedByIdentifier.mockResolvedValue({ id: 'conn-existing' });await caller().removeComposioPlugin({ identifier: 'gmail' });@@ -174,7 +174,7 @@ describe('composioRouter delete paths clean up the connector projection', () =>it('deleteConnection deletes both plugin and connector', async () => {mocks.connectedAccountsDelete.mockResolvedValue(undefined);- mocks.connectorQueryByIdentifiers.mockResolvedValue([{ id: 'conn-existing' }]);+ mocks.connectorFindScopedByIdentifier.mockResolvedValue({ id: 'conn-existing' });await caller().deleteConnection({ connectedAccountId: 'ca-1', identifier: 'gmail' });@@ -183,7 +183,7 @@ describe('composioRouter delete paths clean up the connector projection', () =>});it('does not call connector delete when no projection exists', async () => {- mocks.connectorQueryByIdentifiers.mockResolvedValue([]);+ mocks.connectorFindScopedByIdentifier.mockResolvedValue(null);await caller().removeComposioPlugin({ identifier: 'gmail' });diff --git a/apps/server/src/routers/lambda/composio.ts b/apps/server/src/routers/lambda/composio.tsindex 9fbaf5fa041..6457e3d10a9 100644--- a/apps/server/src/routers/lambda/composio.ts+++ b/apps/server/src/routers/lambda/composio.ts@@ -1,8 +1,10 @@+import type { LobeChatDatabase } from '@lobechat/database';import { type ToolManifest } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';import { getServerComposioAuthConfigId } from '@/config/composio';+import { AgentModel } from '@/database/models/agent';import { ConnectorModel } from '@/database/models/connector';import { ConnectorToolModel } from '@/database/models/connectorTool';import { PluginModel } from '@/database/models/plugin';@@ -48,6 +50,14 @@ async function upsertComposioConnector(connectorModel: ConnectorModel,connectorToolModel: ConnectorToolModel,params: {+ /**+ * When set, the Composio connection is bound to this agent: the account+ * (`metadata.composio.connectedAccountId`) lands on the agent-scoped+ * connector row and shadows the base one at runtime (Agent > Personal). The+ * legacy `user_installed_plugins` projection can't carry an agent scope, so+ * agent connections skip it (the runtime resolves off metadata).+ */+ agentId?: string;composio: ComposioConnectorMetadata;identifier: string;label: string;@@ -76,7 +86,9 @@ async function upsertComposioConnector(? ConnectorStatus.error: ConnectorStatus.disconnected;- const [existing] = await connectorModel.queryByIdentifiers([params.identifier]);+ // Exact-scope idempotency: an agent connection updates/creates the agent's own+ // row, a personal connection the base row — never crossing scopes.+ const existing = await connectorModel.findScopedByIdentifier(params.identifier, params.agentId);let connectorId: string;if (existing) {await connectorModel.update(existing.id, {@@ -88,6 +100,7 @@ async function upsertComposioConnector(connectorId = existing.id;} else {const created = await connectorModel.create({+ agentId: params.agentId ?? null,identifier: params.identifier,isEnabled: true,metadata,@@ -125,24 +138,46 @@ async function upsertComposioConnector(async function deleteComposioConnector(connectorModel: ConnectorModel,identifier: string,+ agentId?: string,): Promise<void> {- const [existing] = await connectorModel.queryByIdentifiers([identifier]);+ const existing = await connectorModel.findScopedByIdentifier(identifier, agentId);if (existing) await connectorModel.delete(existing.id);}+/**+ * Guard: the caller must OWN (have created) the agent before a Composio account+ * is bound to it. Uses `existsOwnedById` (creator-only) rather than the+ * visibility-aware `existsById`, so a member who can merely see a shared public+ * agent can't attach their account to it.+ */+async function assertCanEditAgent(+ db: LobeChatDatabase,+ userId: string,+ agentId: string,+): Promise<void> {+ const agentModel = new AgentModel(db, userId);+ if (!(await agentModel.existsOwnedById(agentId))) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });+ }+}+export const composioRouter = router({createConnection: composioProcedure.input(z.object({+ /** Bind the connection to this agent (Agent > Personal). Requires edit rights. */+ agentId: z.string().optional(),appSlug: z.string(),identifier: z.string(),label: z.string(),}),).mutation(async ({ input, ctx }) => {- const { appSlug, identifier, label } = input;+ const { appSlug, identifier, label, agentId } = input;const { userId } = ctx;+ if (agentId) await assertCanEditAgent(ctx.serverDB, userId, agentId);+const callbackUrl = `${process.env.APP_URL || process.env.NEXTAUTH_URL || ''}/api/composio/oauth/callback`;// Prefer a pre-configured auth config (e.g. a custom/white-label config@@ -173,10 +208,17 @@ export const composioRouter = router({// Composio-managed OAuth auth configs no longer support `initiate`; use// `link` (POST /api/v3/connected_accounts/link) to get the redirect URL.+ //+ // `allowMultiple` for agent connections: Composio rejects a second linked+ // account for the same (user entity, auth config) unless this is set. An+ // agent connector is intentionally a *separate* account from the user's+ // (and from other agents'), all under the same Composio user entity but+ // distinguished by connectedAccountId — so agent links must allow multiple.+ // Personal connections keep the default (one account per auth config).const connReq = await (ctx.composioClient.connectedAccounts as any).link(userId,authConfigId,- { callbackUrl },+ { callbackUrl, ...(agentId ? { allowMultiple: true } : {}) },);let rawTools: any[] = [];@@ -210,26 +252,32 @@ export const composioRouter = router({type: 'default',};- await ctx.pluginModel.create({- customParams: {- composio: {- appSlug,- authConfigId,- connectedAccountId: connReq.id,- redirectUrl: connReq.redirectUrl,- status: 'PENDING',+ // Legacy plugin-table projection is personal-only (no agent_id column), so+ // skip it for agent connections — the runtime resolves those off the+ // agent-scoped connector row's metadata instead.+ if (!agentId) {+ await ctx.pluginModel.create({+ customParams: {+ composio: {+ appSlug,+ authConfigId,+ connectedAccountId: connReq.id,+ redirectUrl: connReq.redirectUrl,+ status: 'PENDING',+ },},- },- identifier,- manifest,- source: 'composio',- type: 'plugin',- });+ identifier,+ manifest,+ source: 'composio',+ type: 'plugin',+ });+ }// Dual-write: mirror the (pending) connection into user_connectors so the// runtime can resolve it off metadata once it goes ACTIVE. Tools sync on// updateComposioPlugin; seed them here too when already fetched.await upsertComposioConnector(ctx.connectorModel, ctx.connectorToolModel, {+ agentId,composio: {appSlug,authConfigId,@@ -257,6 +305,7 @@ export const composioRouter = router({deleteConnection: composioProcedure.input(z.object({+ agentId: z.string().optional(),connectedAccountId: z.string(),identifier: z.string(),}),@@ -268,8 +317,10 @@ export const composioRouter = router({console.warn('[Composio] Failed to delete remote connection:', error);}- await ctx.pluginModel.delete(input.identifier);- await deleteComposioConnector(ctx.connectorModel, input.identifier);+ // Agent connections have no plugin-table row; only remove the base plugin+ // projection for personal connections.+ if (!input.agentId) await ctx.pluginModel.delete(input.identifier);+ await deleteComposioConnector(ctx.connectorModel, input.identifier, input.agentId);return { success: true };}),@@ -313,16 +364,18 @@ export const composioRouter = router({}),removeComposioPlugin: composioProcedure- .input(z.object({ identifier: z.string() }))+ .input(z.object({ agentId: z.string().optional(), identifier: z.string() })).mutation(async ({ input, ctx }) => {- await ctx.pluginModel.delete(input.identifier);- await deleteComposioConnector(ctx.connectorModel, input.identifier);+ if (!input.agentId) await ctx.pluginModel.delete(input.identifier);+ await deleteComposioConnector(ctx.connectorModel, input.identifier, input.agentId);return { success: true };}),updateComposioPlugin: composioProcedure.input(z.object({+ /** Bind the connection to this agent (Agent > Personal). Requires edit rights. */+ agentId: z.string().optional(),appSlug: z.string(),authConfigId: z.string(),connectedAccountId: z.string(),@@ -349,8 +402,11 @@ export const composioRouter = router({tools,status,redirectUrl,+ agentId,} = input;+ if (agentId) await assertCanEditAgent(ctx.serverDB, ctx.userId, agentId);+const existingPlugin = await ctx.pluginModel.findById(identifier);const manifest: ToolManifest = {@@ -372,22 +428,27 @@ export const composioRouter = router({composio: { appSlug, authConfigId, connectedAccountId, redirectUrl, status },};- if (existingPlugin) {- await ctx.pluginModel.update(identifier, { customParams, manifest });- } else {- await ctx.pluginModel.create({- customParams,- identifier,- manifest,- source: 'composio',- type: 'plugin',- });+ // Personal-only plugin projection: skip for agent connections (see+ // createConnection). The agent row's metadata is the runtime source.+ if (!agentId) {+ if (existingPlugin) {+ await ctx.pluginModel.update(identifier, { customParams, manifest });+ } else {+ await ctx.pluginModel.create({+ customParams,+ identifier,+ manifest,+ source: 'composio',+ type: 'plugin',+ });+ }}// Dual-write: project the active connection + tool list into the connector// tables so the runtime resolves this Composio server without the plugin// table. `tools` already carries the full manifest from the client.await upsertComposioConnector(ctx.connectorModel, ctx.connectorToolModel, {+ agentId,composio: { appSlug, authConfigId, connectedAccountId, redirectUrl, status },identifier,label,diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 3bfae09dd74..30082d72b3a 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -2,6 +2,7 @@ import { TRPCError } from '@trpc/server';import { z } from 'zod';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { AgentModel } from '@/database/models/agent';import { ConnectorModel } from '@/database/models/connector';import { ConnectorToolModel } from '@/database/models/connectorTool';import { PluginModel } from '@/database/models/plugin';@@ -68,6 +69,13 @@ const connectorCredentialsInputSchema = z.discriminatedUnion('type', []);const createConnectorSchema = z.object({+ /**+ * Bind this connector to a specific agent (Agent > Workspace/Personal). When+ * set, the row is agent-scoped: it only resolves for that agent's runs and+ * holds the agent's own credentials (service-account pattern). The caller must+ * be able to edit the agent. Omit for a normal personal/workspace connector.+ */+ agentId: z.string().optional(),credentials: connectorCredentialsInputSchema.optional(),identifier: z.string().min(1).max(255),isEnabled: z.boolean().optional().default(true),@@ -115,6 +123,28 @@ export const connectorRouter = router({return toolsByConnector;}),+ /**+ * List the connectors bound to a specific agent (agent-scoped rows only). The+ * agent-settings UI uses this to show + manage the agent's own connectors,+ * which the base `list` deliberately excludes.+ */+ listByAgent: connectorProcedure+ .input(z.object({ agentId: z.string() }))+ .query(async ({ input, ctx }) => {+ const connectors = await ctx.connectorModel.queryByAgent(input.agentId);++ return Promise.all(+ connectors.map(async (c) => {+ const tools = await ctx.connectorToolModel.queryByConnector(c.id);+ const { credentials: _credentials, oidcConfig, ...rest } = c;+ const safeOidcConfig = oidcConfig+ ? { ...oidcConfig, clientSecret: undefined }+ : oidcConfig;+ return { ...rest, oidcConfig: safeOidcConfig, tools };+ }),+ );+ }),+/*** Return the connector record with decrypted user-set credentials so the* edit form can pre-fill accurately. Only the connector owner can call this@@ -151,6 +181,19 @@ export const connectorRouter = router({// ── Mutations ─────────────────────────────────────────────────────────────create: connectorProcedure.input(createConnectorSchema).mutation(async ({ input, ctx }) => {+ const { agentId } = input;++ // Agent-scoped connector: the caller must be able to edit the target agent+ // before a credential is bound to it — otherwise a user could attach their+ // account to someone else's agent. Scoped to the caller's user/workspace.+ if (agentId) {+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);+ const canEdit = await agentModel.existsOwnedById(agentId);+ if (!canEdit) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });+ }+ }+const fields = {// The model expects the decrypted JSON string and encrypts it at rest.credentials: input.credentials ? JSON.stringify(input.credentials) : null,@@ -174,7 +217,14 @@ export const connectorRouter = router({// listings (selector filters on sourceType === 'custom'). Safe because the// other callers (`AddConnectorModal`, marketplace bootstrap) always pass// the same sourceType they originally created the row with.- const [existing] = await ctx.connectorModel.queryByIdentifiers([input.identifier]);+ // Idempotent within the EXACT scope (this agent's row, or the base row when+ // no agentId). The exact-scope lookup is critical: creating an agent+ // connector must not update the personal/workspace row of the same+ // identifier, and re-adding the same agent connector updates its own row —+ // enforcing "one connector per identifier per agent" at the app layer (the+ // DB indexes are non-unique so multiple same-identifier rows can coexist+ // across scopes).+ const existing = await ctx.connectorModel.findScopedByIdentifier(input.identifier, agentId);if (existing) {await ctx.connectorModel.update(existing.id, {...fields,@@ -187,6 +237,7 @@ export const connectorRouter = router({return ctx.connectorModel.create({...fields,+ agentId: agentId ?? null,identifier: input.identifier,isEnabled: input.isEnabled ?? true,sourceType: input.sourceType,@@ -194,6 +245,156 @@ export const connectorRouter = router({});}),+ /**+ * Bind an existing connector to an agent (transfer it into the agent scope).+ * The connector then resolves only for that agent's runs and shadows the+ * user's base connector of the same identifier (Agent > Workspace/Personal).+ *+ * Guards: the caller must be able to edit the agent; the agent must not+ * already have a connector for this identifier (one per identifier per agent).+ */+ bindAgent: connectorProcedure+ .input(z.object({ agentId: z.string(), connectorId: z.string().uuid() }))+ .mutation(async ({ input, ctx }) => {+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);+ if (!(await agentModel.existsOwnedById(input.agentId))) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });+ }++ const connector = await ctx.connectorModel.findById(input.connectorId);+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });++ const existingAgentRow = await ctx.connectorModel.findScopedByIdentifier(+ connector.identifier,+ input.agentId,+ );+ if (existingAgentRow && existingAgentRow.id !== connector.id) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: `Agent already has a "${connector.identifier}" connector`,+ });+ }++ await ctx.connectorModel.update(input.connectorId, { agentId: input.agentId });+ return { id: input.connectorId };+ }),++ /**+ * Unbind a connector from its agent, returning it to the personal/workspace+ * scope. Rejected when a base connector of the same identifier already exists,+ * to keep the base scope single-per-identifier — the caller should delete the+ * agent connector instead of demoting it into a collision.+ */+ unbindAgent: connectorProcedure+ .input(z.object({ connectorId: z.string().uuid() }))+ .mutation(async ({ input, ctx }) => {+ const connector = await ctx.connectorModel.findById(input.connectorId);+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });+ if (!connector.agentId) return { id: input.connectorId }; // already base — no-op++ const existingBase = await ctx.connectorModel.findScopedByIdentifier(connector.identifier);+ if (existingBase) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: `A personal "${connector.identifier}" connector already exists; delete the agent connector instead`,+ });+ }++ await ctx.connectorModel.update(input.connectorId, { agentId: null });+ return { id: input.connectorId };+ }),++ /**+ * "Copy user tool": clone a user connector into an independent agent-owned+ * row (own credentials, separately editable). Server-side because the+ * credentials ciphertext never reaches the client (see ConnectorModel).+ */+ copyToAgent: connectorProcedure+ .input(z.object({ agentId: z.string(), connectorId: z.string().uuid() }))+ .mutation(async ({ input, ctx }) => {+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);+ if (!(await agentModel.existsOwnedById(input.agentId))) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });+ }++ const source = await ctx.connectorModel.findById(input.connectorId);+ if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });++ const existing = await ctx.connectorModel.findScopedByIdentifier(+ source.identifier,+ input.agentId,+ );+ if (existing) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: `Agent already has a "${source.identifier}" connector`,+ });+ }++ const created = await ctx.connectorModel.copyToAgent(input.connectorId, input.agentId);+ if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });+ return { id: created.id };+ }),++ /**+ * "Mount user tool" (Linked): reference-lock a user connector onto this agent.+ * The row stays user-owned (keeps syncing with the user's edits) but resolves+ * for this agent and is locked so no other agent can mount the same one.+ */+ mountToAgent: connectorProcedure+ .input(z.object({ agentId: z.string(), connectorId: z.string().uuid() }))+ .mutation(async ({ input, ctx }) => {+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);+ if (!(await agentModel.existsOwnedById(input.agentId))) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });+ }++ const connector = await ctx.connectorModel.findById(input.connectorId);+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });+ if (connector.agentId) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Only a user connector can be mounted (this one is already agent-owned)',+ });+ }++ const lockedBy = connector.metadata?.mountedByAgentId;+ if (lockedBy && lockedBy !== input.agentId) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'Connector is already mounted by another agent',+ });+ }++ const existing = await ctx.connectorModel.findScopedByIdentifier(+ connector.identifier,+ input.agentId,+ );+ if (existing) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: `Agent already has a "${connector.identifier}" connector`,+ });+ }++ await ctx.connectorModel.update(input.connectorId, {+ metadata: { ...connector.metadata, mountedByAgentId: input.agentId },+ });+ return { id: input.connectorId };+ }),++ /** Unmount a connector from its agent (clears the reference lock). */+ unmountFromAgent: connectorProcedure+ .input(z.object({ connectorId: z.string().uuid() }))+ .mutation(async ({ input, ctx }) => {+ const connector = await ctx.connectorModel.findById(input.connectorId);+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });++ const { mountedByAgentId: _drop, ...restMeta } = connector.metadata ?? {};+ await ctx.connectorModel.update(input.connectorId, { metadata: restMeta });+ return { id: input.connectorId };+ }),+/*** Begin the OAuth authorization-code flow for a custom MCP connector.*@@ -293,7 +494,10 @@ export const connectorRouter = router({id: z.string().uuid(),patch: createConnectorSchema.partial()- .omit({ identifier: true, sourceType: true })+ // `agentId` is intentionally omitted: moving a connector in/out of+ // agent scope must go through bindAgent/unbindAgent (agent edit-rights+ // + uniqueness guards), not the generic update patch.+ .omit({ agentId: true, identifier: true, sourceType: true })// Allow `null` here so an edit can clear credentials (switch to no-auth)..extend({ credentials: connectorCredentialsInputSchema.nullish() }),}),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.tsindex ac92a4ef27b..45d23c7d86a 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts@@ -96,6 +96,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(() => ({queryByIdentifiers: vi.fn().mockResolvedValue([]),+ resolveByIdentifiers: vi.fn().mockResolvedValue([]),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.tsindex ef26c3629ca..37e26639e4a 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts@@ -64,6 +64,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(() => ({queryByIdentifiers: mockConnectorQueryByIdentifiers,+ resolveByIdentifiers: mockConnectorQueryByIdentifiers,})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.tsindex af5387d14b8..b0634bc9883 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts@@ -81,6 +81,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(() => ({queryByIdentifiers: vi.fn().mockResolvedValue([]),+ resolveByIdentifiers: vi.fn().mockResolvedValue([]),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.tsindex f51a254e096..b84a0991d2b 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts@@ -62,6 +62,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(() => ({queryByIdentifiers: vi.fn().mockResolvedValue([]),+ resolveByIdentifiers: vi.fn().mockResolvedValue([]),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.tsindex 6ff87311ac8..1d95b8b8b45 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts@@ -9,7 +9,7 @@ import { AiAgentService } from '../index';// instead of requiring the model to call `activateSkill`. Non-pinned (auto)// skills stay content-less here and remain lazily activatable.const {- mockConnectorQueryByIdentifiers,+ mockConnectorResolveByIdentifiers,mockConnectorToolQueryAll,mockCreateOperation,mockCreateServerAgentToolsEngine,@@ -23,7 +23,7 @@ const {mockSkillFindAll,mockSkillFindByIds,} = vi.hoisted(() => ({- mockConnectorQueryByIdentifiers: vi.fn().mockResolvedValue([]),+ mockConnectorResolveByIdentifiers: vi.fn().mockResolvedValue([]),mockConnectorToolQueryAll: vi.fn().mockResolvedValue([]),mockCreateOperation: vi.fn(),mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({@@ -95,7 +95,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(() => ({- queryByIdentifiers: mockConnectorQueryByIdentifiers,+ resolveByIdentifiers: mockConnectorResolveByIdentifiers,})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.tsindex 1517a4902e0..19c1f84e3bd 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts@@ -68,6 +68,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(() => ({queryByIdentifiers: mockConnectorQueryByIdentifiers,+ resolveByIdentifiers: mockConnectorQueryByIdentifiers,})),}));diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 8afd4743143..e508c3b7f61 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -524,7 +524,7 @@ export class AiAgentService {workspaceId: wsId,});this.marketService = new MarketService({ userInfo: { userId } });- this.composioService = new ComposioService({ db, userId });+ this.composioService = new ComposioService({ db, userId, workspaceId: wsId });}private async resolveOperationTaskId(@@ -2476,7 +2476,11 @@ export class AiAgentService {}const connectors =agentPlugins.length > 0- ? await this.connectorModel.queryByIdentifiers(agentPlugins, connectorGateKeeper)+ ? await this.connectorModel.resolveByIdentifiers(+ agentPlugins,+ resolvedAgentId,+ connectorGateKeeper,+ ): [];// Only connectors WITH a real MCP endpoint (mcpServerUrl or stdio) can replace plugins in the@@ -2527,7 +2531,7 @@ export class AiAgentService {// 5d. Fetch Composio tool manifests from databasetry {- composioManifests = await this.composioService.getComposioManifests();+ composioManifests = await this.composioService.getComposioManifests(resolvedAgentId);} catch (error) {log('execAgent: failed to fetch composio manifests: %O', error);}@@ -2553,7 +2557,7 @@ export class AiAgentService {];const connectorEntries =allIdentifiers.length > 0- ? await this.connectorModel.queryByIdentifiers(allIdentifiers)+ ? await this.connectorModel.resolveByIdentifiers(allIdentifiers, resolvedAgentId): [];if (connectorEntries.length > 0) {diff --git a/apps/server/src/services/toolExecution/builtin.ts b/apps/server/src/services/toolExecution/builtin.tsindex 1b229112cb0..8c9f9a64503 100644--- a/apps/server/src/services/toolExecution/builtin.ts+++ b/apps/server/src/services/toolExecution/builtin.ts@@ -45,11 +45,13 @@ const collectRuntimeApiNames = (runtime: Record<string, any>): string[] => {export class BuiltinToolsExecutor implements IToolExecutor {private marketService: MarketService;- private composioService: ComposioService;+ private db: LobeChatDatabase;+ private userId: string;constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;this.marketService = new MarketService({ userInfo: { userId } });- this.composioService = new ComposioService({ db, userId });}async execute(@@ -110,9 +112,19 @@ export class BuiltinToolsExecutor implements IToolExecutor {});}- // Route Composio tools to ComposioService+ // Route Composio tools to ComposioService. Build it request-scoped: agentId+ // and workspaceId live on the per-call context (not known at construction),+ // so a workspace run resolves workspace connectors (LOBE-10891) and a+ // service-account agent runs off its own Composio account+ // (Agent > Workspace/Personal).if (source === 'composio') {- return this.composioService.executeComposioTool({+ const composioService = new ComposioService({+ db: this.db,+ userId: this.userId,+ workspaceId: context.workspaceId,+ });+ return composioService.executeComposioTool({+ agentId: context.agentId,args,identifier,toolSlug: apiName,diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex b9dfc9e58e0..09df02a8c38 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -93,6 +93,7 @@ export class ToolExecutionService {identifier,apiName,context.workspaceId,+ context.agentId,);if (permission === ConnectorToolPermission.disabled) {log('Tool %s:%s is disabled by user — blocking execution', identifier, apiName);diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 7442667976a..cb19f0ca580 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -597,6 +597,29 @@"serviceModel.memoryModels.title": "Memory Models","serviceModel.modelAssignments.title": "Model Assignments","serviceModel.optionalFeatures.title": "Optional Features",+ "settingAgent.agentTools.add": "Add Tool",+ "settingAgent.agentTools.agentEmpty": "No agent-exclusive tools yet",+ "settingAgent.agentTools.badge.agentOnly": "Agent-only",+ "settingAgent.agentTools.badge.copy": "Copy",+ "settingAgent.agentTools.badge.linked": "Linked",+ "settingAgent.agentTools.badge.overridden": "Overridden",+ "settingAgent.agentTools.connectNew.desc": "Agent-exclusive connection",+ "settingAgent.agentTools.connectNew.title": "Connect new tool",+ "settingAgent.agentTools.connectNewPickerTitle": "Connect a new tool for this Agent",+ "settingAgent.agentTools.copy.desc": "Independent copy, separately configurable",+ "settingAgent.agentTools.copy.title": "Copy user tool",+ "settingAgent.agentTools.copyConfirm": "Copy {{count}}",+ "settingAgent.agentTools.copyPick": "Select user connectors to copy into this agent",+ "settingAgent.agentTools.menuTitle": "Add a tool for this Agent",+ "settingAgent.agentTools.mount.desc": "Reference, syncs with user config",+ "settingAgent.agentTools.mount.title": "Mount user tool",+ "settingAgent.agentTools.overriddenNote": "{{count}} user tool(s) overridden by same-named Agent Tools; they will not run.",+ "settingAgent.agentTools.pickerEmpty": "No user connectors available to add",+ "settingAgent.agentTools.priorityHint": "Run priority",+ "settingAgent.agentTools.priorityTooltip": "When identifiers collide, the Agent tool overrides the User tool at runtime (Agent > Workspace > Personal).",+ "settingAgent.agentTools.removeOwnedConfirm": "Delete this agent-exclusive connector? Its credentials will be removed.",+ "settingAgent.agentTools.tabAgent": "Agent Tools",+ "settingAgent.agentTools.tabUser": "User Tools","settingAgent.avatar.sizeExceeded": "Image size exceeds 1MB limit, please choose a smaller image","settingAgent.avatar.title": "Avatar","settingAgent.backgroundColor.title": "Background Color",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex d1c5bd5a3ad..4e79a091ab6 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -597,6 +597,29 @@"serviceModel.memoryModels.title": "记忆模型","serviceModel.modelAssignments.title": "模型分配","serviceModel.optionalFeatures.title": "可选功能",+ "settingAgent.agentTools.add": "添加工具",+ "settingAgent.agentTools.agentEmpty": "还没有 Agent 专属工具",+ "settingAgent.agentTools.badge.agentOnly": "Agent 专属",+ "settingAgent.agentTools.badge.copy": "副本",+ "settingAgent.agentTools.badge.linked": "引用",+ "settingAgent.agentTools.badge.overridden": "已覆盖",+ "settingAgent.agentTools.connectNew.desc": "Agent 专属连接",+ "settingAgent.agentTools.connectNew.title": "连接新工具",+ "settingAgent.agentTools.connectNewPickerTitle": "为此 Agent 连接一个新工具",+ "settingAgent.agentTools.copy.desc": "独立副本,可单独改配置",+ "settingAgent.agentTools.copy.title": "复制用户工具",+ "settingAgent.agentTools.copyConfirm": "确认复制 {{count}}",+ "settingAgent.agentTools.copyPick": "勾选要复制到该 Agent 的用户连接器",+ "settingAgent.agentTools.menuTitle": "为此 Agent 添加工具",+ "settingAgent.agentTools.mount.desc": "引用,随用户配置更新",+ "settingAgent.agentTools.mount.title": "挂载用户工具",+ "settingAgent.agentTools.overriddenNote": "{{count}} 个用户工具被同名 Agent 工具覆盖,运行时不会生效。",+ "settingAgent.agentTools.pickerEmpty": "没有可添加的用户连接器",+ "settingAgent.agentTools.priorityHint": "运行优先级",+ "settingAgent.agentTools.priorityTooltip": "同名时,运行时优先使用 Agent 工具(Agent > 工作空间 > 个人)。",+ "settingAgent.agentTools.removeOwnedConfirm": "删除这个 Agent 专属连接器?其凭据将被移除。",+ "settingAgent.agentTools.tabAgent": "Agent Tools",+ "settingAgent.agentTools.tabUser": "User Tools","settingAgent.avatar.sizeExceeded": "图片大小超过 1MB 限制,请选择更小的图片","settingAgent.avatar.title": "助理头像","settingAgent.backgroundColor.title": "头像背景色",diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex fcd47f76f64..3219dd660ad 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -74,6 +74,23 @@ afterEach(async () => {});describe('AgentModel', () => {+ describe('existsOwnedById', () => {+ it('is true only for the agent creator (edit-rights gate), not merely visibility', async () => {+ const ownAgent = 'owned-agent-id';+ const othersAgent = 'others-agent-id';+ await serverDB.insert(agents).values([+ { id: ownAgent, userId },+ { id: othersAgent, userId: userId2 },+ ]);++ expect(await agentModel.existsOwnedById(ownAgent)).toBe(true);+ // Another user's agent is not "owned" even if it were visible.+ expect(await agentModel.existsOwnedById(othersAgent)).toBe(false);+ // Its actual creator passes.+ expect(await agentModel2.existsOwnedById(othersAgent)).toBe(true);+ });+ });+describe('getAgentConfigById', () => {it('should return agent config with assigned knowledge', async () => {const agentId = 'test-agent-id';diff --git a/packages/database/src/models/__tests__/connectorAgentScope.test.ts b/packages/database/src/models/__tests__/connectorAgentScope.test.tsnew file mode 100644index 00000000000..ce24495fd53--- /dev/null+++ b/packages/database/src/models/__tests__/connectorAgentScope.test.ts@@ -0,0 +1,349 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { agents, userConnectors, userConnectorTools, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { ConnectorModel } from '../connector';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'agentscope-user';+const otherUserId = 'agentscope-other-user';+const workspaceId = 'agentscope-workspace';+const agentA = 'agentscope-agent-a';+const agentB = 'agentscope-agent-b';++/** Insert a connector row directly so we can control (agentId, workspaceId, metadata) exactly. */+const insertConnector = async (row: {+ agentId?: string | null;+ credentials?: string | null;+ identifier: string;+ metadata?: Record<string, unknown> | null;+ name: string;+ userId?: string;+ workspaceId?: string | null;+}) => {+ const [created] = await serverDB+ .insert(userConnectors)+ .values({+ agentId: row.agentId ?? null,+ credentials: row.credentials ?? null,+ identifier: row.identifier,+ metadata: row.metadata ?? null,+ name: row.name,+ sourceType: 'custom',+ status: 'connected',+ userId: row.userId ?? userId,+ workspaceId: row.workspaceId ?? null,+ })+ .returning();+ return created;+};++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: 'agentscope-ws' });+ await serverDB.insert(agents).values([+ { id: agentA, userId },+ { id: agentB, userId },+ ]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('ConnectorModel agent-scoped resolution', () => {+ describe('resolveByIdentifiers (personal run)', () => {+ it('prefers the agent-owned row over the base personal row (Agent > Personal)', async () => {+ await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ const agentRow = await insertConnector({+ agentId: agentA,+ identifier: 'gmail',+ name: 'Agent Gmail',+ });++ const model = new ConnectorModel(serverDB, userId);+ const resolved = await model.resolveByIdentifiers(['gmail'], agentA);++ expect(resolved).toHaveLength(1);+ expect(resolved[0].id).toBe(agentRow.id);+ expect(resolved[0].name).toBe('Agent Gmail');+ });++ it('downgrades to the base personal row when the agent has no binding', async () => {+ const baseRow = await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });++ const model = new ConnectorModel(serverDB, userId);+ const resolved = await model.resolveByIdentifiers(['gmail'], agentA);++ expect(resolved).toHaveLength(1);+ expect(resolved[0].id).toBe(baseRow.id);+ });++ it('resolves the agent row even when no base row exists', async () => {+ const agentRow = await insertConnector({+ agentId: agentA,+ identifier: 'gmail',+ name: 'Agent Gmail',+ });++ const model = new ConnectorModel(serverDB, userId);+ const resolved = await model.resolveByIdentifiers(['gmail'], agentA);++ expect(resolved.map((r) => r.id)).toEqual([agentRow.id]);+ });++ it("never resolves another agent's connector", async () => {+ const baseRow = await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ await insertConnector({ agentId: agentB, identifier: 'gmail', name: 'Agent B Gmail' });++ const model = new ConnectorModel(serverDB, userId);+ // Running as agent A: agent B's row must be invisible → falls back to base.+ const resolved = await model.resolveByIdentifiers(['gmail'], agentA);++ expect(resolved).toHaveLength(1);+ expect(resolved[0].id).toBe(baseRow.id);+ });++ it('with no agentId resolves base rows only (agent rows excluded)', async () => {+ const baseRow = await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ await insertConnector({ agentId: agentA, identifier: 'gmail', name: 'Agent Gmail' });++ const model = new ConnectorModel(serverDB, userId);+ const resolved = await model.resolveByIdentifiers(['gmail']);++ expect(resolved).toHaveLength(1);+ expect(resolved[0].id).toBe(baseRow.id);+ });++ it('returns at most one row per identifier across a mixed batch', async () => {+ await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ await insertConnector({ agentId: agentA, identifier: 'gmail', name: 'Agent Gmail' });+ await insertConnector({ identifier: 'notion', name: 'Personal Notion' });++ const model = new ConnectorModel(serverDB, userId);+ const resolved = await model.resolveByIdentifiers(['gmail', 'notion'], agentA);++ const byId = Object.fromEntries(resolved.map((r) => [r.identifier, r.name]));+ expect(resolved).toHaveLength(2);+ expect(byId.gmail).toBe('Agent Gmail');+ expect(byId.notion).toBe('Personal Notion');+ });+ });++ describe('resolveByIdentifiers (workspace run)', () => {+ it('prefers the agent-workspace row over the base workspace row and never falls back to personal', async () => {+ // personal row (must NOT leak into a workspace run)+ await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ // workspace base row+ const wsRow = await insertConnector({+ identifier: 'gmail',+ name: 'Workspace Gmail',+ workspaceId,+ });+ // agent-workspace row+ const agentWsRow = await insertConnector({+ agentId: agentA,+ identifier: 'gmail',+ name: 'Agent WS Gmail',+ workspaceId,+ });++ const model = new ConnectorModel(serverDB, userId, workspaceId);++ expect((await model.resolveByIdentifiers(['gmail'], agentA))[0].id).toBe(agentWsRow.id);+ // no agent binding → workspace base, still not personal+ expect((await model.resolveByIdentifiers(['gmail']))[0].id).toBe(wsRow.id);+ });+ });++ describe('findScopedByIdentifier', () => {+ it('matches the exact scope and does not cross between agent and base', async () => {+ const baseRow = await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ const agentRow = await insertConnector({+ agentId: agentA,+ identifier: 'gmail',+ name: 'Agent Gmail',+ });++ const model = new ConnectorModel(serverDB, userId);++ expect((await model.findScopedByIdentifier('gmail'))?.id).toBe(baseRow.id);+ expect((await model.findScopedByIdentifier('gmail', agentA))?.id).toBe(agentRow.id);+ // agent B has no row for this identifier+ expect(await model.findScopedByIdentifier('gmail', agentB)).toBeNull();+ });+ });++ describe('resolveAll', () => {+ it('dedupes by identifier with the agent row winning', async () => {+ await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ await insertConnector({ agentId: agentA, identifier: 'gmail', name: 'Agent Gmail' });+ await insertConnector({ identifier: 'notion', name: 'Personal Notion' });++ const model = new ConnectorModel(serverDB, userId);+ const all = await model.resolveAll(agentA);++ const byIdentifier = Object.fromEntries(all.map((r) => [r.identifier, r.name]));+ expect(all).toHaveLength(2);+ expect(byIdentifier.gmail).toBe('Agent Gmail');+ expect(byIdentifier.notion).toBe('Personal Notion');+ });+ });++ describe('queryByAgent', () => {+ it('returns only the given agent rows and excludes base + other-agent rows', async () => {+ await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ const aRow = await insertConnector({ agentId: agentA, identifier: 'gmail', name: 'A Gmail' });+ await insertConnector({ agentId: agentB, identifier: 'gmail', name: 'B Gmail' });++ const model = new ConnectorModel(serverDB, userId);+ const rows = await model.queryByAgent(agentA);++ expect(rows.map((r) => r.id)).toEqual([aRow.id]);+ });+ });++ describe('base query excludes agent rows', () => {+ it('query() and queryByIdentifiers() return base rows only', async () => {+ await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ await insertConnector({ agentId: agentA, identifier: 'gmail', name: 'Agent Gmail' });++ const model = new ConnectorModel(serverDB, userId);++ const listed = await model.query();+ expect(listed.every((r) => r.agentId === null)).toBe(true);+ expect(listed).toHaveLength(1);++ const byId = await model.queryByIdentifiers(['gmail']);+ expect(byId).toHaveLength(1);+ expect(byId[0].agentId).toBeNull();+ });+ });++ describe('copyToAgent', () => {+ it('clones a user connector into an agent-owned row, copying the credentials ciphertext verbatim and leaving the source intact', async () => {+ const source = await insertConnector({+ credentials: 'enc:cipher-blob',+ identifier: 'gmail',+ name: 'Personal Gmail',+ });++ const model = new ConnectorModel(serverDB, userId);+ const copy = await model.copyToAgent(source.id, agentA);++ expect(copy).not.toBeNull();+ expect(copy!.id).not.toBe(source.id);+ expect(copy!.agentId).toBe(agentA);+ expect(copy!.identifier).toBe('gmail');+ expect(copy!.credentials).toBe('enc:cipher-blob'); // ciphertext copied as-is+ // source row is untouched+ const stillBase = await model.findScopedByIdentifier('gmail');+ expect(stillBase?.id).toBe(source.id);+ });++ it('clones the connector tools onto the copy, leaving the source tools intact', async () => {+ const source = await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });+ await serverDB.insert(userConnectorTools).values({+ crudType: 'read',+ permission: 'auto',+ toolName: 'GMAIL_SEND_EMAIL',+ userConnectorId: source.id,+ userId,+ });++ const model = new ConnectorModel(serverDB, userId);+ const copy = await model.copyToAgent(source.id, agentA);++ const copiedTools = await serverDB+ .select()+ .from(userConnectorTools)+ .where(eq(userConnectorTools.userConnectorId, copy!.id));+ expect(copiedTools.map((t) => t.toolName)).toEqual(['GMAIL_SEND_EMAIL']);++ const sourceTools = await serverDB+ .select()+ .from(userConnectorTools)+ .where(eq(userConnectorTools.userConnectorId, source.id));+ expect(sourceTools).toHaveLength(1);+ });++ it('drops a mount lock from the copied metadata', async () => {+ const source = await insertConnector({+ identifier: 'gmail',+ metadata: { avatar: '📧', mountedByAgentId: agentB },+ name: 'Personal Gmail',+ });++ const model = new ConnectorModel(serverDB, userId);+ const copy = await model.copyToAgent(source.id, agentA);++ expect(copy!.metadata?.mountedByAgentId).toBeUndefined();+ expect(copy!.metadata?.avatar).toBe('📧');+ });+ });++ describe('mount (reference + lock)', () => {+ it('a base row mounted by an agent resolves for that agent but is locked away from others', async () => {+ const mounted = await insertConnector({+ identifier: 'gmail',+ metadata: { mountedByAgentId: agentA },+ name: 'Personal Gmail',+ });++ const model = new ConnectorModel(serverDB, userId);++ // Agent A (the mounter) resolves it.+ expect((await model.resolveByIdentifiers(['gmail'], agentA))[0]?.id).toBe(mounted.id);+ // Agent B is locked out — the only row is mounted by A, no free fallback.+ expect(await model.resolveByIdentifiers(['gmail'], agentB)).toHaveLength(0);+ // Non-agent base resolution also excludes a mounted row.+ expect(await model.resolveByIdentifiers(['gmail'])).toHaveLength(0);+ });++ it('prefers an agent-owned row over a mount, and a mount over a free base row', async () => {+ await insertConnector({ identifier: 'gmail', name: 'Free base' });+ await insertConnector({+ identifier: 'notion',+ metadata: { mountedByAgentId: agentA },+ name: 'Mounted Notion',+ });+ const owned = await insertConnector({+ agentId: agentA,+ identifier: 'gmail',+ name: 'Agent-owned Gmail',+ });++ const model = new ConnectorModel(serverDB, userId);+ const resolved = await model.resolveByIdentifiers(['gmail', 'notion'], agentA);+ const byIdentifier = Object.fromEntries(resolved.map((r) => [r.identifier, r]));++ expect(byIdentifier.gmail.id).toBe(owned.id); // owned > free base+ expect(byIdentifier.notion.name).toBe('Mounted Notion'); // mount resolves+ });++ it('queryByAgent returns agent-owned AND mounted rows', async () => {+ const owned = await insertConnector({+ agentId: agentA,+ identifier: 'gmail',+ name: 'Owned',+ });+ const mounted = await insertConnector({+ identifier: 'notion',+ metadata: { mountedByAgentId: agentA },+ name: 'Mounted',+ });+ await insertConnector({ identifier: 'slack', name: 'Free base' }); // excluded++ const model = new ConnectorModel(serverDB, userId);+ const rows = await model.queryByAgent(agentA);++ expect(rows.map((r) => r.id).sort()).toEqual([owned.id, mounted.id].sort());+ });+ });+});diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 3747e8e45db..3271e08ef90 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -239,6 +239,24 @@ export class AgentModel {return rows.length > 0;};+ /**+ * Stricter than {@link existsById}: the agent must be owned (created) by this+ * user, regardless of workspace visibility. `existsById` uses the visibility+ * -aware ownership predicate, so a *public* workspace agent created by another+ * member also returns true — which is only "can see", not "can edit". Callers+ * that bind credentials/config to an agent (e.g. agent-scoped connectors) must+ * use this so a member can't attach an account to someone else's shared agent.+ */+ existsOwnedById = async (id: string): Promise<boolean> => {+ const rows = await this.db+ .select({ id: agents.id })+ .from(agents)+ .where(and(eq(agents.id, id), eq(agents.userId, this.userId)))+ .limit(1);++ return rows.length > 0;+ };+/*** Lightweight lookup of an agent's currently-configured model + provider,* used to snapshot the model into a task config so later changes to thediff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.tsindex ad2cee657f7..f21672aa149 100644--- a/packages/database/src/models/connector.ts+++ b/packages/database/src/models/connector.ts@@ -1,4 +1,4 @@-import { and, eq, inArray } from 'drizzle-orm';+import { and, eq, inArray, isNull, or, sql } from 'drizzle-orm';import type {ConnectorCredentials,@@ -6,7 +6,7 @@ import type {NewUserConnector,UserConnectorItem,} from '../schemas';-import { userConnectors } from '../schemas';+import { userConnectors, userConnectorTools } from '../schemas';import type { LobeChatDatabase } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';@@ -41,6 +41,64 @@ export class ConnectorModel {private ownership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, userConnectors);+ /**+ * Base (non-agent) scope: the current user/workspace scope restricted to rows+ * that are NOT bound to a specific agent (`agent_id IS NULL`). Agent-scoped+ * rows are a refinement resolved separately via {@link resolveByIdentifiers} /+ * {@link resolveAll}; base list/lookup methods must not surface them, otherwise+ * an agent connector would leak into personal/workspace management + resolution+ * and collide on identifier.+ */+ private baseScope = () => and(this.ownership(), isNull(userConnectors.agentId));++ /**+ * Candidate rows for agent-aware resolution within the current scope. For an+ * agent this is:+ * - agent-OWNED rows (`agent_id = agentId`) — the Copy / Connect-new flows;+ * - base rows (`agent_id IS NULL`) that are either MOUNTED by this agent+ * (`metadata.mountedByAgentId = agentId`, the Linked flow) or free (not+ * mounted by anyone).+ * A base row mounted (locked) by *another* agent is excluded, so a mounted+ * connector can serve only its one agent. Without an agent, only free base+ * rows are candidates.+ */+ private scopePredicate = (agentId?: string) => {+ const mountedBy = sql`${userConnectors.metadata} ->> 'mountedByAgentId'`;+ if (!agentId) {+ return and(this.ownership(), isNull(userConnectors.agentId), sql`${mountedBy} IS NULL`);+ }+ return and(+ this.ownership(),+ or(+ eq(userConnectors.agentId, agentId),+ and(+ isNull(userConnectors.agentId),+ or(sql`${mountedBy} = ${agentId}`, sql`${mountedBy} IS NULL`),+ ),+ ),+ );+ };++ /**+ * Reduce candidate rows to at most one per identifier by priority within the+ * current scope: agent-OWNED (2) > MOUNTED by this agent (1) > free base (0).+ * Resolution never crosses the base scope: a workspace run resolves within the+ * workspace, a personal run within personal — no cross-scope personal fallback.+ */+ private pickByPriority = (rows: UserConnectorItem[], agentId?: string): UserConnectorItem[] => {+ const rank = (row: UserConnectorItem): number => {+ if (agentId && row.agentId === agentId) return 2;+ if (agentId && row.metadata?.mountedByAgentId === agentId) return 1;+ return 0;+ };+ const byIdentifier = new Map<string, UserConnectorItem>();+ for (const row of rows) {+ const current = byIdentifier.get(row.identifier);+ if (!current || rank(row) > rank(current)) byIdentifier.set(row.identifier, row);+ }+ return [...byIdentifier.values()];+ };+create = async (params: CreateConnectorParams,gateKeeper: GateKeeper | undefined = this.gateKeeper,@@ -62,6 +120,54 @@ export class ConnectorModel {return result;};+ /**+ * Clone an existing connector into an agent scope ("Copy user tool"): a new+ * independent row with the same config, bound to `agentId`. The encrypted+ * `credentials` ciphertext is copied verbatim (same vault key, so no+ * decrypt/re-encrypt needed) — which is why copying must happen server-side:+ * the client never receives the ciphertext. Any mount reference on the source+ * is dropped so the copy is a standalone agent-owned connector.+ */+ copyToAgent = async (sourceId: string, agentId: string): Promise<UserConnectorItem | null> => {+ const [source] = await this.db+ .select()+ .from(userConnectors)+ .where(and(eq(userConnectors.id, sourceId), this.ownership()))+ .limit(1);+ if (!source) return null;++ const { id: _id, createdAt: _c, updatedAt: _u, metadata, ...rest } = source;+ const cleanedMetadata = metadata+ ? (() => {+ const { mountedByAgentId: _m, ...restMeta } = metadata;+ return restMeta;+ })()+ : metadata;++ const [created] = await this.db+ .insert(userConnectors)+ .values({ ...rest, agentId, metadata: cleanedMetadata })+ .returning();++ // Clone the connector's tools (user_connector_tools) onto the new row —+ // otherwise the copy has no callable tools and the runtime resolves nothing.+ const sourceTools = await this.db+ .select()+ .from(userConnectorTools)+ .where(eq(userConnectorTools.userConnectorId, sourceId));++ if (sourceTools.length > 0) {+ await this.db.insert(userConnectorTools).values(+ sourceTools.map(({ id: _toolId, createdAt: _tc, updatedAt: _tu, ...toolRest }) => ({+ ...toolRest,+ userConnectorId: created.id,+ })),+ );+ }++ return created;+ };+delete = async (id: string): Promise<void> => {await this.db.delete(userConnectors).where(and(eq(userConnectors.id, id), this.ownership()));};@@ -69,11 +175,42 @@ export class ConnectorModel {query = async (gateKeeper: GateKeeper | undefined = this.gateKeeper,): Promise<DecryptedConnector[]> => {- const rows = await this.db.select().from(userConnectors).where(this.ownership());+ const rows = await this.db.select().from(userConnectors).where(this.baseScope());++ return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));+ };++ /**+ * All connectors that belong to an agent's "Agent Tools" view: agent-OWNED+ * rows (`agent_id = agentId` — Copy / Connect-new) plus base rows MOUNTED by+ * this agent (`metadata.mountedByAgentId = agentId` — Linked). Powers the+ * agent-settings management view (the base {@link query} excludes agent-owned+ * rows; mounted rows still appear there too, flagged as locked).+ */+ queryByAgent = async (+ agentId: string,+ gateKeeper: GateKeeper | undefined = this.gateKeeper,+ ): Promise<DecryptedConnector[]> => {+ const rows = await this.db+ .select()+ .from(userConnectors)+ .where(+ and(+ this.ownership(),+ or(+ eq(userConnectors.agentId, agentId),+ sql`${userConnectors.metadata} ->> 'mountedByAgentId' = ${agentId}`,+ ),+ ),+ );return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));};+ /**+ * Base (non-agent) rows for the given identifiers. Excludes agent-scoped rows;+ * use {@link resolveByIdentifiers} for agent-aware runtime resolution.+ */queryByIdentifiers = async (identifiers: string[],gateKeeper: GateKeeper | undefined = this.gateKeeper,@@ -83,11 +220,81 @@ export class ConnectorModel {const rows = await this.db.select().from(userConnectors)- .where(and(this.ownership(), inArray(userConnectors.identifier, identifiers)));+ .where(and(this.baseScope(), inArray(userConnectors.identifier, identifiers)));return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));};+ /**+ * Agent-aware runtime resolution. For each identifier returns at most one+ * connector, preferring the agent-owned row (`agent_id = agentId`) over the+ * base row (Agent > Workspace/Personal). When `agentId` is omitted this is+ * equivalent to {@link queryByIdentifiers} (base rows only).+ *+ * This is the single entry point runtime paths (aiAgent manifest build,+ * connector exec, MCP call gate, Composio account resolution) must use in+ * place of `const [c] = await queryByIdentifiers(...)`, which silently picked+ * an arbitrary row once multiple rows share an identifier.+ */+ resolveByIdentifiers = async (+ identifiers: string[],+ agentId?: string,+ gateKeeper: GateKeeper | undefined = this.gateKeeper,+ ): Promise<DecryptedConnector[]> => {+ if (identifiers.length === 0) return [];++ const rows = await this.db+ .select()+ .from(userConnectors)+ .where(and(this.scopePredicate(agentId), inArray(userConnectors.identifier, identifiers)));++ return Promise.all(this.pickByPriority(rows, agentId).map((r) => decryptRow(r, gateKeeper)));+ };++ /**+ * Agent-aware variant of {@link query}: every resolvable connector in the+ * current scope, deduped by identifier with the agent-owned row winning. Used+ * to enumerate connectors for a run (e.g. Composio manifest building) where+ * the agent's own connector should shadow the base one.+ */+ resolveAll = async (+ agentId?: string,+ gateKeeper: GateKeeper | undefined = this.gateKeeper,+ ): Promise<DecryptedConnector[]> => {+ const rows = await this.db.select().from(userConnectors).where(this.scopePredicate(agentId));++ return Promise.all(this.pickByPriority(rows, agentId).map((r) => decryptRow(r, gateKeeper)));+ };++ /**+ * Exact-scope lookup for write-path idempotency: finds the row for one+ * specific scope — the given agent (`agent_id = agentId`) or, when `agentId`+ * is omitted, the base row (`agent_id IS NULL`). Unlike+ * {@link resolveByIdentifiers} it does NOT fall back across scopes, so+ * creating an agent connector never updates the personal/workspace row and+ * vice versa.+ */+ findScopedByIdentifier = async (+ identifier: string,+ agentId?: string,+ gateKeeper: GateKeeper | undefined = this.gateKeeper,+ ): Promise<DecryptedConnector | null> => {+ const [row] = await this.db+ .select()+ .from(userConnectors)+ .where(+ and(+ this.ownership(),+ eq(userConnectors.identifier, identifier),+ agentId ? eq(userConnectors.agentId, agentId) : isNull(userConnectors.agentId),+ ),+ )+ .limit(1);++ if (!row) return null;+ return decryptRow(row, gateKeeper);+ };+findById = async (id: string,gateKeeper: GateKeeper | undefined = this.gateKeeper,diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.tsindex 7561eee4794..96f3f3f0e7d 100644--- a/packages/database/src/schemas/connector.ts+++ b/packages/database/src/schemas/connector.ts@@ -128,6 +128,15 @@ export interface ConnectorMetadata {composio?: ComposioConnectorMetadata;customHeaders?: Record<string, string>;description?: string;+ /**+ * "Mount" reference lock: a base (user-owned) connector referenced by an+ * agent via the "挂载/Linked" flow. The row stays user-owned (`agent_id`+ * NULL) and keeps syncing with the user's edits, but resolves for this agent+ * and is locked so no other agent can mount the same connector. Cleared on+ * unmount. Distinct from `agent_id` (which is full agent ownership — Copy /+ * Connect-new).+ */+ mountedByAgentId?: string;}// ─────────────────────────────────────────────────────────────────────────────diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 9a300c883b8..82b5a9a7eb7 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -693,6 +693,32 @@ export default {'Enter core instructions, press / to open the Slash Menu','settingAgent.prompt.placeholder': 'Enter agent instructions','settingAgent.prompt.title': 'Core Instructions',+ 'settingAgent.agentTools.add': 'Add Tool',+ 'settingAgent.agentTools.agentEmpty': 'No agent-exclusive tools yet',+ 'settingAgent.agentTools.badge.agentOnly': 'Agent-only',+ 'settingAgent.agentTools.badge.copy': 'Copy',+ 'settingAgent.agentTools.badge.linked': 'Linked',+ 'settingAgent.agentTools.badge.overridden': 'Overridden',+ 'settingAgent.agentTools.connectNew.desc': 'Agent-exclusive connection',+ 'settingAgent.agentTools.connectNew.title': 'Connect new tool',+ 'settingAgent.agentTools.connectNewPickerTitle': 'Connect a new tool for this Agent',+ 'settingAgent.agentTools.copy.desc': 'Independent copy, separately configurable',+ 'settingAgent.agentTools.copy.title': 'Copy user tool',+ 'settingAgent.agentTools.copyConfirm': 'Copy {{count}}',+ 'settingAgent.agentTools.copyPick': 'Select user connectors to copy into this agent',+ 'settingAgent.agentTools.menuTitle': 'Add a tool for this Agent',+ 'settingAgent.agentTools.mount.desc': 'Reference, syncs with user config',+ 'settingAgent.agentTools.mount.title': 'Mount user tool',+ 'settingAgent.agentTools.overriddenNote':+ '{{count}} user tool(s) overridden by same-named Agent Tools; they will not run.',+ 'settingAgent.agentTools.pickerEmpty': 'No user connectors available to add',+ 'settingAgent.agentTools.priorityHint': 'Run priority',+ 'settingAgent.agentTools.priorityTooltip':+ 'When identifiers collide, the Agent tool overrides the User tool at runtime (Agent > Workspace > Personal).',+ 'settingAgent.agentTools.removeOwnedConfirm':+ 'Delete this agent-exclusive connector? Its credentials will be removed.',+ 'settingAgent.agentTools.tabAgent': 'Agent Tools',+ 'settingAgent.agentTools.tabUser': 'User Tools','settingAgent.runtimeConfig.title': 'Model & Tools','settingAgent.submit': 'Update Agent','settingAgent.tag.desc': 'Agent tags will be displayed in the Agent Community',diff --git a/src/features/AgentSkillStore/Content.tsx b/src/features/AgentSkillStore/Content.tsxnew file mode 100644index 00000000000..69901d1afb5--- /dev/null+++ b/src/features/AgentSkillStore/Content.tsx@@ -0,0 +1,61 @@+'use client';++import { COMPOSIO_APP_TYPES } from '@lobechat/const';+import { Flexbox, Text } from '@lobehub/ui';+import { memo, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import { gridStyles } from '@/features/SkillStore/SkillList/style';+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';+import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';++import Item from './Item';++/**+ * "Connect new tool" store for a single agent — a trimmed, agent-scoped mirror+ * of SkillStore's first (LobeHub) tab. v1 lists Composio connectors; "connected"+ * reflects the AGENT's own connectors, and connecting binds a fresh account to+ * the agent (agent_id). LobeHub-OAuth / custom-MCP tabs are intentionally left+ * out for now.+ */+const AgentSkillStoreContent = memo<{ agentId: string }>(({ agentId }) => {+ const { t } = useTranslation('setting');+ const isComposioEnabled = useServerConfigStore(serverConfigSelectors.enableComposio);+ const isInit = useToolStore(connectorSelectors.isAgentConnectorsInit(agentId));+ const fetchAgentConnectors = useToolStore((s) => s.fetchAgentConnectors);++ useEffect(() => {+ if (agentId && !isInit) fetchAgentConnectors(agentId);+ }, [agentId, isInit, fetchAgentConnectors]);++ return (+ <Flexbox gap={8} style={{ maxHeight: '75vh' }} width={'100%'}>+ {isComposioEnabled ? (+ <Flexbox height={496} style={{ marginBlockEnd: -12, marginInline: -16, overflow: 'auto' }}>+ <div className={gridStyles.grid}>+ {COMPOSIO_APP_TYPES.map((type) => (+ <Item+ agentId={agentId}+ appSlug={type.appSlug}+ description={type.description}+ icon={type.icon}+ identifier={type.identifier}+ key={type.identifier}+ label={type.label}+ />+ ))}+ </div>+ </Flexbox>+ ) : (+ <Text style={{ padding: 24 }} type={'secondary'}>+ {t('settingAgent.agentTools.pickerEmpty')}+ </Text>+ )}+ </Flexbox>+ );+});++AgentSkillStoreContent.displayName = 'AgentSkillStoreContent';++export default AgentSkillStoreContent;diff --git a/src/features/AgentSkillStore/Item.tsx b/src/features/AgentSkillStore/Item.tsxnew file mode 100644index 00000000000..96161d4c2e0--- /dev/null+++ b/src/features/AgentSkillStore/Item.tsx@@ -0,0 +1,118 @@+'use client';++import { ActionIcon, Block, DropdownMenu, Flexbox, Icon, stopPropagation } from '@lobehub/ui';+import { confirmModal } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { Loader2, MoreVerticalIcon, Plus, Unplug } from 'lucide-react';+import React, { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { itemStyles } from '@/features/SkillStore/SkillList/style';+import { usePermission } from '@/hooks/usePermission';++import { useAgentComposioConnect } from './useAgentComposioConnect';++interface ItemProps {+ agentId: string;+ appSlug: string;+ description?: string;+ icon: string | React.ComponentType;+ identifier: string;+ label: string;+}++/**+ * Agent-scoped Composio connector card — mirrors SkillStore's LobeHub Item but+ * its connected state + connect/disconnect are bound to the agent, not the user.+ */+const Item = memo<ItemProps>(({ agentId, appSlug, description, icon, identifier, label }) => {+ const { t } = useTranslation('setting');+ const styles = itemStyles;+ const { allowed: canCreate } = usePermission('create_content');+ const { allowed: canEdit } = usePermission('edit_own_content');++ const { handleConnect, handleDisconnect, isConnected, isConnecting } = useAgentComposioConnect({+ agentId,+ appSlug,+ identifier,+ label,+ });++ const localizedDescription = t(`tools.composio.servers.${identifier}.description` as any, {+ defaultValue: description ?? '',+ });++ const confirmDisconnect = () => {+ if (!canEdit) return;+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('settingAgent.agentTools.removeOwnedConfirm'),+ okButtonProps: { danger: true },+ okText: t('tools.lobehubSkill.disconnect'),+ onOk: handleDisconnect,+ });+ };++ const renderIcon = () => {+ if (typeof icon === 'string') return <img alt={label} height={40} src={icon} width={40} />;+ return <Icon fill={cssVar.colorText} icon={icon as any} size={40} />;+ };++ const renderAction = () => {+ if (isConnecting) return <ActionIcon loading icon={Loader2} />;+ if (isConnected) {+ return (+ <DropdownMenu+ nativeButton={false}+ placement="bottomRight"+ items={[+ {+ danger: true,+ disabled: !canEdit,+ icon: <Icon icon={Unplug} />,+ key: 'disconnect',+ label: t('tools.lobehubSkill.disconnect'),+ onClick: confirmDisconnect,+ },+ ]}+ >+ <ActionIcon disabled={!canEdit} icon={MoreVerticalIcon} />+ </DropdownMenu>+ );+ }+ return (+ <ActionIcon+ disabled={!canCreate || !canEdit}+ icon={Plus}+ title={t('tools.lobehubSkill.connect')}+ onClick={() => {+ if (!canCreate || !canEdit) return;+ handleConnect();+ }}+ />+ );+ };++ return (+ <Block+ horizontal+ align={'center'}+ className={styles.container}+ gap={12}+ paddingBlock={12}+ paddingInline={12}+ variant={'outlined'}+ >+ {renderIcon()}+ <Flexbox flex={1} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>+ <span className={styles.title}>{label}</span>+ {localizedDescription && <span className={styles.description}>{localizedDescription}</span>}+ </Flexbox>+ <div onClick={stopPropagation}>{renderAction()}</div>+ </Block>+ );+});++Item.displayName = 'AgentSkillStoreItem';++export default Item;diff --git a/src/features/AgentSkillStore/index.tsx b/src/features/AgentSkillStore/index.tsxnew file mode 100644index 00000000000..7b265b986a0--- /dev/null+++ b/src/features/AgentSkillStore/index.tsx@@ -0,0 +1,15 @@+'use client';++import { createModal } from '@lobehub/ui/base-ui';+import { t } from 'i18next';++import AgentSkillStoreContent from './Content';++/** Open the agent-scoped "connect new tool" store for a specific agent. */+export const createAgentSkillStoreModal = (agentId: string) =>+ createModal({+ content: <AgentSkillStoreContent agentId={agentId} />,+ footer: null,+ title: t('settingAgent.agentTools.connectNewPickerTitle', { ns: 'setting' }),+ width: 'min(80%, 800px)',+ });diff --git a/src/features/AgentSkillStore/useAgentComposioConnect.ts b/src/features/AgentSkillStore/useAgentComposioConnect.tsnew file mode 100644index 00000000000..70933abffc4--- /dev/null+++ b/src/features/AgentSkillStore/useAgentComposioConnect.ts@@ -0,0 +1,194 @@+'use client';++import { upsertPluginMode } from '@lobechat/types';+import isEqual from 'fast-deep-equal';+import { useCallback, useEffect, useRef, useState } from 'react';++import { lambdaClient, toolsClient } from '@/libs/trpc/client';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';++const POLL_INTERVAL_MS = 1000;+const POLL_TIMEOUT_MS = 15_000;++interface PendingConnection {+ authConfigId: string;+ connectedAccountId: string;+ redirectUrl?: string;+}++interface Options {+ agentId: string;+ appSlug: string;+ identifier: string;+ label: string;+}++/**+ * Agent-scoped Composio connect — the "clean" path that does NOT touch the+ * user-scoped composio store. It drives the connect/activate flow directly+ * against the lambda router with `agentId`, so the account lands on an+ * agent-owned connector row (`user_connectors.agent_id`), and derives+ * "connected" from the agent's own connectors (not the user's).+ */+export const useAgentComposioConnect = ({ agentId, appSlug, identifier, label }: Options) => {+ const [isConnecting, setIsConnecting] = useState(false);+ const [isWaitingAuth, setIsWaitingAuth] = useState(false);++ const pendingRef = useRef<PendingConnection | null>(null);+ const oauthWindowRef = useRef<Window | null>(null);+ const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const agentConnectors = useToolStore(connectorSelectors.agentConnectors(agentId), isEqual);+ const fetchAgentConnectors = useToolStore((s) => s.fetchAgentConnectors);+ const detachConnectorFromAgent = useToolStore((s) => s.detachConnectorFromAgent);+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);++ const agentRow = agentConnectors.find(+ (c) => c.identifier === identifier && c.agentId === agentId && !!c.metadata?.composio,+ );+ const isConnected = !!agentRow;++ const cleanup = useCallback(() => {+ for (const ref of [windowCheckIntervalRef, pollIntervalRef]) {+ if (ref.current) {+ clearInterval(ref.current);+ ref.current = null;+ }+ }+ if (pollTimeoutRef.current) {+ clearTimeout(pollTimeoutRef.current);+ pollTimeoutRef.current = null;+ }+ oauthWindowRef.current = null;+ setIsWaitingAuth(false);+ }, []);++ useEffect(() => () => cleanup(), [cleanup]);++ /** After OAuth returns ACTIVE, write the agent connector row + pin the tool. */+ const activate = useCallback(async () => {+ const pending = pendingRef.current;+ if (!pending) return;+ try {+ const status = await lambdaClient.composio.getConnection.query({+ connectedAccountId: pending.connectedAccountId,+ });+ if (status.status !== 'ACTIVE') return;++ const toolsResp = await toolsClient.composio.listActions.query({ appSlug });+ const tools = (toolsResp.tools ?? []).map((tool) => ({+ description: tool.description,+ inputSchema: tool.inputSchema,+ name: tool.name,+ }));++ await lambdaClient.composio.updateComposioPlugin.mutate({+ agentId,+ appSlug,+ authConfigId: pending.authConfigId,+ connectedAccountId: pending.connectedAccountId,+ identifier,+ label,+ redirectUrl: pending.redirectUrl,+ status: 'ACTIVE',+ tools,+ });++ // Pin the tool for this agent so the runtime actually resolves it.+ const config = agentSelectors.getAgentConfigById(agentId)(useAgentStore.getState());+ await updateAgentConfigById(agentId, {+ plugins: upsertPluginMode(config?.plugins, identifier, 'pinned'),+ });++ await fetchAgentConnectors(agentId);+ pendingRef.current = null;+ } catch (error) {+ console.error('[AgentSkillStore] activate failed:', error);+ }+ }, [agentId, appSlug, identifier, label, updateAgentConfigById, fetchAgentConnectors]);++ const startFallbackPolling = useCallback(() => {+ if (pollIntervalRef.current) return;+ pollIntervalRef.current = setInterval(() => {+ activate().then(() => {+ if (pendingRef.current === null) cleanup();+ });+ }, POLL_INTERVAL_MS);+ pollTimeoutRef.current = setTimeout(cleanup, POLL_TIMEOUT_MS);+ }, [activate, cleanup]);++ const startWindowMonitor = useCallback(+ (oauthWindow: Window) => {+ windowCheckIntervalRef.current = setInterval(async () => {+ if (oauthWindow.closed) {+ if (windowCheckIntervalRef.current) {+ clearInterval(windowCheckIntervalRef.current);+ windowCheckIntervalRef.current = null;+ }+ await activate();+ cleanup();+ }+ }, 500);+ },+ [activate, cleanup],+ );++ const openOAuthWindow = useCallback(+ (redirectUrl: string) => {+ cleanup();+ setIsWaitingAuth(true);+ const oauthWindow = window.open(redirectUrl, '_blank', 'width=600,height=700');+ if (oauthWindow) {+ oauthWindowRef.current = oauthWindow;+ startWindowMonitor(oauthWindow);+ } else {+ startFallbackPolling();+ }+ },+ [cleanup, startWindowMonitor, startFallbackPolling],+ );++ const handleConnect = useCallback(async () => {+ if (isConnected) return;+ setIsConnecting(true);+ try {+ const conn = await lambdaClient.composio.createConnection.mutate({+ agentId,+ appSlug,+ identifier,+ label,+ });+ pendingRef.current = {+ authConfigId: conn.authConfigId,+ connectedAccountId: conn.connectedAccountId,+ redirectUrl: conn.redirectUrl,+ };+ if (conn.redirectUrl) {+ openOAuthWindow(conn.redirectUrl);+ } else {+ await activate();+ }+ } catch (error) {+ console.error('[AgentSkillStore] connect failed:', error);+ } finally {+ setIsConnecting(false);+ }+ }, [isConnected, agentId, appSlug, identifier, label, openOAuthWindow, activate]);++ const handleDisconnect = useCallback(async () => {+ if (!agentRow) return;+ await detachConnectorFromAgent(agentRow.id, agentId, 'delete');+ }, [agentRow, agentId, detachConnectorFromAgent]);++ return {+ handleConnect,+ handleDisconnect,+ isConnected,+ isConnecting: isConnecting || isWaitingAuth,+ };+};diff --git a/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsxindex 96f34b06673..9d2df429998 100644--- a/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx+++ b/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx@@ -22,6 +22,12 @@ interface ComposioServerItemProps {* Used in group profile to specify which member's plugins to toggle*/agentId?: string;+ /**+ * When true, a fresh connection is bound to the agent (Agent-exclusive+ * "Connect new tool" flow); the resulting account lands on an agent-scoped+ * connector row. Default false keeps composio connects user-scoped.+ */+ agentScoped?: boolean;/*** Identifier used for storage (e.g., 'google-calendar')*/@@ -35,7 +41,7 @@ interface ComposioServerItemProps {}const ComposioServerItem = memo<ComposioServerItemProps>(- ({ appSlug, identifier, label, server, agentId }) => {+ ({ appSlug, identifier, label, server, agentId, agentScoped = false }) => {const { t } = useTranslation('setting');const [isConnecting, setIsConnecting] = useState(false);const [isToggling, setIsToggling] = useState(false);@@ -207,6 +213,9 @@ const ComposioServerItem = memo<ComposioServerItemProps>(setIsConnecting(true);try {const newServer = await createComposioConnection({+ // When invoked from an Agent's "Connect new tool" flow, bind the+ // connection to that agent so the account lands on an agent-scoped row.+ agentId: agentScoped ? effectiveAgentId : undefined,appSlug,identifier,label,diff --git a/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsxnew file mode 100644index 00000000000..9c096057e92--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/AgentToolsSection.tsx@@ -0,0 +1,117 @@+'use client';++import { upsertPluginMode } from '@lobechat/types';+import { Dropdown, Flexbox, Icon, Text } from '@lobehub/ui';+import { Button, confirmModal } from '@lobehub/ui/base-ui';+import isEqual from 'fast-deep-equal';+import { CopyIcon, PlugZapIcon, PlusIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { createAgentSkillStoreModal } from '@/features/AgentSkillStore';+import PluginTag from '@/features/ProfileEditor/PluginTag';+import { usePermission } from '@/hooks/usePermission';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';++/**+ * The "Agent Tools" section (top of the tools area): the connectors owned by+ * this agent, rendered with the same chips as User Tools (PluginTag). Removing+ * an agent chip is a two-step op — unpin it from `agents.plugins` AND delete the+ * agent-owned `user_connectors` row (one more step than the user side).+ */+const AgentToolsSection = memo<{ agentId: string; onStartCopy: () => void }>(+ ({ agentId, onStartCopy }) => {+ const { t } = useTranslation('setting');+ const { allowed: canEdit } = usePermission('edit_own_content');++ const agentConnectors = useToolStore(connectorSelectors.agentConnectors(agentId), isEqual);+ const detachConnectorFromAgent = useToolStore((s) => s.detachConnectorFromAgent);+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);++ const handleRemove = async (connector: ConnectorWithTools) => {+ const ok = await confirmModal({ content: t('settingAgent.agentTools.removeOwnedConfirm') });+ if (!ok) return;+ // 1) remove from agents.plugins, 2) delete the agent connector row.+ const config = agentSelectors.getAgentConfigById(agentId)(useAgentStore.getState());+ await updateAgentConfigById(agentId, {+ plugins: upsertPluginMode(config?.plugins, connector.identifier, 'auto'),+ });+ await detachConnectorFromAgent(connector.id, agentId, 'delete');+ };++ const addMenuItems = [+ {+ icon: <Icon icon={PlugZapIcon} />,+ key: 'connectNew',+ label: (+ <Flexbox>+ <Text>{t('settingAgent.agentTools.connectNew.title')}</Text>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('settingAgent.agentTools.connectNew.desc')}+ </Text>+ </Flexbox>+ ),+ onClick: () => createAgentSkillStoreModal(agentId),+ },+ {+ icon: <Icon icon={CopyIcon} />,+ key: 'copy',+ label: (+ <Flexbox>+ <Text>{t('settingAgent.agentTools.copy.title')}</Text>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('settingAgent.agentTools.copy.desc')}+ </Text>+ </Flexbox>+ ),+ onClick: onStartCopy,+ },+ ];++ return (+ <Flexbox gap={8}>+ <Text style={{ fontSize: 12, fontWeight: 500 }} type={'secondary'}>+ {t('settingAgent.agentTools.tabAgent')} · {agentConnectors.length}+ </Text>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <Dropdown+ disabled={!canEdit}+ menu={{ items: addMenuItems }}+ placement={'bottomLeft'}+ trigger={['click']}+ >+ <Button icon={<Icon icon={PlusIcon} />} size={'small'} type={'text'}>+ {t('settingAgent.agentTools.add')}+ </Button>+ </Dropdown>++ {agentConnectors.length === 0 && (+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('settingAgent.agentTools.agentEmpty')}+ </Text>+ )}++ {agentConnectors.map((connector) => (+ <PluginTag+ agentId={agentId}+ disabled={!canEdit}+ key={connector.id}+ pluginId={connector.identifier}+ onRemove={() => {+ handleRemove(connector);+ }}+ />+ ))}+ </Flexbox>+ </Flexbox>+ );+ },+);++AgentToolsSection.displayName = 'AgentToolsSection';++export default AgentToolsSection;diff --git a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsxnew file mode 100644index 00000000000..76e476a7849--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.tsx@@ -0,0 +1,106 @@+'use client';++import { getActivePluginIds } from '@lobechat/types';+import { Flexbox, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import isEqual from 'fast-deep-equal';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import SharedAgentTool, { type AgentToolProps } from '@/features/ProfileEditor/AgentTool';+import PluginTag from '@/features/ProfileEditor/PluginTag';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';++interface Props extends AgentToolProps {+ agentId: string;+ copying: boolean;+ copyMode: boolean;+ onCancelCopy: () => void;+ onConfirmCopy: () => void;+ selected: Set<string>;+ toggleSelected: (id: string) => void;+}++/**+ * The "User Tools" section (bottom of the tools area). Normally the user's+ * pinned tools (SharedAgentTool). In copy mode, the user's connectors become+ * selectable chips so several can be copied into the agent at once.+ */+const UserToolsSection = memo<Props>(+ ({+ agentId,+ copyMode,+ copying,+ onCancelCopy,+ onConfirmCopy,+ selected,+ toggleSelected,+ ...toolProps+ }) => {+ const { t } = useTranslation('setting');+ const userConnectors = useToolStore(connectorSelectors.connectorList, isEqual);+ const config = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);+ const userToolCount = getActivePluginIds(config?.plugins).length;++ // Copyable = the user's own base connectors (not agent-owned, not mounted).+ const copyable = userConnectors.filter((c) => !c.agentId && !c.metadata?.mountedByAgentId);++ if (copyMode) {+ return (+ <Flexbox gap={8}>+ <Flexbox horizontal align={'center'} justify={'space-between'}>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('settingAgent.agentTools.copyPick')}+ </Text>+ <Flexbox horizontal gap={8}>+ <Button disabled={copying} size={'small'} type={'text'} onClick={onCancelCopy}>+ {t('cancel', { ns: 'common' })}+ </Button>+ <Button+ disabled={selected.size === 0 || copying}+ loading={copying}+ size={'small'}+ type={'primary'}+ onClick={onConfirmCopy}+ >+ {t('settingAgent.agentTools.copyConfirm', { count: selected.size })}+ </Button>+ </Flexbox>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ {copyable.length === 0 && (+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('settingAgent.agentTools.pickerEmpty')}+ </Text>+ )}+ {copyable.map((c) => (+ <PluginTag+ selectable+ key={c.id}+ pluginId={c.identifier}+ selected={selected.has(c.id)}+ onSelect={() => toggleSelected(c.id)}+ />+ ))}+ </Flexbox>+ </Flexbox>+ );+ }++ return (+ <Flexbox gap={8}>+ <Text style={{ fontSize: 12, fontWeight: 500 }} type={'secondary'}>+ {t('settingAgent.agentTools.tabUser')} · {userToolCount}+ </Text>+ <SharedAgentTool {...toolProps} agentId={agentId} />+ </Flexbox>+ );+ },+);++UserToolsSection.displayName = 'UserToolsSection';++export default UserToolsSection;diff --git a/src/features/ProfileEditor/AgentUserTools/index.tsx b/src/features/ProfileEditor/AgentUserTools/index.tsxnew file mode 100644index 00000000000..8f2ad749fd4--- /dev/null+++ b/src/features/ProfileEditor/AgentUserTools/index.tsx@@ -0,0 +1,118 @@+'use client';++import { upsertPluginMode } from '@lobechat/types';+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';+import isEqual from 'fast-deep-equal';+import { InfoIcon } from 'lucide-react';+import { memo, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { type AgentToolProps } from '@/features/ProfileEditor/AgentTool';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';++import AgentToolsSection from './AgentToolsSection';+import UserToolsSection from './UserToolsSection';++/**+ * The profile "Model & Tools" tools area — a single page with two stacked+ * sections: Agent Tools (top, connectors bound to this agent) and User Tools+ * (bottom, the user's pinned tools). Agent tools resolve with priority over+ * same-named user tools at runtime.+ */+const AgentUserTools = memo<AgentToolProps>((props) => {+ const { agentId } = props;+ const { t } = useTranslation('setting');+ const activeAgentId = useAgentStore((s) => s.activeAgentId);+ const effectiveAgentId = agentId || activeAgentId || '';++ const isInit = useToolStore(connectorSelectors.isAgentConnectorsInit(effectiveAgentId));+ const fetchAgentConnectors = useToolStore((s) => s.fetchAgentConnectors);+ const copyConnectorToAgent = useToolStore((s) => s.copyConnectorToAgent);+ const userConnectors = useToolStore(connectorSelectors.connectorList, isEqual);+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);++ useEffect(() => {+ if (effectiveAgentId && !isInit) fetchAgentConnectors(effectiveAgentId);+ }, [effectiveAgentId, isInit, fetchAgentConnectors]);++ const [copyMode, setCopyMode] = useState(false);+ const [copying, setCopying] = useState(false);+ const [selected, setSelected] = useState<Set<string>>(() => new Set());++ const toggleSelected = (id: string) =>+ setSelected((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });++ const resetCopy = () => {+ setCopyMode(false);+ setSelected(new Set());+ };++ const handleConfirmCopy = async () => {+ setCopying(true);+ try {+ const identifiers: string[] = [];+ for (const id of selected) {+ const conn = userConnectors.find((c) => c.id === id);+ if (!conn) continue;+ await copyConnectorToAgent(id, effectiveAgentId);+ identifiers.push(conn.identifier);+ }+ // Pin the copied tools for the agent so the runtime resolves them.+ if (identifiers.length > 0) {+ const config = agentSelectors.getAgentConfigById(effectiveAgentId)(+ useAgentStore.getState(),+ );+ let plugins = config?.plugins;+ for (const identifier of identifiers)+ plugins = upsertPluginMode(plugins, identifier, 'pinned');+ await updateAgentConfigById(effectiveAgentId, { plugins });+ }+ resetCopy();+ } finally {+ setCopying(false);+ }+ };++ return (+ <Flexbox gap={16} width={'100%'}>+ <Flexbox horizontal align={'center'} justify={'flex-end'}>+ <Tooltip title={t('settingAgent.agentTools.priorityTooltip')}>+ <Flexbox+ horizontal+ align={'center'}+ gap={4}+ style={{ cursor: 'help', fontSize: 12, opacity: 0.55 }}+ >+ <Icon icon={InfoIcon} size={14} />+ {t('settingAgent.agentTools.priorityHint')}+ </Flexbox>+ </Tooltip>+ </Flexbox>++ <AgentToolsSection agentId={effectiveAgentId} onStartCopy={() => setCopyMode(true)} />++ <UserToolsSection+ {...props}+ agentId={effectiveAgentId}+ copyMode={copyMode}+ copying={copying}+ selected={selected}+ toggleSelected={toggleSelected}+ onCancelCopy={resetCopy}+ onConfirmCopy={handleConfirmCopy}+ />+ </Flexbox>+ );+});++AgentUserTools.displayName = 'AgentUserTools';++export default AgentUserTools;diff --git a/src/features/ProfileEditor/PluginTag.tsx b/src/features/ProfileEditor/PluginTag.tsxindex 6124760ddab..18776d7d059 100644--- a/src/features/ProfileEditor/PluginTag.tsx+++ b/src/features/ProfileEditor/PluginTag.tsx@@ -2,11 +2,11 @@import { type ComposioAppType, type LobehubSkillProviderType } from '@lobechat/const';import { COMPOSIO_APP_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';-import { Avatar, Icon, Tag } from '@lobehub/ui';+import { Avatar, Flexbox, Icon, Tag } from '@lobehub/ui';import { McpIcon } from '@lobehub/ui/icons';import { createStaticStyles, cssVar } from 'antd-style';import isEqual from 'fast-deep-equal';-import { AlertCircle, Loader2, X } from 'lucide-react';+import { AlertCircle, Loader2, Square, SquareCheckBig, X } from 'lucide-react';import React, { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -79,9 +79,24 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));export interface PluginTagProps {+ /**+ * When set, an identifier owned/mounted by this agent resolves as installed+ * (agent connectors live on the agent's own rows, not the user's stores),+ * so an agent-exclusive connector doesn't render as "Not Installed".+ */+ agentId?: string;disabled?: boolean;- onRemove: (e: React.MouseEvent) => void;+ onRemove?: (e: React.MouseEvent) => void;+ /** Fires when the checkbox/tag is toggled in `selectable` mode. */+ onSelect?: () => void;pluginId: string | { enabled: boolean; identifier: string; settings: Record<string, any> };+ /**+ * Render as a selectable chip: a leading checkbox, no remove (×) button, and+ * the whole tag toggles selection. Used by the multi-select "copy" flow.+ */+ selectable?: boolean;+ /** Selection state in `selectable` mode. */+ selected?: boolean;/*** Whether to show "Desktop Only" label for tools not available in web* @default false@@ -95,13 +110,29 @@ export interface PluginTagProps {}const PluginTag = memo<PluginTagProps>(- ({ pluginId, onRemove, disabled, showDesktopOnlyLabel = false, useAllMetaList = false }) => {+ ({+ agentId,+ pluginId,+ onRemove,+ onSelect,+ selectable = false,+ selected = false,+ disabled,+ showDesktopOnlyLabel = false,+ useAllMetaList = false,+ }) => {const isDarkMode = useIsDark();const { t } = useTranslation('setting');// Extract identifierconst identifier = typeof pluginId === 'string' ? pluginId : pluginId?.identifier;+ // Agent-scoped connectors (empty unless agentId is provided).+ const agentConnectors = useToolStore(+ connectorSelectors.agentConnectors(agentId ?? ''),+ isEqual,+ );+// Get local plugin lists - use allMetaList or metaList based on propconst builtinList = useToolStore(useAllMetaList ? builtinToolSelectors.allMetaList : builtinToolSelectors.metaList,@@ -125,6 +156,15 @@ const PluginTag = memo<PluginTagProps>(// Try to find in local lists first (including Composio and LobehubSkill)const localMeta = useMemo(() => {+ // Agent-owned/mounted connector: resolve as installed even though it isn't+ // in the user-scoped stores. The icon still comes from the normal+ // resolution below (composio/lobehub/builtin/plugin), with an MCP fallback+ // at the end for an agent-only connector absent from every user list.+ const agentConn = agentId+ ? agentConnectors.find((c) => c.identifier === identifier)+ : undefined;+ const agentInstalled = !!agentConn;+// Check if it's a Composio server typeif (isComposioEnabledInEnv) {const composioType = COMPOSIO_APP_TYPES.find((type) => type.identifier === identifier);@@ -134,7 +174,7 @@ const PluginTag = memo<PluginTagProps>(return {availableInWeb: true,icon: composioType.icon,- isInstalled: !!connectedServer,+ isInstalled: !!connectedServer || agentInstalled,label: composioType.label,title: composioType.label,type: 'composio' as const,@@ -151,7 +191,7 @@ const PluginTag = memo<PluginTagProps>(return {availableInWeb: true,icon: lobehubSkillProvider.icon,- isInstalled: !!connectedServer,+ isInstalled: !!connectedServer || agentInstalled,label: lobehubSkillProvider.label,title: lobehubSkillProvider.label,type: 'lobehub-skill' as const,@@ -199,9 +239,24 @@ const PluginTag = memo<PluginTagProps>(};}+ // Agent-only connector not found in any user store: use its own row + MCP+ // icon so it renders installed (not a warning "Not Installed" chip).+ if (agentConn) {+ return {+ availableInWeb: true,+ icon: McpIcon,+ isInstalled: true,+ label: agentConn.name || identifier,+ title: agentConn.name || identifier,+ type: 'custom-connector' as const,+ };+ }+return null;}, [identifier,+ agentId,+ agentConnectors,builtinList,installedPluginList,isComposioEnabledInEnv,@@ -209,6 +264,7 @@ const PluginTag = memo<PluginTagProps>(isLobehubSkillEnabled,allLobehubSkillServers,customConnectors,+ useAllMetaList,]);// Fetch from remote if not found locally@@ -290,20 +346,35 @@ const PluginTag = memo<PluginTagProps>(return (<TagclassName={styles.tag}- closable={!disabled}+ closable={!disabled && !selectable}closeIcon={<X size={12} />}color={showErrorState ? 'error' : undefined}- icon={renderIcon()}+ style={selectable ? { cursor: 'pointer' } : undefined}variant={isDarkMode ? 'filled' : 'outlined'}+ icon={+ selectable ? (+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon+ icon={selected ? SquareCheckBig : Square}+ size={14}+ style={{ color: selected ? cssVar.colorPrimary : cssVar.colorTextQuaternary }}+ />+ {renderIcon()}+ </Flexbox>+ ) : (+ renderIcon()+ )+ }title={showErrorState? t('tools.notInstalledWarning', { defaultValue: 'This tool is not installed' }): undefined}+ onClick={selectable ? onSelect : undefined}onClose={(e) => {if (disabled) return;- onRemove(e);+ onRemove?.(e);}}>{getDisplayText()}diff --git a/src/libs/mcp/connectorPermissionCheck.ts b/src/libs/mcp/connectorPermissionCheck.tsindex 13e8518e020..7aa2f288816 100644--- a/src/libs/mcp/connectorPermissionCheck.ts+++ b/src/libs/mcp/connectorPermissionCheck.ts@@ -15,6 +15,8 @@ export { patchManifestWithPermissions } from './patchManifestPermissions';* @param identifier - Connector identifier (e.g. 'gmail', 'vercel')* @param toolName - Tool API name (e.g. 'gmail_search_emails', 'deploy')* @param workspaceId - Workspace scope (omit for personal mode)+ * @param agentId - Agent scope: prefer the agent-owned connector row for this+ * identifier (Agent > Workspace/Personal), matching runtime resolution.** Returns the stored permission, or null if no connector/tool entry exists.*/@@ -24,10 +26,11 @@ export async function getConnectorToolPermission(identifier: string,toolName: string,workspaceId?: string,+ agentId?: string,): Promise<ConnectorToolPermission | null> {try {const connectorModel = new ConnectorModel(db, userId, workspaceId);- const [connector] = await connectorModel.queryByIdentifiers([identifier]);+ const [connector] = await connectorModel.resolveByIdentifiers([identifier], agentId);if (!connector) return null;const toolModel = new ConnectorToolModel(db, userId, workspaceId);diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentTool.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentTool.tsxindex a4807cfa169..f6312b2f983 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentTool.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentTool.tsx@@ -1,15 +1,16 @@'use client';-import { AgentTool as SharedAgentTool } from '@/features/ProfileEditor';+import AgentUserTools from '@/features/ProfileEditor/AgentUserTools';/**- * AgentTool for agent profile editor+ * Tools area for the agent profile editor — an Agent Tools / User Tools tabbed+ * view (agent-scoped connectors vs the user's pinned tools).* - showWebBrowsing: Agent profile supports web browsing toggle* - filterAvailableInWeb: Filter out desktop-only tools in web version* - useAllMetaList: Use allMetaList to include hidden tools*/const AgentTool = () => {- return <SharedAgentTool filterAvailableInWeb showWebBrowsing useAllMetaList />;+ return <AgentUserTools filterAvailableInWeb showWebBrowsing useAllMetaList />;};export default AgentTool;diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsxindex 3de66a1906e..9937e9f40df 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx@@ -155,8 +155,8 @@ const ProfileEditor = memo(() => {updateAgentConfigById(agentId, value);}}/>- <AgentTool /></Flexbox>+ <AgentTool /></Flexbox></>)}diff --git a/src/server/services/composio/index.test.ts b/src/server/services/composio/index.test.tsindex 255247a71d2..31edeaeea00 100644--- a/src/server/services/composio/index.test.ts+++ b/src/server/services/composio/index.test.ts@@ -14,8 +14,11 @@ const mocks = vi.hoisted(() => ({vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn().mockImplementation(() => ({- query: mocks.connectorQuery,- queryByIdentifiers: mocks.connectorQueryByIdentifiers,+ // Runtime resolution goes through the agent-aware resolvers; map them to the+ // same fixtures (the priority/dedup logic itself is covered by the model's+ // own connectorAgentScope tests).+ resolveAll: mocks.connectorQuery,+ resolveByIdentifiers: mocks.connectorQueryByIdentifiers,})),}));diff --git a/src/server/services/composio/index.ts b/src/server/services/composio/index.tsindex 59e09a618d9..32aea2e7329 100644--- a/src/server/services/composio/index.ts+++ b/src/server/services/composio/index.ts@@ -15,6 +15,12 @@ const log = debug('lobe-server:composio-service');const VALID_COMPOSIO_IDENTIFIERS = new Set(COMPOSIO_APP_TYPES.map((type) => type.identifier));export interface ComposioToolExecuteParams {+ /**+ * Agent scope: prefer the agent-owned connector row (`agent_id = agentId`)+ * for this identifier, so a service-account agent runs off its own Composio+ * account instead of the caller's (Agent > Workspace/Personal).+ */+ agentId?: string;args: Record<string, any>;identifier: string;toolSlug: string;@@ -23,6 +29,12 @@ export interface ComposioToolExecuteParams {export interface ComposioServiceOptions {db?: LobeChatDatabase;userId?: string;+ /**+ * Workspace scope. When set, connector/plugin rows resolve within the team+ * workspace instead of the caller's personal scope (fixes workspace-installed+ * Composio connectors being invisible at runtime — LOBE-10891).+ */+ workspaceId?: string;}/**@@ -41,26 +53,29 @@ export class ComposioService {private userId?: string;constructor(options: ComposioServiceOptions = {}) {- const { db, userId } = options;+ const { db, userId, workspaceId } = options;this.userId = userId;if (db && userId) {- // Personal-scoped, mirroring the write path in the composio lambda router.- this.pluginModel = new PluginModel(db, userId);- this.connectorModel = new ConnectorModel(db, userId);- this.connectorToolModel = new ConnectorToolModel(db, userId);+ // Scope to the caller's workspace (personal when undefined). Agent-scoped+ // resolution is a per-call refinement on top of this, applied via the+ // connector model's resolve* methods.+ this.pluginModel = new PluginModel(db, userId, workspaceId);+ this.connectorModel = new ConnectorModel(db, userId, workspaceId);+ this.connectorToolModel = new ConnectorToolModel(db, userId, workspaceId);}log(- 'ComposioService initialized: hasDB=%s, hasUserId=%s, isClientAvailable=%s',+ 'ComposioService initialized: hasDB=%s, hasUserId=%s, hasWorkspace=%s, isClientAvailable=%s',!!db,!!userId,+ !!workspaceId,isComposioClientAvailable(),);}async executeComposioTool(params: ComposioToolExecuteParams): Promise<ToolExecutionResult> {- const { identifier, toolSlug, args } = params;+ const { identifier, toolSlug, args, agentId } = params;log('executeComposioTool: %s/%s with args: %O', identifier, toolSlug, args);@@ -84,7 +99,7 @@ export class ComposioService {}try {- const connectedAccountId = await this.resolveConnectedAccountId(identifier);+ const connectedAccountId = await this.resolveConnectedAccountId(identifier, agentId);if (!connectedAccountId) {return {content: `Composio configuration not found for server "${identifier}"`,@@ -151,12 +166,16 @@ export class ComposioService {/*** Resolve the Composio `connectedAccountId` for an identifier.- * Connector metadata first (new path); plugin customParams as fallback (old- * connections without a connector projection).+ * Connector metadata first (new path), preferring the agent-owned row when an+ * `agentId` is given (Agent > Workspace/Personal); plugin customParams as+ * fallback (old connections without a connector projection).*/- private async resolveConnectedAccountId(identifier: string): Promise<string | undefined> {+ private async resolveConnectedAccountId(+ identifier: string,+ agentId?: string,+ ): Promise<string | undefined> {if (this.connectorModel) {- const [connector] = await this.connectorModel.queryByIdentifiers([identifier]);+ const [connector] = await this.connectorModel.resolveByIdentifiers([identifier], agentId);const fromConnector = connector?.metadata?.composio?.connectedAccountId;if (fromConnector) return fromConnector;}@@ -169,17 +188,18 @@ export class ComposioService {return undefined;}- async getComposioManifests(): Promise<LobeToolManifest[]> {+ async getComposioManifests(agentId?: string): Promise<LobeToolManifest[]> {const manifests: LobeToolManifest[] = [];const coveredIdentifiers = new Set<string>();// 1. Connector-based (new path): rows whose metadata.composio marks them as// Composio connectors and are ACTIVE. Tool defs come from// user_connector_tools (all of them, so disabled tools stay visible for- // downstream permission patching).+ // downstream permission patching). Resolved agent-aware: an agent-owned+ // Composio connector shadows the base one for the same identifier.if (this.connectorModel && this.connectorToolModel) {try {- const connectors = await this.connectorModel.query();+ const connectors = await this.connectorModel.resolveAll(agentId);const composioConnectors = connectors.filter((c) => c.isEnabled && c.metadata?.composio?.status === 'ACTIVE',);diff --git a/src/store/tool/slices/composioStore/action.ts b/src/store/tool/slices/composioStore/action.tsindex 8bc2b90927a..a82645f5424 100644--- a/src/store/tool/slices/composioStore/action.ts+++ b/src/store/tool/slices/composioStore/action.ts@@ -91,7 +91,7 @@ export class ComposioStoreActionImpl {createComposioConnection = async (params: CreateComposioServerParams,): Promise<ComposioServer | undefined> => {- const { appSlug, identifier, label } = params;+ const { appSlug, identifier, label, agentId } = params;this.#set(produce((draft: ComposioStoreState) => {@@ -103,12 +103,14 @@ export class ComposioStoreActionImpl {try {const response = await lambdaClient.composio.createConnection.mutate({+ agentId,appSlug,identifier,label,});const server: ComposioServer = {+ agentId,appSlug,authConfigId: response.authConfigId,connectedAccountId: response.connectedAccountId,@@ -216,6 +218,7 @@ export class ComposioStoreActionImpl {);await lambdaClient.composio.updateComposioPlugin.mutate({+ agentId: server.agentId,appSlug: server.appSlug,authConfigId: server.authConfigId,connectedAccountId: server.connectedAccountId,diff --git a/src/store/tool/slices/composioStore/types.ts b/src/store/tool/slices/composioStore/types.tsindex 3939a52289a..a24b7b83cef 100644--- a/src/store/tool/slices/composioStore/types.ts+++ b/src/store/tool/slices/composioStore/types.ts@@ -15,6 +15,8 @@ export interface ComposioTool {}export interface ComposioServer {+ /** Bind this connection to an agent (Agent-exclusive connection). */+ agentId?: string;appSlug: string;authConfigId: string;connectedAccountId: string;@@ -29,6 +31,8 @@ export interface ComposioServer {}export interface CreateComposioServerParams {+ /** Bind this connection to an agent (Agent-exclusive connection). */+ agentId?: string;appSlug: string;identifier: string;label: string;diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex ac72627b965..0de9371d873 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -22,6 +22,49 @@ export class ConnectorActionImpl {this.#set({ connectors: data as any, isConnectorsInit: true }, false, 'fetchConnectors');};+ /**+ * Fetch an agent's own tools (agent-owned + mounted) for the "Agent Tools"+ * tab. Stored keyed by agentId.+ */+ fetchAgentConnectors = async (agentId: string): Promise<void> => {+ const data = await lambdaClient.connector.listByAgent.query({ agentId });+ this.#set(+ (s) => ({+ agentConnectors: { ...s.agentConnectors, [agentId]: data as any },+ agentConnectorsInit: { ...s.agentConnectorsInit, [agentId]: true },+ }),+ false,+ 'fetchAgentConnectors',+ );+ };++ /** Copy a user connector into an agent-owned, independently editable row. */+ copyConnectorToAgent = async (connectorId: string, agentId: string): Promise<string> => {+ const { id } = await lambdaClient.connector.copyToAgent.mutate({ agentId, connectorId });+ await this.fetchAgentConnectors(agentId);+ return id;+ };++ /** Mount (reference + lock) a user connector onto an agent. */+ mountConnectorToAgent = async (connectorId: string, agentId: string): Promise<void> => {+ await lambdaClient.connector.mountToAgent.mutate({ agentId, connectorId });+ await Promise.all([this.fetchAgentConnectors(agentId), this.fetchConnectors()]);+ };++ /** Unmount / detach a connector from an agent (unmounts or deletes the agent row). */+ detachConnectorFromAgent = async (+ connectorId: string,+ agentId: string,+ mode: 'unmount' | 'delete',+ ): Promise<void> => {+ if (mode === 'unmount') {+ await lambdaClient.connector.unmountFromAgent.mutate({ connectorId });+ } else {+ await lambdaClient.connector.delete.mutate({ id: connectorId });+ }+ await Promise.all([this.fetchAgentConnectors(agentId), this.fetchConnectors()]);+ };+/*** Fetch the connector with its decrypted user-set credentials for the edit* form. Does NOT update the store — caller uses the result directly.diff --git a/src/store/tool/slices/connector/initialState.ts b/src/store/tool/slices/connector/initialState.tsindex ad81ca9a1a8..cc75d1a6005 100644--- a/src/store/tool/slices/connector/initialState.ts+++ b/src/store/tool/slices/connector/initialState.ts@@ -1,6 +1,9 @@import type { ConnectorWithTools } from './types';export interface ConnectorState {+ /** Agent-scoped connectors (owned + mounted), keyed by agentId. */+ agentConnectors: Record<string, ConnectorWithTools[]>;+ agentConnectorsInit: Record<string, boolean>;connectorCreating: boolean;connectors: ConnectorWithTools[];connectorSyncing: Record<string, boolean>;@@ -8,6 +11,8 @@ export interface ConnectorState {}export const initialConnectorState: ConnectorState = {+ agentConnectors: {},+ agentConnectorsInit: {},connectorCreating: false,connectors: [],connectorSyncing: {},diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.tsindex 50c5a71711e..7a48fb91958 100644--- a/src/store/tool/slices/connector/selectors.ts+++ b/src/store/tool/slices/connector/selectors.ts@@ -56,11 +56,52 @@ const isSyncing =(s: ToolStore): boolean =>s.connectorSyncing[connectorId] ?? false;+/** An agent's own tools (agent-owned + mounted), for the Agent Tools tab. */+const agentConnectors =+ (agentId: string) =>+ (s: ToolStore): ConnectorWithTools[] =>+ s.agentConnectors?.[agentId] ?? [];++const isAgentConnectorsInit =+ (agentId: string) =>+ (s: ToolStore): boolean =>+ s.agentConnectorsInit?.[agentId] ?? false;++/**+ * The badge kind of an agent tool, derived from its scope + whether a same-named+ * user connector exists:+ * - `agentOnly` — agent-owned, no user connector of the same identifier;+ * - `copy` — agent-owned, and the user also has one of the same identifier;+ * - `linked` — a user-owned row this agent has mounted (referenced + locked).+ */+type AgentToolBadge = 'agentOnly' | 'copy' | 'linked';+const agentToolBadge =+ (agentId: string, connector: ConnectorWithTools) =>+ (s: ToolStore): AgentToolBadge => {+ if (connector.agentId !== agentId) return 'linked'; // mounted user row+ const hasUserSame = (s.connectors ?? []).some(+ (c) => c.identifier === connector.identifier && !c.agentId,+ );+ return hasUserSame ? 'copy' : 'agentOnly';+ };++/** Identifiers of user connectors that an agent has overridden (owns a same-named tool). */+const agentOverriddenIdentifiers =+ (agentId: string) =>+ (s: ToolStore): Set<string> => {+ const owned = (s.agentConnectors?.[agentId] ?? []).filter((c) => c.agentId === agentId);+ return new Set(owned.map((c) => c.identifier));+ };+export const connectorSelectors = {+ agentConnectors,+ agentOverriddenIdentifiers,+ agentToolBadge,connectedConnectors,connectorById,connectorByIdentifier,connectorList,+ isAgentConnectorsInit,connectorToolsGrouped,customConnectors,connectorToolsGroupedByIdentifier:diff --git a/src/store/tool/slices/connector/types.ts b/src/store/tool/slices/connector/types.tsindex 26401eacc47..6dc7f004a5c 100644--- a/src/store/tool/slices/connector/types.ts+++ b/src/store/tool/slices/connector/types.ts@@ -12,6 +12,8 @@ export interface ConnectorTool {}export interface ConnectorWithTools {+ /** Set when this connector is fully owned by an agent (Copy / Connect-new). */+ agentId?: string | null;credentials: unknown;id: string;identifier: string;