π€― 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
π fix(creds): integrate Klavis authorization status into lobe-creds system (#14090)
LiJian66d096e96347
diff --git a/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts b/packages/builtin-tool-creds/src/ExecutionRuntime/index.tsindex 26328181d5f..bc0d7896d71 100644--- a/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts@@ -1,7 +1,8 @@-import { getLobehubSkillProviderById } from '@lobechat/const';+import { getKlavisServerByServerIdentifier, getLobehubSkillProviderById } from '@lobechat/const';import type { BuiltinServerRuntimeOutput } from '@lobechat/types';import type {+ ConnectKlavisServiceParams,GetPlaintextCredParams,InitiateOAuthConnectParams,InjectCredsToSandboxParams,@@ -102,6 +103,42 @@ export class CredsExecutionRuntime {this.context = context;}+ /**+ * Connect a Klavis integration service+ * In server-side context, Klavis OAuth requires browser interaction,+ * so we return a message guiding the user to connect via the UI.+ */+ async connectKlavisService(+ args: ConnectKlavisServiceParams,+ ): Promise<BuiltinServerRuntimeOutput> {+ const { service } = args;++ const serverType = getKlavisServerByServerIdentifier(service);+ if (!serverType) {+ return {+ content: `Unknown Klavis service: "${service}". Check the available Klavis services list in the credentials context.`,+ error: {+ message: `Unknown Klavis service: ${service}`,+ type: 'UnknownService',+ },+ success: false,+ };+ }++ // Server-side cannot open OAuth popups or access browser stores.+ // Guide the user to connect via the frontend UI.+ return {+ content: `To connect ${serverType.label}, please use the LobeHub app UI to initiate the Klavis OAuth flow. Server-side execution cannot open OAuth popups. Go to Settings or the onboarding page to connect ${serverType.label}.`,+ state: {+ connected: false,+ identifier: service,+ requiresUserAction: true,+ serviceName: serverType.label,+ },+ success: true,+ };+ }+/*** Initiate OAuth connection flow* In server-side context, returns authorization URL for the user to clickdiff --git a/packages/builtin-tool-creds/src/executor/index.ts b/packages/builtin-tool-creds/src/executor/index.tsindex ff22dcf7de1..0868317db0f 100644--- a/packages/builtin-tool-creds/src/executor/index.ts+++ b/packages/builtin-tool-creds/src/executor/index.ts@@ -1,14 +1,18 @@-import { getLobehubSkillProviderById } from '@lobechat/const';+import { getKlavisServerByServerIdentifier, getLobehubSkillProviderById } from '@lobechat/const';import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';import debug from 'debug';import { lambdaClient, toolsClient } from '@/libs/trpc/client';+import { getToolStoreState, useToolStore } from '@/store/tool';+import { klavisStoreSelectors } from '@/store/tool/selectors';+import { KlavisServerStatus } from '@/store/tool/slices/klavisStore/types';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/slices/auth/selectors';import { CredsIdentifier } from '../manifest';import {+ type ConnectKlavisServiceParams,CredsApiName,type GetPlaintextCredParams,type InitiateOAuthConnectParams,@@ -22,6 +26,134 @@ class CredsExecutor extends BaseExecutor<typeof CredsApiName> {readonly identifier = CredsIdentifier;protected readonly apiEnum = CredsApiName;+ /**+ * Connect a Klavis integration service via OAuth+ * Creates a Klavis server instance and initiates the OAuth flow+ */+ connectKlavisService = async (+ params: ConnectKlavisServiceParams,+ _ctx?: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ const { service } = params;++ // Validate service identifier+ const serverType = getKlavisServerByServerIdentifier(service);+ if (!serverType) {+ return {+ error: {+ message: `Unknown Klavis service: "${service}". Check the available Klavis services list in the credentials context.`,+ type: 'UnknownService',+ },+ success: false,+ };+ }++ // Check if already connected via store+ const toolState = getToolStoreState();+ const existingServer = klavisStoreSelectors.getServerByIdentifier(service)(toolState);+ if (existingServer?.status === KlavisServerStatus.CONNECTED) {+ return {+ content: `Already connected to ${serverType.label}. You can use ${serverType.label} tools directly.`,+ state: {+ connected: true,+ identifier: service,+ serviceName: serverType.label,+ },+ success: true,+ };+ }++ // Get userId+ const userId = userProfileSelectors.userId(useUserStore.getState());+ if (!userId) {+ return {+ error: {+ message: 'User is not authenticated',+ type: 'MissingUserId',+ },+ success: false,+ };+ }++ log('[CredsExecutor] connectKlavisService - creating server for:', service);++ // Create Klavis server instance+ const server = await useToolStore.getState().createKlavisServer({+ identifier: serverType.identifier,+ serverName: serverType.serverName,+ userId,+ });++ if (!server) {+ return {+ error: {+ message: `Failed to create Klavis server instance for ${serverType.label}`,+ type: 'CreateServerFailed',+ },+ success: false,+ };+ }++ // If already authenticated (no OAuth needed)+ if (server.isAuthenticated) {+ return {+ content: `Successfully connected to ${serverType.label}! You can now use ${serverType.label} tools.`,+ state: {+ connected: true,+ identifier: service,+ serviceName: serverType.label,+ },+ success: true,+ };+ }++ // OAuth needed β open popup and poll for completion+ if (server.oauthUrl) {+ const result = await this.openKlavisOAuthAndWait(server.oauthUrl, server.identifier);++ if (result.success) {+ return {+ content: `Successfully connected to ${serverType.label}! You can now use ${serverType.label} tools.`,+ state: {+ connected: true,+ identifier: service,+ serviceName: serverType.label,+ },+ success: true,+ };+ }++ return {+ content: `Authorization was cancelled or timed out for ${serverType.label}. You can try again later.`,+ state: {+ connected: false,+ identifier: service,+ serviceName: serverType.label,+ },+ success: true,+ };+ }++ return {+ error: {+ message: 'Unexpected server state: no oauthUrl and not authenticated',+ type: 'UnexpectedState',+ },+ success: false,+ };+ } catch (error) {+ log('[CredsExecutor] connectKlavisService - error:', error);+ return {+ error: {+ message: error instanceof Error ? error.message : 'Failed to connect Klavis service',+ type: 'ConnectKlavisFailed',+ },+ success: false,+ };+ }+ };+/*** Initiate OAuth connection flow* Opens authorization popup and waits for user to complete authorization@@ -174,6 +306,91 @@ class CredsExecutor extends BaseExecutor<typeof CredsApiName> {});};+ /**+ * Open Klavis OAuth popup and poll for authorization completion+ * Unlike Market OAuth which uses postMessage, Klavis OAuth uses polling+ */+ private openKlavisOAuthAndWait = (+ oauthUrl: string,+ identifier: string,+ ): Promise<{ success: boolean }> => {+ return new Promise((resolve) => {+ const popup = window.open(oauthUrl, '_blank', 'width=600,height=700');++ if (!popup) {+ resolve({ success: false });+ return;+ }++ let resolved = false;+ // eslint-disable-next-line prefer-const+ let pollInterval: ReturnType<typeof setInterval>;+ // eslint-disable-next-line prefer-const+ let windowCheckInterval: ReturnType<typeof setInterval>;++ const checkConnected = async (): Promise<boolean> => {+ try {+ await useToolStore.getState().refreshKlavisServerTools(identifier);+ const toolState = getToolStoreState();+ const server = klavisStoreSelectors.getServerByIdentifier(identifier)(toolState);+ return server?.status === KlavisServerStatus.CONNECTED;+ } catch {+ return false;+ }+ };++ const cleanup = () => {+ if (resolved) return;+ resolved = true;+ clearInterval(pollInterval);+ clearInterval(windowCheckInterval);+ };++ // Poll for authentication completion every 1s+ pollInterval = setInterval(async () => {+ if (resolved) return;+ if (await checkConnected()) {+ cleanup();+ resolve({ success: true });+ }+ }, 1000);++ // Monitor popup closure β give a short grace period then treat as cancelled+ windowCheckInterval = setInterval(() => {+ if (popup.closed) {+ clearInterval(windowCheckInterval);+ if (resolved) return;++ // Grace period: check a few more times after popup closes (4s)+ // User may have authorized right before closing+ setTimeout(async () => {+ if (resolved) return;+ // One final check+ if (await checkConnected()) {+ cleanup();+ resolve({ success: true });+ } else {+ cleanup();+ resolve({ success: false });+ }+ }, 4000);+ }+ }, 500);++ // Hard timeout after 2 minutes+ setTimeout(+ () => {+ if (!resolved) {+ cleanup();+ if (!popup.closed) popup.close();+ resolve({ success: false });+ }+ },+ 2 * 60 * 1000,+ );+ });+ };+/*** Get plaintext credential value by key*/diff --git a/packages/builtin-tool-creds/src/helpers.ts b/packages/builtin-tool-creds/src/helpers.tsindex 853af5c5a3b..4ce167b417a 100644--- a/packages/builtin-tool-creds/src/helpers.ts+++ b/packages/builtin-tool-creds/src/helpers.ts@@ -86,6 +86,53 @@ export const injectCredsContext = (content: string, context: UserCredsContext):.replaceAll('{{SETTINGS_URL}}', context.settingsUrl);};+// ==================== Klavis Services ====================++/**+ * Summary of a Klavis service for display in the tool prompt+ */+export interface KlavisServiceSummary {+ description?: string;+ identifier: string;+ name: string;+}++/**+ * Generate the Klavis services list string for injection into the prompt+ */+export const generateKlavisServicesList = (+ connected: KlavisServiceSummary[],+ available: KlavisServiceSummary[],+): string => {+ if (connected.length === 0 && available.length === 0) {+ return '';+ }++ const sections: string[] = [];++ if (connected.length > 0) {+ const items = connected+ .map(+ (s) =>+ ` - ${s.name} (identifier: ${s.identifier}) β Authorized via Klavis OAuth. Use ${s.identifier} tools directly.`,+ )+ .join('\n');+ sections.push(`**Connected Klavis Services (authorized, use tools directly):**\n${items}`);+ }++ if (available.length > 0) {+ const items = available+ .map(+ (s) =>+ ` - ${s.name} (identifier: ${s.identifier}) β Use \`connectKlavisService\` to connect.`,+ )+ .join('\n');+ sections.push(`**Available Klavis Services (not yet connected):**\n${items}`);+ }++ return sections.join('\n\n');+};+/*** Check if a skill's required credentials are satisfied*/diff --git a/packages/builtin-tool-creds/src/index.ts b/packages/builtin-tool-creds/src/index.tsindex 6bd006d0867..89db5af205d 100644--- a/packages/builtin-tool-creds/src/index.ts+++ b/packages/builtin-tool-creds/src/index.ts@@ -4,13 +4,17 @@ export {type CredRequirement,type CredSummary,generateCredsList,+ generateKlavisServicesList,groupCredsByType,injectCredsContext,+ type KlavisServiceSummary,type UserCredsContext,} from './helpers';export { CredsIdentifier, CredsManifest } from './manifest';export { systemPrompt } from './systemRole';export {+ type ConnectKlavisServiceParams,+ type ConnectKlavisServiceState,CredsApiName,type CredsApiNameType,type CredSummaryForContext,diff --git a/packages/builtin-tool-creds/src/manifest.ts b/packages/builtin-tool-creds/src/manifest.tsindex da1d8753eb3..4418c97cd3a 100644--- a/packages/builtin-tool-creds/src/manifest.ts+++ b/packages/builtin-tool-creds/src/manifest.ts@@ -8,6 +8,23 @@ export const CredsIdentifier = 'lobe-creds';export const CredsManifest: BuiltinToolManifest = {api: [+ {+ description:+ 'Connect a Klavis integration service via OAuth. Use this to authorize access to third-party services managed by the Klavis platform (e.g., Notion, Gmail, Google Calendar, Slack). Check the available Klavis services in the credentials context before calling this.',+ name: CredsApiName.connectKlavisService,+ parameters: {+ additionalProperties: false,+ properties: {+ service: {+ description:+ 'The Klavis service identifier to connect (e.g., "notion", "gmail", "google-calendar"). See the available Klavis services list in the credentials context.',+ type: 'string',+ },+ },+ required: ['service'],+ type: 'object',+ } satisfies JSONSchema7,+ },{description:'Initiate OAuth connection flow for a third-party service (e.g., Linear, Microsoft Outlook, Twitter/X). Returns an authorization URL that the user must click to authorize. After authorization, the credential will be automatically saved.',diff --git a/packages/builtin-tool-creds/src/systemRole.ts b/packages/builtin-tool-creds/src/systemRole.tsindex 00799ed457f..92dee2c18a8 100644--- a/packages/builtin-tool-creds/src/systemRole.ts+++ b/packages/builtin-tool-creds/src/systemRole.ts@@ -93,6 +93,18 @@ When sandbox mode is enabled and you need to run code that requires credentials:- Use the file path directly in your code (e.g., \`GOOGLE_APPLICATION_CREDENTIALS=~/.creds/files/gcp-service-account/credentials.json\`)</sandbox_integration>+<klavis_integrations>+{{KLAVIS_SERVICES_LIST}}+</klavis_integrations>++<klavis_guidelines>+- **Klavis integrations** are OAuth connections managed by the Klavis platform for third-party services (e.g., Notion, Gmail, Google Calendar, Slack).+- For **connected** Klavis services: Use the corresponding tools directly. Do NOT ask users for API keys, tokens, or credentials β the authorization is already handled by Klavis.+- For **available but not connected** services: Use \`connectKlavisService\` to initiate the OAuth connection flow via Klavis.+- Klavis credentials **CANNOT** be retrieved via \`getPlaintextCred\` or injected via \`injectCredsToSandbox\` β they are tool-only authorizations managed externally by Klavis.+- If a user asks about a service that matches a connected Klavis integration, always prefer using the Klavis tools over asking the user for manual credentials.+</klavis_guidelines>+<response_expectations>- When credentials are relevant, mention which ones are available and how they can be used.- When accessing credentials, briefly explain why access is needed.diff --git a/packages/builtin-tool-creds/src/types.ts b/packages/builtin-tool-creds/src/types.tsindex 7465665a5ac..7590e53d5e8 100644--- a/packages/builtin-tool-creds/src/types.ts+++ b/packages/builtin-tool-creds/src/types.ts@@ -1,6 +1,12 @@import type { CredType } from '@lobechat/types';export const CredsApiName = {+ /**+ * Connect a Klavis integration service via OAuth+ * Initiates Klavis OAuth flow for third-party services like Notion, Gmail, etc.+ */+ connectKlavisService: 'connectKlavisService',+/*** Get plaintext value of a credential* Use when AI needs to access credential value for API calls@@ -138,6 +144,34 @@ export interface SaveCredsState {success: boolean;}+// ==================== Klavis Service Types ====================++export interface ConnectKlavisServiceParams {+ /**+ * The Klavis service identifier to connect (e.g., 'notion', 'gmail', 'google-calendar')+ */+ service: string;+}++export interface ConnectKlavisServiceState {+ /**+ * Whether the service is now connected+ */+ connected: boolean;+ /**+ * The service identifier+ */+ identifier: string;+ /**+ * OAuth URL (only present when authorization is needed)+ */+ oauthUrl?: string;+ /**+ * The service display name+ */+ serviceName: string;+}+// ==================== Context Types ====================export interface CredSummaryForContext {diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex a4265549c3a..76e5cbdfb43 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -1,7 +1,13 @@import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';-import { CredsIdentifier, type CredSummary, generateCredsList } from '@lobechat/builtin-tool-creds';+import {+ CredsIdentifier,+ type CredSummary,+ generateCredsList,+ generateKlavisServicesList,+ type KlavisServiceSummary,+} from '@lobechat/builtin-tool-creds';import {CronIdentifier,type CronJobSummaryForContext,@@ -53,6 +59,7 @@ import {lobehubSkillStoreSelectors,toolSelectors,} from '@/store/tool/selectors';+import { KlavisServerStatus } from '@/store/tool/slices/klavisStore';import { isCanUseVideo, isCanUseVision } from '../helper';import { combineUserMemoryData, resolveTopicMemories, resolveUserPersona } from './memoryManager';@@ -382,6 +389,39 @@ export const contextEngineering = async ({}}+ // Build Klavis services list for creds context+ // Shows which Klavis services are connected (authorized) and which are available to connect+ let klavisServicesList = '';++ const isKlavisEnabled =+ typeof window !== 'undefined' &&+ window.global_serverConfigStore?.getState()?.serverConfig?.enableKlavis;++ if (isCredsEnabled && isKlavisEnabled) {+ try {+ const toolState = getToolStoreState();+ const allKlavisServers = klavisStoreSelectors.getServers(toolState);++ const connected: KlavisServiceSummary[] = allKlavisServers+ .filter((s) => s.status === KlavisServerStatus.CONNECTED)+ .map((s) => ({ identifier: s.identifier, name: s.serverName }));++ const connectedIds = new Set(connected.map((s) => s.identifier));+ const available: KlavisServiceSummary[] = KLAVIS_SERVER_TYPES.filter(+ (t) => !connectedIds.has(t.identifier),+ ).map((t) => ({ identifier: t.identifier, name: t.label }));++ klavisServicesList = generateKlavisServicesList(connected, available);+ log(+ 'Klavis services context resolved: connected=%d, available=%d',+ connected.length,+ available.length,+ );+ } catch (error) {+ log('Failed to resolve Klavis services context:', error);+ }+ }+// Resolve cron jobs context for cron tool// Only inject a small preview (up to 4) to save context window;// the model can call listCronJobs API for the full list.@@ -735,6 +775,8 @@ export const contextEngineering = async ({...VARIABLE_GENERATORS,// NOTICE: required by builtin-tool-creds/src/systemRole.tsCREDS_LIST: () => (credsList ? generateCredsList(credsList) : ''),+ // NOTICE: required by builtin-tool-creds/src/systemRole.ts (Klavis integrations)+ KLAVIS_SERVICES_LIST: () => klavisServicesList,// NOTICE: required by builtin-tool-cron/src/systemRole.tsCRON_JOBS_LIST: () => (cronJobsList ? generateCronJobsList(cronJobsList, cronJobsTotal) : ''),// NOTICE(@nekomeowww): required by builtin-tool-memory/src/systemRole.ts