🤯 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(onboarding): add X understanding source (#18118)
Neko393fd751090e
diff --git a/apps/server/src/routers/lambda/__tests__/user.test.ts b/apps/server/src/routers/lambda/__tests__/user.test.tsindex 9da1d7c4a4e..d669b81802e 100644--- a/apps/server/src/routers/lambda/__tests__/user.test.ts+++ b/apps/server/src/routers/lambda/__tests__/user.test.ts@@ -142,7 +142,13 @@ describe('userRouter', () => {await expect(userRouter.createCaller(scopedCtx).getSupportedUnderstandingProviders(),).resolves.toEqual({- providerIds: ['github', 'gmail', 'notion'],+ connectionSources: {+ github: 'composio',+ gmail: 'composio',+ notion: 'composio',+ twitter: 'lobehub',+ },+ providerIds: ['github', 'gmail', 'notion', 'twitter'],sourceProviderIds: ['github'],});});diff --git a/apps/server/src/routers/lambda/user.ts b/apps/server/src/routers/lambda/user.tsindex 6b26459cfe7..e6e436af24e 100644--- a/apps/server/src/routers/lambda/user.ts+++ b/apps/server/src/routers/lambda/user.ts@@ -397,8 +397,17 @@ export const userRouter = router({}),getSupportedUnderstandingProviders: understandingServiceProcedure.query(- async ({ ctx }): Promise<{ providerIds: string[]; sourceProviderIds: string[] }> => {+ async ({+ ctx,+ }): Promise<{+ connectionSources: Record<string, 'composio' | 'lobehub'>;+ providerIds: string[];+ sourceProviderIds: string[];+ }> => {return {+ connectionSources: Object.fromEntries(+ understandingProviders.map((provider) => [provider.id, provider.connectionSource]),+ ),providerIds: understandingProviders.map((provider) => provider.id),sourceProviderIds: await ctx.understandingService.listSourceProviderIds(),};diff --git a/apps/server/src/services/connectorData/index.test.ts b/apps/server/src/services/connectorData/index.test.tsindex 807d797888a..a43c196f61b 100644--- a/apps/server/src/services/connectorData/index.test.ts+++ b/apps/server/src/services/connectorData/index.test.ts@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({createGitHubOAuthClient: vi.fn(),createGmailClient: vi.fn(),createNotionClient: vi.fn(),+ createTwitterClient: vi.fn(),ensureFreshConnectorToken: vi.fn(),findById: vi.fn(),getAccount: vi.fn(),@@ -17,6 +18,8 @@ const mocks = vi.hoisted(() => ({initWithEnvKey: vi.fn(),isComposioLookupNotFound: vi.fn(),markComposioUnavailable: vi.fn(),+ marketCallTool: vi.fn(),+ marketGetStatus: vi.fn(),queryComposioReferences: vi.fn(),queryReferences: vi.fn(),}));@@ -34,6 +37,10 @@ vi.mock('@lobechat/connector-data/notion', () => ({createNotionConnectorClient: mocks.createNotionClient,}));+vi.mock('@lobechat/connector-data/twitter', () => ({+ createTwitterMarketConnectorClient: mocks.createTwitterClient,+}));+vi.mock('@/database/models/connector', () => ({ConnectorModel: vi.fn(() => ({findById: mocks.findById,@@ -53,6 +60,16 @@ vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({vi.mock('@/server/services/connector/tokens', () => ({ensureFreshConnectorToken: mocks.ensureFreshConnectorToken,}));+vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn(() => ({+ market: {+ skills: {+ callTool: mocks.marketCallTool,+ getStatus: mocks.marketGetStatus,+ },+ },+ })),+}));const authDb = (rows: Array<{ accessToken: string | null; accessTokenExpiresAt?: Date | null; id: string }>,@@ -83,9 +100,12 @@ describe('ConnectorDataService', () => {mocks.createGitHubComposioClient.mockReturnValue({ kind: 'github-composio-client' });mocks.createGitHubOAuthClient.mockReturnValue({ kind: 'github-client' });mocks.markComposioUnavailable.mockResolvedValue(false);+ mocks.marketCallTool.mockResolvedValue({ data: { data: [] }, success: true });+ mocks.marketGetStatus.mockResolvedValue({ connected: true, success: true });mocks.getAccount.mockResolvedValue({ externalAccountId: 'gmail-account', scopes: [] });mocks.createGmailClient.mockReturnValue({ getAccount: mocks.getAccount, kind: 'gmail-client' });mocks.createNotionClient.mockReturnValue({ kind: 'notion-client' });+ mocks.createTwitterClient.mockReturnValue({ kind: 'twitter-client' });mocks.queryReferences.mockResolvedValue([]);mocks.queryComposioReferences.mockResolvedValue([]);});@@ -404,9 +424,9 @@ describe('ConnectorDataService', () => {},]);- await expect(- new ConnectorDataService(authDb([]), 'user-1').getNotionClient(),- ).resolves.toEqual({ kind: 'notion-client' });+ await expect(new ConnectorDataService(authDb([]), 'user-1').getNotionClient()).resolves.toEqual(+ { kind: 'notion-client' },+ );expect(mocks.createNotionClient).toHaveBeenCalledWith({composio: expect.objectContaining({ kind: 'composio' }),connectedAccountId: 'notion-account',@@ -414,6 +434,34 @@ describe('ConnectorDataService', () => {});});+ /** @example A connected Market X skill resolves through the registry-backed read-only client. */+ it('creates Twitter from the active Market connector', async () => {+ await expect(+ new ConnectorDataService(authDb([]), 'user-1').getTwitterClient(),+ ).resolves.toEqual({ kind: 'twitter-client' });+ expect(mocks.marketGetStatus).toHaveBeenCalledWith('twitter');+ expect(mocks.createTwitterClient).toHaveBeenCalledWith({+ market: { callTool: expect.any(Function) },+ });++ const [{ market }] = mocks.createTwitterClient.mock.calls[0];+ await market.callTool('search_tweets', { query: 'from:ada' });+ expect(mocks.marketCallTool).toHaveBeenCalledWith('twitter', {+ args: { query: 'from:ada' },+ tool: 'search_tweets',+ });+ });++ /** @example A disconnected Market X skill is not exposed as an available source. */+ it('rejects Twitter when the Market connector is not connected', async () => {+ mocks.marketGetStatus.mockResolvedValue({ connected: false, success: true });++ await expect(+ new ConnectorDataService(authDb([]), 'user-1').getTwitterClient(),+ ).rejects.toMatchObject({ code: 'twitter_authorization_unavailable' });+ expect(mocks.createTwitterClient).not.toHaveBeenCalled();+ });+it('lists only providers whose connector client can currently be resolved', async () => {/** @example A stale Gmail connection is excluded while GitHub OAuth remains available. */const service = new ConnectorDataService(diff --git a/apps/server/src/services/connectorData/index.ts b/apps/server/src/services/connectorData/index.tsindex e93decdfb88..88b265a3f61 100644--- a/apps/server/src/services/connectorData/index.ts+++ b/apps/server/src/services/connectorData/index.ts@@ -12,6 +12,8 @@ import type { GmailConnectorClient } from '@lobechat/connector-data/gmail';import { createGmailConnectorClient } from '@lobechat/connector-data/gmail';import type { NotionConnectorClient } from '@lobechat/connector-data/notion';import { createNotionConnectorClient } from '@lobechat/connector-data/notion';+import type { TwitterConnectorClient } from '@lobechat/connector-data/twitter';+import { createTwitterMarketConnectorClient } from '@lobechat/connector-data/twitter';import { and, eq } from 'drizzle-orm';import { ConnectorModel } from '@/database/models/connector';@@ -20,6 +22,7 @@ import type { LobeChatDatabase } from '@/database/type';import { getComposioClient, isComposioConnectedAccountLookupNotFoundError } from '@/libs/composio';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { ensureFreshConnectorToken } from '@/server/services/connector/tokens';+import { MarketService } from '@/server/services/market';const TOKEN_EXPIRY_SKEW_MS = 60_000;@@ -77,7 +80,7 @@ const isTokenUsable = (expiresAt: Date | number | null | undefined) =>* - The database and user scope come from an authenticated server context** Returns:- * - Provider clients backed by Composio, connector OAuth, or supported account fallback+ * - Provider clients backed by Composio, LobeHub Market, connector OAuth, or account fallback*/export class ConnectorDataService {constructor(@@ -91,6 +94,7 @@ export class ConnectorDataService {github: () => this.getGitHubClient(),gmail: () => this.getGmailClient(),notion: () => this.getNotionClient(),+ twitter: () => this.getTwitterClient(),};return resolvers[providerId]();};@@ -284,4 +288,37 @@ export class ConnectorDataService {}throw unavailable('notion');};++ /**+ * Resolves the current user's LobeHub Market X connection.+ *+ * Use when:+ * - An onboarding collector needs read-only public X profile and recent-post evidence+ *+ * Expects:+ * - Trusted Client authentication is configured for the Market service+ * - The current Market user has connected the `twitter` provider+ *+ * Returns:+ * - A user-scoped X connector client backed by Market skill tools+ */+ getTwitterClient = async (): Promise<TwitterConnectorClient> => {+ const market = new MarketService({+ userInfo: { userId: this.userId, workspaceId: this.workspaceId },+ }).market;+ const status = await market.skills.getStatus('twitter');+ if (!status.success || !status.connected) throw unavailable('twitter');++ return createTwitterMarketConnectorClient({+ market: {+ callTool: async (toolName, arguments_) => {+ const response = await market.skills.callTool('twitter', {+ args: arguments_,+ tool: toolName,+ });+ return { data: response.data, success: response.success };+ },+ },+ });+ };}diff --git a/apps/server/src/services/market/index.test.ts b/apps/server/src/services/market/index.test.tsindex fa0c4022cda..d9d8bada55e 100644--- a/apps/server/src/services/market/index.test.ts+++ b/apps/server/src/services/market/index.test.ts@@ -556,9 +556,9 @@ describe('MarketService', () => {identifier: 'twitter',meta: {avatar: '🐦',- description: 'LobeHub Skill: X (Twitter)',+ description: 'LobeHub Skill: X',tags: ['lobehub-skill', 'twitter'],- title: 'X (Twitter)',+ title: 'X',},type: 'builtin',});diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.tsindex 7d98ec6b7be..090ed921710 100644--- a/apps/server/src/services/market/index.ts+++ b/apps/server/src/services/market/index.ts@@ -653,7 +653,7 @@ export class MarketService {microsoft: 'Outlook Calendar',notion: 'Notion',posthog: 'PostHog',- twitter: 'X (Twitter)',+ twitter: 'X',vercel: 'Vercel',};const providerLabel = PROVIDER_LABELS[providerId] || providerId;diff --git a/apps/server/src/services/taskRecommendation/config.ts b/apps/server/src/services/taskRecommendation/config.tsindex ed47d557eb7..1d9b44bf2f1 100644--- a/apps/server/src/services/taskRecommendation/config.ts+++ b/apps/server/src/services/taskRecommendation/config.ts@@ -61,6 +61,12 @@ export interface NotionTaskRecommendationProviderConfig extends TaskRecommendatistaleWorkspacePrinciples: readonly string[];}+/** X collection policy for recent public post and mention signals. */+export interface TwitterTaskRecommendationProviderConfig extends TaskRecommendationProviderConfig {+ /** Maximum deduplicated recent X records serialized into one recommendation call. */+ maxSignals: number;+}+/** Complete configurable policy for onboarding task generation. */export interface TaskRecommendationConfig {/** Cross-provider recommendation allocation policy. */diff --git a/apps/server/src/services/taskRecommendation/providers/index.ts b/apps/server/src/services/taskRecommendation/providers/index.tsindex 7429bf94f6d..10254d20fae 100644--- a/apps/server/src/services/taskRecommendation/providers/index.ts+++ b/apps/server/src/services/taskRecommendation/providers/index.ts@@ -2,12 +2,14 @@ import type { TaskRecommendationProvider } from '../types';import { createGitHubTaskRecommendationProvider } from './github';import { createGmailTaskRecommendationProvider } from './gmail';import { createNotionTaskRecommendationProvider } from './notion';+import { createTwitterTaskRecommendationProvider } from './twitter';/** Independent connector providers used by the onboarding task workflow. */export const taskRecommendationProviders = [createGitHubTaskRecommendationProvider(),createGmailTaskRecommendationProvider(),createNotionTaskRecommendationProvider(),+ createTwitterTaskRecommendationProvider(),] as const satisfies readonly TaskRecommendationProvider[];/** Provider registry used for connector validation and workflow dispatch. */diff --git a/apps/server/src/services/taskRecommendation/providers/twitter.test.ts b/apps/server/src/services/taskRecommendation/providers/twitter.test.tsnew file mode 100644index 00000000000..8063d664dc9--- /dev/null+++ b/apps/server/src/services/taskRecommendation/providers/twitter.test.ts@@ -0,0 +1,105 @@+// @vitest-environment node+import { ConnectorDataError } from '@lobechat/connector-data';+import type { TwitterPost, TwitterProfile } from '@lobechat/connector-data/twitter';+import { describe, expect, it, vi } from 'vitest';++import { createTwitterTaskRecommendationProvider } from './twitter';++const profile: TwitterProfile = {+ id: '42',+ metrics: {},+ name: 'Ada',+ sourceUrl: 'https://x.com/ada',+ username: 'ada',+};+const authoredPost: TwitterPost = {+ authorId: '42',+ authorUsername: 'ada',+ id: '100',+ metrics: { replyCount: 2 },+ referencedPostTypes: [],+ sourceUrl: 'https://x.com/ada/status/100',+ text: 'We shipped the new connector.',+};+const mention: TwitterPost = {+ authorId: '7',+ authorUsername: 'reader',+ id: '101',+ metrics: {},+ referencedPostTypes: [],+ sourceUrl: 'https://x.com/reader/status/101',+ text: '@ada Could you share an example?',+};++/** @example X recommendations stay read-only and grounded in exact public post URLs. */+describe('createTwitterTaskRecommendationProvider', () => {+ /** @example Recent authored posts and mentions become distinct trusted task signals. */+ it('collects recent activity with titled X sources', async () => {+ const searchRecentPosts = vi+ .fn()+ .mockResolvedValueOnce([authoredPost])+ .mockResolvedValueOnce([mention]);+ const provider = createTwitterTaskRecommendationProvider();+ const result = await provider.collect({+ connectorData: {+ getTwitterClient: vi.fn(async () => ({+ getProfile: vi.fn(async () => profile),+ searchRecentPosts,+ })),+ },+ } as never);++ expect(result).toMatchObject({+ diagnostics: { evidenceCount: 2, failedCount: 0, succeededCount: 3 },+ signalCount: 2,+ sources: [+ {+ title: 'We shipped the new connector.',+ type: 'twitter',+ url: 'https://x.com/ada/status/100',+ },+ {+ title: '@ada Could you share an example?',+ type: 'twitter',+ url: 'https://x.com/reader/status/101',+ },+ ],+ });+ expect(result.context).toContain('"kind": "authored_post"');+ expect(result.context).toContain('"kind": "mention"');+ expect(provider.guide.principles.join('\n')).toContain('Never post, reply, like, repost');+ });++ /** @example A failed mention query remains partial while authored-post tasks stay available. */+ it('retains successful signals when one recent search fails', async () => {+ const searchRecentPosts = vi+ .fn()+ .mockResolvedValueOnce([authoredPost])+ .mockRejectedValueOnce(+ new ConnectorDataError({+ code: 'twitter_search_failed',+ operation: 'searchRecentPosts',+ provider: 'twitter',+ retryable: true,+ }),+ );+ const provider = createTwitterTaskRecommendationProvider();+ const result = await provider.collect({+ connectorData: {+ getTwitterClient: vi.fn(async () => ({+ getProfile: vi.fn(async () => profile),+ searchRecentPosts,+ })),+ },+ } as never);++ expect(result).toMatchObject({+ diagnostics: {+ errors: [{ operation: 'mention', retryable: true }],+ evidenceCount: 1,+ failedCount: 1,+ },+ signalCount: 1,+ });+ });+});diff --git a/apps/server/src/services/taskRecommendation/providers/twitter.ts b/apps/server/src/services/taskRecommendation/providers/twitter.tsnew file mode 100644index 00000000000..e2b4adda493--- /dev/null+++ b/apps/server/src/services/taskRecommendation/providers/twitter.ts@@ -0,0 +1,115 @@+import { ConnectorDataError } from '@lobechat/connector-data';+import type { TwitterPost } from '@lobechat/connector-data/twitter';+import { DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG } from '@lobechat/prompts';+import type { OnboardingTaskSource } from '@lobechat/types';++import type { TwitterTaskRecommendationProviderConfig } from '../config';+import type { TaskRecommendationProvider } from '../types';++interface TwitterSignal {+ kind: 'authored_post' | 'mention';+ post: TwitterPost;+}++/**+ * Creates the independent X task recommendation collector.+ *+ * Use when:+ * - The onboarding task workflow needs recent public post and mention signals+ * - Tests or product tuning need to inject a bounded X collection policy+ *+ * Expects:+ * - A read-only X connector available through Connector Data+ * - Prompt guidance that keeps all social side effects behind later user approval+ *+ * Returns:+ * - A registry-ready provider that emits grounded public post URLs and bounded evidence+ */+export const createTwitterTaskRecommendationProvider = (+ config: TwitterTaskRecommendationProviderConfig = {+ ...DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.providers.twitter,+ maxContextLength: 24_000,+ maxSignals: 32,+ },+): TaskRecommendationProvider => ({+ id: 'twitter',+ guide: { examples: config.examples, principles: config.principles },+ collect: async ({ connectorData }) => {+ const client = await connectorData.getTwitterClient();+ const profile = await client.getProfile();+ const searches = [+ {+ kind: 'authored_post',+ query: `from:${profile.username} -is:retweet`,+ },+ {+ kind: 'mention',+ query: `@${profile.username} -from:${profile.username} -is:retweet`,+ },+ ] as const;+ const maxResults = Math.max(10, Math.ceil(config.maxSignals / searches.length));+ const settled = await Promise.allSettled(+ searches.map(({ query }) => client.searchRecentPosts({ maxResults, query })),+ );+ const errors = settled.flatMap((result, index) =>+ result.status === 'rejected'+ ? [+ {+ code: 'TWITTER_TASK_SIGNAL_COLLECTION_FAILED',+ message: 'X task signal collection failed',+ operation: searches[index].kind,+ provider: 'twitter',+ retryable:+ result.reason instanceof ConnectorDataError ? result.reason.retryable : true,+ },+ ]+ : [],+ );+ const candidates = settled.flatMap((result, index): TwitterSignal[] =>+ result.status === 'fulfilled'+ ? result.value.map((post) => ({ kind: searches[index].kind, post }))+ : [],+ );+ const signals = [+ ...new Map(candidates.map((signal) => [signal.post.id, signal])).values(),+ ].slice(0, config.maxSignals);+ const sources = [+ ...new Map(+ signals.map(({ post }) => [+ post.sourceUrl,+ {+ title: post.text.replaceAll(/\s+/g, ' ').slice(0, 160),+ type: 'twitter',+ url: post.sourceUrl,+ } satisfies OnboardingTaskSource,+ ]),+ ).values(),+ ];++ return {+ context: JSON.stringify(+ {+ profile: {+ description: profile.description,+ name: profile.name,+ sourceUrl: profile.sourceUrl,+ username: profile.username,+ },+ provider: 'twitter',+ recentSearchWindowDays: 7,+ signals,+ },+ null,+ 2,+ ).slice(0, config.maxContextLength),+ diagnostics: {+ errors,+ evidenceCount: signals.length,+ failedCount: errors.length,+ succeededCount: 1 + settled.filter(({ status }) => status === 'fulfilled').length,+ },+ signalCount: signals.length,+ sources,+ };+ },+});diff --git a/apps/server/src/services/understanding/providers/github.ts b/apps/server/src/services/understanding/providers/github.tsindex bcf335e5a91..0aa7bce7477 100644--- a/apps/server/src/services/understanding/providers/github.ts+++ b/apps/server/src/services/understanding/providers/github.ts@@ -12,6 +12,7 @@ interface SupplementalOperation {}export const githubUnderstandingProvider: UnderstandingProvider = {+ connectionSource: 'composio',id: 'github',collect: async ({ connectorData }) => {const client = await connectorData.getGitHubClient();diff --git a/apps/server/src/services/understanding/providers/gmail.ts b/apps/server/src/services/understanding/providers/gmail.tsindex 8601cd3d630..983d70bd7f0 100644--- a/apps/server/src/services/understanding/providers/gmail.ts+++ b/apps/server/src/services/understanding/providers/gmail.ts@@ -74,6 +74,7 @@ const selectContextMessages = (messages: GmailMessage[]) => {export const GMAIL_PROFILE_QUERIES = GMAIL_PROFILE_SEARCHES.map(({ query }) => query);export const gmailUnderstandingProvider: UnderstandingProvider = {+ connectionSource: 'composio',id: 'gmail',collect: async ({ connectorData }) => {const client = await connectorData.getGmailClient();diff --git a/apps/server/src/services/understanding/providers/index.ts b/apps/server/src/services/understanding/providers/index.tsindex 1ba7b79716e..5592d4d847d 100644--- a/apps/server/src/services/understanding/providers/index.ts+++ b/apps/server/src/services/understanding/providers/index.ts@@ -2,15 +2,22 @@ import type { UnderstandingProvider } from '../types';import { githubUnderstandingProvider } from './github';import { gmailUnderstandingProvider } from './gmail';import { notionUnderstandingProvider } from './notion';+import { twitterUnderstandingProvider } from './twitter';export const understandingProviders = [githubUnderstandingProvider,gmailUnderstandingProvider,notionUnderstandingProvider,+ twitterUnderstandingProvider,] as const satisfies readonly UnderstandingProvider[];export const understandingProviderMap = new Map<string, UnderstandingProvider>(understandingProviders.map((provider) => [provider.id, provider]),);-export { githubUnderstandingProvider, gmailUnderstandingProvider, notionUnderstandingProvider };+export {+ githubUnderstandingProvider,+ gmailUnderstandingProvider,+ notionUnderstandingProvider,+ twitterUnderstandingProvider,+};diff --git a/apps/server/src/services/understanding/providers/notion.ts b/apps/server/src/services/understanding/providers/notion.tsindex 701a004848f..1889577a3ea 100644--- a/apps/server/src/services/understanding/providers/notion.ts+++ b/apps/server/src/services/understanding/providers/notion.ts@@ -39,6 +39,7 @@ const serializeContext = (items: NotionItemContent[]): string =>* - A bounded source brief that remains usable when individual page reads fail*/export const notionUnderstandingProvider: UnderstandingProvider = {+ connectionSource: 'composio',id: 'notion',collect: async ({ connectorData }) => {const client = await connectorData.getNotionClient();@@ -53,7 +54,9 @@ export const notionUnderstandingProvider: UnderstandingProvider = {const contentCandidates = items.filter(({ kind }) => kind === 'page')- .toSorted((left, right) => editTime(right) - editTime(left) || left.id.localeCompare(right.id))+ .toSorted(+ (left, right) => editTime(right) - editTime(left) || left.id.localeCompare(right.id),+ ).slice(0, MAX_CONTENT_PAGES);const settledContent = await Promise.allSettled(contentCandidates.map(({ id }) => client.getPageMarkdown(id)),@@ -70,8 +73,7 @@ export const notionUnderstandingProvider: UnderstandingProvider = {message: 'Notion page content enrichment failed',operation: 'page_content',provider: 'notion',- retryable:- result.reason instanceof ConnectorDataError ? result.reason.retryable : true,+ retryable: result.reason instanceof ConnectorDataError ? result.reason.retryable : true,},];});@@ -93,8 +95,7 @@ export const notionUnderstandingProvider: UnderstandingProvider = {errors,evidenceCount: sourceCount,failedCount: errors.length,- succeededCount:- 1 + settledContent.filter(({ status }) => status === 'fulfilled').length,+ succeededCount: 1 + settledContent.filter(({ status }) => status === 'fulfilled').length,},sourceCount,};diff --git a/apps/server/src/services/understanding/providers/twitter.test.ts b/apps/server/src/services/understanding/providers/twitter.test.tsnew file mode 100644index 00000000000..ed5fdf2cb43--- /dev/null+++ b/apps/server/src/services/understanding/providers/twitter.test.ts@@ -0,0 +1,94 @@+import { ConnectorDataError } from '@lobechat/connector-data';+import type { TwitterPost, TwitterProfile } from '@lobechat/connector-data/twitter';+import { describe, expect, it, vi } from 'vitest';++import { twitterUnderstandingProvider } from './twitter';++const profile: TwitterProfile = {+ description: 'Building developer tools',+ id: '42',+ metrics: {},+ name: 'Ada',+ sourceUrl: 'https://x.com/ada',+ username: 'ada',+};+const authoredPost: TwitterPost = {+ authorId: '42',+ authorUsername: 'ada',+ id: '100',+ metrics: { likeCount: 3 },+ referencedPostTypes: [],+ sourceUrl: 'https://x.com/ada/status/100',+ text: 'We shipped the new connector.',+};+const mention: TwitterPost = {+ authorId: '7',+ authorUsername: 'reader',+ id: '101',+ metrics: {},+ referencedPostTypes: [],+ sourceUrl: 'https://x.com/reader/status/101',+ text: '@ada Could you share an example?',+};++/** @example X public evidence enriches Understanding while preserving authorship boundaries. */+describe('twitterUnderstandingProvider', () => {+ /** @example A pinned recent post is counted once while third-party mentions remain distinct. */+ it('collects profile, authored posts, and mentions without duplicating the pinned post', async () => {+ const searchRecentPosts = vi+ .fn()+ .mockResolvedValueOnce([authoredPost])+ .mockResolvedValueOnce([mention]);+ const result = await twitterUnderstandingProvider.collect({+ connectorData: {+ getTwitterClient: vi.fn(async () => ({+ getProfile: vi.fn(async () => ({ ...profile, pinnedPost: authoredPost })),+ searchRecentPosts,+ })),+ } as never,+ userId: 'user-1',+ });++ expect(result).toMatchObject({+ diagnostics: { evidenceCount: 3, failedCount: 0, succeededCount: 3 },+ sourceCount: 3,+ });+ expect(result.context).toContain('We shipped the new connector.');+ expect(result.context).toContain('@ada Could you share an example?');+ expect(result.context).toContain('Mentions, replies, and engagement counts');+ expect(result.context).toContain('latest seven days');+ });++ /** @example One failed recent search remains partial while profile and other activity stay usable. */+ it('retains profile and authored posts when mention search fails', async () => {+ const searchRecentPosts = vi+ .fn()+ .mockResolvedValueOnce([authoredPost])+ .mockRejectedValueOnce(+ new ConnectorDataError({+ code: 'twitter_search_failed',+ operation: 'searchRecentPosts',+ provider: 'twitter',+ retryable: true,+ }),+ );+ const result = await twitterUnderstandingProvider.collect({+ connectorData: {+ getTwitterClient: vi.fn(async () => ({+ getProfile: vi.fn(async () => profile),+ searchRecentPosts,+ })),+ } as never,+ userId: 'user-1',+ });++ expect(result).toMatchObject({+ diagnostics: {+ errors: [{ operation: 'mentions', retryable: true }],+ evidenceCount: 2,+ failedCount: 1,+ },+ sourceCount: 2,+ });+ });+});diff --git a/apps/server/src/services/understanding/providers/twitter.ts b/apps/server/src/services/understanding/providers/twitter.tsnew file mode 100644index 00000000000..adb4e1c5cf3--- /dev/null+++ b/apps/server/src/services/understanding/providers/twitter.ts@@ -0,0 +1,110 @@+import { ConnectorDataError } from '@lobechat/connector-data';+import type { TwitterPost } from '@lobechat/connector-data/twitter';++import type { UnderstandingProvider } from '../types';++const MAX_RECENT_POSTS = 25;++interface TwitterActivityCollection {+ errors: Array<{+ code: string;+ message: string;+ operation: string;+ provider: 'twitter';+ retryable: boolean;+ }>;+ mentions: TwitterPost[];+ posts: TwitterPost[];+ succeededCount: number;+}++const collectRecentActivity = async (+ searchRecentPosts: (input: { maxResults?: number; query: string }) => Promise<TwitterPost[]>,+ username: string,+): Promise<TwitterActivityCollection> => {+ const searches = [+ { kind: 'posts', query: `from:${username} -is:retweet` },+ { kind: 'mentions', query: `@${username} -from:${username} -is:retweet` },+ ] as const;+ const settled = await Promise.allSettled(+ searches.map(({ query }) => searchRecentPosts({ maxResults: MAX_RECENT_POSTS, query })),+ );+ const errors = settled.flatMap((result, index) =>+ result.status === 'rejected'+ ? [+ {+ code: 'TWITTER_RECENT_ACTIVITY_FAILED',+ message: 'X recent activity collection failed',+ operation: searches[index].kind,+ provider: 'twitter' as const,+ retryable: result.reason instanceof ConnectorDataError ? result.reason.retryable : true,+ },+ ]+ : [],+ );+ return {+ errors,+ mentions: settled[1].status === 'fulfilled' ? settled[1].value : [],+ posts: settled[0].status === 'fulfilled' ? settled[0].value : [],+ succeededCount: settled.filter(({ status }) => status === 'fulfilled').length,+ };+};++/**+ * Collects public profile and recent activity evidence for onboarding Understanding.+ *+ * Use when:+ * - A connected X account participates in the onboarding Understanding session+ *+ * Expects:+ * - Connector Data has resolved the current user's read-only Market X connection+ *+ * Returns:+ * - A bounded source brief that separates authored posts from third-party mentions+ */+export const twitterUnderstandingProvider: UnderstandingProvider = {+ connectionSource: 'lobehub',+ id: 'twitter',+ collect: async ({ connectorData }) => {+ const client = await connectorData.getTwitterClient();+ const profile = await client.getProfile();+ const activity = await collectRecentActivity(client.searchRecentPosts, profile.username);+ const posts = [+ ...new Map(+ activity.posts+ .filter(({ id }) => id !== profile.pinnedPost?.id)+ .map((post) => [post.id, post]),+ ).values(),+ ];+ const authoredPostIds = new Set(posts.map(({ id }) => id));+ const mentions = [+ ...new Map(+ activity.mentions+ .filter(({ id }) => !authoredPostIds.has(id))+ .map((post) => [post.id, post]),+ ).values(),+ ];+ const evidenceCount = 1 + posts.length + mentions.length + (profile.pinnedPost ? 1 : 0);++ return {+ context: [+ 'Provider: twitter',+ '# Source Brief',+ 'X evidence policy:',+ '- The profile bio and authored posts are public self-presentation signals, not proof of a current job, project, or commitment.',+ '- A pinned post may be intentionally persistent and old; do not treat it as recent activity unless its timestamp establishes recency.',+ '- Mentions, replies, and engagement counts indicate public attention, not an obligation to respond or evidence that the user agrees.',+ '- Keep authored posts distinct from third-party mentions and do not infer sensitive traits, private relationships, or off-platform intent.',+ '- Recent search covers only the latest seven days, so missing topics or activity must not be treated as evidence of absence.',+ JSON.stringify({ mentions, posts, profile, provider: 'twitter' }, null, 2),+ ].join('\n\n'),+ diagnostics: {+ errors: activity.errors,+ evidenceCount,+ failedCount: activity.errors.length,+ succeededCount: 1 + activity.succeededCount,+ },+ sourceCount: evidenceCount,+ };+ },+};diff --git a/apps/server/src/services/understanding/service.test.ts b/apps/server/src/services/understanding/service.test.tsindex 5cdba200414..5c2e80a238f 100644--- a/apps/server/src/services/understanding/service.test.ts+++ b/apps/server/src/services/understanding/service.test.ts@@ -111,7 +111,11 @@ const createHarness = (initialSession?: OnboardingUnderstandingSession) => {diagnostics,sourceCount: 3,}));- providers.set('github', { collect: githubCollect, id: 'github' });+ providers.set('github', {+ collect: githubCollect,+ connectionSource: 'composio',+ id: 'github',+ });providers.set('gmail', {collect: vi.fn(async () => ({context:@@ -119,6 +123,7 @@ const createHarness = (initialSession?: OnboardingUnderstandingSession) => {diagnostics,sourceCount: 3,})),+ connectionSource: 'composio',id: 'gmail',});diff --git a/apps/server/src/services/understanding/types.ts b/apps/server/src/services/understanding/types.tsindex 8d9da227720..f62395057bf 100644--- a/apps/server/src/services/understanding/types.ts+++ b/apps/server/src/services/understanding/types.ts@@ -2,16 +2,27 @@ import type { CollectionDiagnostics } from '@lobechat/types';import type { ConnectorDataService } from '@/server/services/connectorData';+/** Evidence and collection metadata returned by one Understanding provider. */export interface CollectedUnderstandingProviderContext {+ /** Prompt-ready evidence collected from the provider. */context: string;+ /** Structured diagnostics for partial or failed collection attempts. */diagnostics: CollectionDiagnostics;+ /** Number of source records represented in {@link context}. */sourceCount: number;}+/** Connection system used by onboarding to authorize one Understanding provider. */+export type UnderstandingProviderConnectionSource = 'composio' | 'lobehub';++/** Registry contract for a provider that contributes onboarding Understanding evidence. */export interface UnderstandingProvider {+ /** Collects prompt-ready evidence for the current user. */collect: (input: {connectorData: ConnectorDataService;userId: string;}) => Promise<CollectedUnderstandingProviderContext>;+ /** Frontend connection system that owns this provider's OAuth lifecycle. */+ readonly connectionSource: UnderstandingProviderConnectionSource;readonly id: string;}diff --git a/packages/connector-data/package.json b/packages/connector-data/package.jsonindex c2d221dbc4e..0a98b3a25d2 100644--- a/packages/connector-data/package.json+++ b/packages/connector-data/package.json@@ -19,6 +19,10 @@"./notion": {"types": "./src/notion/index.ts","default": "./src/notion/index.ts"+ },+ "./twitter": {+ "types": "./src/twitter/index.ts",+ "default": "./src/twitter/index.ts"}},"main": "./src/index.ts",diff --git a/packages/connector-data/src/providers.ts b/packages/connector-data/src/providers.tsindex 4482dba8cf2..bdaa937a582 100644--- a/packages/connector-data/src/providers.ts+++ b/packages/connector-data/src/providers.ts@@ -1,5 +1,5 @@/** Provider identifiers with a first-party Connector Data client. */-export const CONNECTOR_DATA_PROVIDER_IDS = ['github', 'gmail', 'notion'] as const;+export const CONNECTOR_DATA_PROVIDER_IDS = ['github', 'gmail', 'notion', 'twitter'] as const;/** Provider identifier accepted by Connector Data errors and client resolution. */export type ConnectorDataProvider = (typeof CONNECTOR_DATA_PROVIDER_IDS)[number];diff --git a/packages/connector-data/src/twitter/index.ts b/packages/connector-data/src/twitter/index.tsnew file mode 100644index 00000000000..51aa50722ca--- /dev/null+++ b/packages/connector-data/src/twitter/index.ts@@ -0,0 +1,3 @@+export * from './marketClient';+export * from './parser';+export * from './types';diff --git a/packages/connector-data/src/twitter/marketClient.test.ts b/packages/connector-data/src/twitter/marketClient.test.tsnew file mode 100644index 00000000000..da77a91ffcd--- /dev/null+++ b/packages/connector-data/src/twitter/marketClient.test.ts@@ -0,0 +1,98 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ConnectorDataError } from '../errors';+import { createTwitterMarketConnectorClient } from './marketClient';++const mocks = vi.hoisted(() => ({+ log: vi.fn(),+}));++vi.mock('debug', () => ({+ default: vi.fn(() => mocks.log),+}));++const createClient = (callTool: ReturnType<typeof vi.fn>) =>+ createTwitterMarketConnectorClient({ market: { callTool } });++/** @example Market X tools provide bounded profile and recent-post evidence. */+describe('createTwitterMarketConnectorClient', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ /** @example Profile and search calls use the Market X tool contract. */+ it('loads the authenticated profile and recent posts', async () => {+ const callTool = vi+ .fn()+ .mockResolvedValueOnce({+ data: { data: { id: '42', name: 'Ada', username: 'ada' } },+ success: true,+ })+ .mockResolvedValueOnce({+ data: { data: [{ author_id: '42', id: '100', text: 'Hello' }] },+ success: true,+ });+ const client = createClient(callTool);++ await expect(client.getProfile()).resolves.toMatchObject({ username: 'ada' });+ await expect(+ client.searchRecentPosts({ maxResults: 1, query: 'from:ada -is:retweet' }),+ ).resolves.toHaveLength(1);+ expect(callTool).toHaveBeenNthCalledWith(+ 1,+ 'get_me',+ expect.objectContaining({ userFields: expect.arrayContaining(['description']) }),+ );+ expect(callTool).toHaveBeenNthCalledWith(+ 2,+ 'search_tweets',+ expect.objectContaining({+ maxResults: 10,+ query: 'from:ada -is:retweet',+ sortOrder: 'recency',+ }),+ );+ });++ /** @example An embedded HTTP 402 records a safe credits-depleted diagnostic. */+ it('logs the safe reason for embedded Market tool failures', async () => {+ // ROOT CAUSE:+ //+ // Market reports a successful transport envelope while embedding the X provider failure in+ // `data.isError` and `data.statusCode`. The connector rejected the result correctly, but it+ // discarded the provider reason, so Understanding only exposed a generic collection failure.+ //+ // Before: `{ success: true, data: { isError: true, statusCode: 402, error: '...' } }`+ // became an untraceable `twitter_searchRecentPosts_failed`.+ //+ // We now log a bounded `credits_depleted` reason and status without retaining the raw message.+ const client = createClient(+ vi.fn(async () => ({+ data: {+ error: 'Twitter API Error: credits depleted (HTTP 402); token=secret',+ isError: true,+ statusCode: 402,+ },+ success: true,+ })),+ );++ const error = await client+ .searchRecentPosts({ query: 'from:ada -is:retweet' })+ .catch((reason) => reason);++ expect(error).toBeInstanceOf(ConnectorDataError);+ expect(error).toMatchObject({+ code: 'twitter_searchRecentPosts_failed',+ operation: 'searchRecentPosts',+ retryable: false,+ });+ expect(mocks.log).toHaveBeenCalledWith('Market X tool call failed: %O', {+ operation: 'searchRecentPosts',+ reason: 'credits_depleted',+ statusCode: 402,+ toolName: 'search_tweets',+ });+ expect(JSON.stringify(mocks.log.mock.calls)).not.toContain('token=secret');+ });+});diff --git a/packages/connector-data/src/twitter/marketClient.ts b/packages/connector-data/src/twitter/marketClient.tsnew file mode 100644index 00000000000..86ca88e4cce--- /dev/null+++ b/packages/connector-data/src/twitter/marketClient.ts@@ -0,0 +1,186 @@+import { toRecord } from '@lobechat/utils/object';+import debug from 'debug';++import { ConnectorDataError } from '../errors';+import { withConnectorRetry } from '../retry';+import { parseTwitterPosts, parseTwitterProfile } from './parser';+import type { TwitterConnectorClient } from './types';++const DEFAULT_MAX_RESULTS = 25;+const MAX_QUERY_LENGTH = 512;+const PROFILE_TOOL_NAME = 'get_me';+const RECENT_SEARCH_TOOL_NAME = 'search_tweets';+const log = debug('lobe-server:connector-data:twitter');++interface TwitterMarketToolFailure {+ reason: string;+ statusCode?: number;+}++/** Maps an untrusted provider error to a bounded, non-sensitive diagnostic reason. */+const readSafeToolFailureReason = (error: string, statusCode?: number): string => {+ const normalizedError = error.toLowerCase();+ if (normalizedError.includes('credits depleted')) return 'credits_depleted';+ if (normalizedError.includes('token expired')) return 'token_expired';+ if (normalizedError.includes('not connected')) return 'not_connected';+ if (normalizedError.includes('rate limit') || statusCode === 429) return 'rate_limited';+ if (statusCode === 402) return 'payment_required';++ return 'upstream_error';+};++/** Result returned by one Market X tool execution. */+export interface TwitterMarketToolResult {+ /** Provider response payload, when execution reached the provider. */+ data?: unknown;+ /** Whether Market accepted and completed the tool invocation. */+ success: boolean;+}++/** Minimal Market tool executor required by the read-only X connector. */+export interface TwitterMarketToolExecutor {+ /** Executes one tool against the current user's Market X connection. */+ callTool: (+ toolName: string,+ arguments_: Record<string, unknown>,+ ) => Promise<TwitterMarketToolResult>;+}++/** Options for creating a Market-backed X connector client. */+export interface CreateTwitterMarketConnectorClientOptions {+ /** User-scoped Market tool executor authenticated through Trusted Client or OAuth. */+ market: TwitterMarketToolExecutor;+}++/**+ * Extracts a bounded diagnostic from an embedded Market X tool error.+ *+ * The upstream message is intentionally mapped to a safe reason instead of being logged verbatim,+ * because provider errors may include credentials or user content.+ */+const readEmbeddedToolFailure = (value: unknown): TwitterMarketToolFailure | undefined => {+ const record = toRecord(value);+ if (!record) return;+ const statusCode =+ typeof record.statusCode === 'number' && Number.isFinite(record.statusCode)+ ? record.statusCode+ : undefined;+ if (record.isError !== true && (statusCode === undefined || statusCode < 400)) return;++ const error = typeof record.error === 'string' ? record.error : '';+ const reason = readSafeToolFailureReason(error, statusCode);++ return { reason, ...(statusCode === undefined ? {} : { statusCode }) };+};++/**+ * Creates a bounded, read-only X client over LobeHub Market tools.+ *+ * Use when:+ * - Understanding should reuse the user's existing LobeHub Market X authorization+ * - Background workflows need X evidence through Trusted Client authentication+ *+ * Expects:+ * - `market` executes tools for an already-connected `twitter` provider+ * - Tool responses follow the Market skill result contract+ *+ * Returns:+ * - A client that normalizes Market response variants and sanitizes provider failures+ */+export const createTwitterMarketConnectorClient = ({+ market,+}: CreateTwitterMarketConnectorClientOptions): TwitterConnectorClient => {+ const execute = async (+ toolName: string,+ operation: string,+ arguments_: Record<string, unknown>,+ ) =>+ withConnectorRetry(+ async () => {+ const response = await market.callTool(toolName, arguments_);+ const failure = readEmbeddedToolFailure(response.data);+ if (response.success !== true || failure) {+ log('Market X tool call failed: %O', {+ operation,+ reason: failure?.reason ?? 'market_call_unsuccessful',+ ...(failure?.statusCode === undefined ? {} : { statusCode: failure.statusCode }),+ toolName,+ });+ throw new ConnectorDataError({+ code: `twitter_${operation}_failed`,+ operation,+ provider: 'twitter',+ retryable: false,+ });+ }+ return response.data;+ },+ { code: `twitter_${operation}_failed`, operation, provider: 'twitter' },+ );++ return {+ getProfile: async () => {+ const response = await execute(PROFILE_TOOL_NAME, 'getProfile', {+ userFields: [+ 'created_at',+ 'description',+ 'location',+ 'pinned_tweet_id',+ 'profile_image_url',+ 'public_metrics',+ 'url',+ 'verified',+ ],+ });+ const profile = parseTwitterProfile(response);+ if (!profile) {+ throw new ConnectorDataError({+ code: 'twitter_response_invalid',+ operation: 'getProfile',+ provider: 'twitter',+ retryable: false,+ });+ }+ return profile;+ },+ searchRecentPosts: async ({ maxResults = DEFAULT_MAX_RESULTS, query }) => {+ const normalizedQuery = query.trim().slice(0, MAX_QUERY_LENGTH);+ if (!normalizedQuery) {+ throw new ConnectorDataError({+ code: 'twitter_query_invalid',+ operation: 'searchRecentPosts',+ provider: 'twitter',+ retryable: false,+ });+ }+ const finiteMaxResults = Number.isFinite(maxResults) ? maxResults : DEFAULT_MAX_RESULTS;+ // X recent search accepts 10-100 results per request; clamp before calling Market.+ const boundedMaxResults = Math.min(Math.max(10, Math.floor(finiteMaxResults)), 100);+ const response = await execute(RECENT_SEARCH_TOOL_NAME, 'searchRecentPosts', {+ expansions: ['author_id'],+ maxResults: boundedMaxResults,+ query: normalizedQuery,+ sortOrder: 'recency',+ tweetFields: [+ 'author_id',+ 'conversation_id',+ 'created_at',+ 'in_reply_to_user_id',+ 'public_metrics',+ 'referenced_tweets',+ ],+ userFields: ['username'],+ });+ const posts = parseTwitterPosts(response, boundedMaxResults);+ if (!posts) {+ throw new ConnectorDataError({+ code: 'twitter_response_invalid',+ operation: 'searchRecentPosts',+ provider: 'twitter',+ retryable: false,+ });+ }+ return posts;+ },+ };+};diff --git a/packages/connector-data/src/twitter/parser.test.ts b/packages/connector-data/src/twitter/parser.test.tsnew file mode 100644index 00000000000..834cf3d889a--- /dev/null+++ b/packages/connector-data/src/twitter/parser.test.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from 'vitest';++import { parseTwitterPosts, parseTwitterProfile } from './parser';++/** @example Market X responses become bounded, source-addressable public evidence. */+describe('X response parsers', () => {+ /** @example Authenticated profile metadata retains a canonical URL and expanded pinned post. */+ it('normalizes a wrapped profile and pinned post', () => {+ expect(+ parseTwitterProfile({+ data: {+ data: {+ created_at: '2020-01-01T00:00:00.000Z',+ description: 'Building useful tools',+ id: '42',+ name: 'Ada',+ pinned_tweet_id: '100',+ public_metrics: { followers_count: 12, tweet_count: 34 },+ username: 'ada',+ verified: true,+ },+ includes: {+ tweets: [+ {+ author_id: '42',+ created_at: '2026-08-01T00:00:00.000Z',+ id: '100',+ text: 'Pinned launch notes',+ },+ ],+ users: [{ id: '42', username: 'ada' }],+ },+ },+ }),+ ).toEqual({+ createdAt: '2020-01-01T00:00:00.000Z',+ description: 'Building useful tools',+ id: '42',+ metrics: { followersCount: 12, postCount: 34 },+ name: 'Ada',+ pinnedPost: {+ authorId: '42',+ authorUsername: 'ada',+ createdAt: '2026-08-01T00:00:00.000Z',+ id: '100',+ metrics: {},+ referencedPostTypes: [],+ sourceUrl: 'https://x.com/ada/status/100',+ text: 'Pinned launch notes',+ },+ sourceUrl: 'https://x.com/ada',+ username: 'ada',+ verified: true,+ });+ });++ /** @example Recent-search posts resolve expanded authors and public engagement counters. */+ it('normalizes wrapped recent-search posts', () => {+ expect(+ parseTwitterPosts(+ {+ data: {+ data: [+ {+ author_id: '7',+ conversation_id: '200',+ created_at: '2026-08-09T12:00:00Z',+ id: '200',+ public_metrics: { like_count: 5, reply_count: 2, retweet_count: 1 },+ referenced_tweets: [{ id: '199', type: 'replied_to' }],+ text: 'Could you share the migration notes?',+ },+ ],+ includes: { users: [{ id: '7', username: 'reader' }] },+ },+ },+ 10,+ ),+ ).toEqual([+ {+ authorId: '7',+ authorUsername: 'reader',+ conversationId: '200',+ createdAt: '2026-08-09T12:00:00.000Z',+ id: '200',+ metrics: { likeCount: 5, replyCount: 2, repostCount: 1 },+ referencedPostTypes: ['replied_to'],+ sourceUrl: 'https://x.com/reader/status/200',+ text: 'Could you share the migration notes?',+ },+ ]);+ });++ /** @example X recent-search metadata with zero results becomes valid empty evidence. */+ it('normalizes an explicit zero-result response', () => {+ // ROOT CAUSE:+ //+ // X omits the `data` collection when a recent search has no matching posts and returns only+ // `{ meta: { result_count: 0 } }`. Treating every missing collection as malformed made a+ // successful empty search count as a failed Understanding source operation.+ //+ // Before: parseTwitterPosts({ data: { meta: { result_count: 0 } } }, 10) returned undefined.+ // After: the explicit zero-result metadata is normalized to an empty post collection.+ expect(parseTwitterPosts({ data: { meta: { result_count: 0 } } }, 10)).toEqual([]);+ });++ /** @example A non-empty malformed collection is rejected instead of becoming empty evidence. */+ it('rejects a recent-search collection with no valid posts', () => {+ expect(parseTwitterPosts({ data: { data: [{ unexpected: true }] } }, 10)).toBeUndefined();+ });++ /** @example An invalid handle cannot inject operators into later recent-search queries. */+ it('rejects a profile whose username is not an X handle', () => {+ expect(+ parseTwitterProfile({+ data: { data: { id: '42', name: 'Ada', username: 'ada OR from:someone_else' } },+ }),+ ).toBeUndefined();+ });+});diff --git a/packages/connector-data/src/twitter/parser.ts b/packages/connector-data/src/twitter/parser.tsnew file mode 100644index 00000000000..936021e88a5--- /dev/null+++ b/packages/connector-data/src/twitter/parser.ts@@ -0,0 +1,215 @@+import { toRecord } from '@lobechat/utils/object';++import type {+ TwitterPost,+ TwitterPostMetrics,+ TwitterProfile,+ TwitterProfileMetrics,+} from './types';++const MAX_DESCRIPTION_LENGTH = 1000;+const MAX_ID_LENGTH = 64;+const MAX_LOCATION_LENGTH = 200;+const MAX_NAME_LENGTH = 200;+const MAX_POST_TEXT_LENGTH = 4000;+const MAX_USERNAME_LENGTH = 15;+const SAFE_USERNAME = /^\w+$/;+const executionWrappers = ['data', 'result', 'response'] as const;++const boundedString = (value: unknown, limit: number): string | undefined => {+ if (typeof value !== 'string') return;+ const normalized = value.trim().slice(0, limit);+ return normalized || undefined;+};++const boundedNumber = (value: unknown): number | undefined =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;++const readUsername = (value: unknown): string | undefined => {+ const username = boundedString(value, MAX_USERNAME_LENGTH);+ return username && SAFE_USERNAME.test(username) ? username : undefined;+};++const readTimestamp = (value: unknown): string | undefined => {+ const timestamp = boundedString(value, 64);+ if (!timestamp) return;+ const milliseconds = new Date(timestamp).getTime();+ return Number.isFinite(milliseconds) ? new Date(milliseconds).toISOString() : undefined;+};++const readProfileMetrics = (value: unknown): TwitterProfileMetrics => {+ const metrics = toRecord(value);+ if (!metrics) return {};+ return {+ followersCount: boundedNumber(metrics.followers_count),+ followingCount: boundedNumber(metrics.following_count),+ listedCount: boundedNumber(metrics.listed_count),+ postCount: boundedNumber(metrics.tweet_count ?? metrics.post_count),+ };+};++const readPostMetrics = (value: unknown): TwitterPostMetrics => {+ const metrics = toRecord(value);+ if (!metrics) return {};+ return {+ bookmarkCount: boundedNumber(metrics.bookmark_count),+ impressionCount: boundedNumber(metrics.impression_count),+ likeCount: boundedNumber(metrics.like_count),+ quoteCount: boundedNumber(metrics.quote_count),+ replyCount: boundedNumber(metrics.reply_count),+ repostCount: boundedNumber(metrics.retweet_count ?? metrics.repost_count),+ };+};++const walkExecutionRecords = (value: unknown): Record<string, unknown>[] => {+ const queue: Array<{ depth: number; value: unknown }> = [{ depth: 0, value }];+ const records: Record<string, unknown>[] = [];+ while (queue.length > 0) {+ const current = queue.shift()!;+ const record = toRecord(current.value);+ if (!record) continue;+ records.push(record);+ if (current.depth >= 3) continue;+ for (const key of executionWrappers) {+ if (record[key] !== undefined) queue.push({ depth: current.depth + 1, value: record[key] });+ }+ }+ return records;+};++const readIncludedUsers = (records: Record<string, unknown>[]): Map<string, string> => {+ const users = new Map<string, string>();+ for (const record of records) {+ const includes = toRecord(record.includes);+ if (!Array.isArray(includes?.users)) continue;+ for (const candidate of includes.users.slice(0, 200)) {+ const user = toRecord(candidate);+ const id = boundedString(user?.id, MAX_ID_LENGTH);+ const username = readUsername(user?.username);+ if (id && username) users.set(id, username);+ }+ }+ return users;+};++const normalizePost = (+ value: unknown,+ usernamesById: ReadonlyMap<string, string>,+): TwitterPost | undefined => {+ const post = toRecord(value);+ const id = boundedString(post?.id, MAX_ID_LENGTH);+ const noteTweet = toRecord(post?.note_tweet);+ const text = boundedString(noteTweet?.text ?? post?.text, MAX_POST_TEXT_LENGTH);+ if (!post || !id || !text) return;+ const authorId = boundedString(post.author_id, MAX_ID_LENGTH);+ const authorUsername = authorId ? usernamesById.get(authorId) : undefined;+ const conversationId = boundedString(post.conversation_id, MAX_ID_LENGTH);+ const createdAt = readTimestamp(post.created_at);+ const inReplyToUserId = boundedString(post.in_reply_to_user_id, MAX_ID_LENGTH);+ const references = Array.isArray(post.referenced_tweets)+ ? post.referenced_tweets.slice(0, 16).flatMap((reference) => {+ const type = boundedString(toRecord(reference)?.type, 32);+ return type ? [type] : [];+ })+ : [];+ return {+ ...(authorId ? { authorId } : {}),+ ...(authorUsername ? { authorUsername } : {}),+ ...(conversationId ? { conversationId } : {}),+ ...(createdAt ? { createdAt } : {}),+ id,+ ...(inReplyToUserId ? { inReplyToUserId } : {}),+ metrics: readPostMetrics(post.public_metrics),+ referencedPostTypes: [...new Set(references)],+ sourceUrl: authorUsername+ ? `https://x.com/${authorUsername}/status/${id}`+ : `https://x.com/i/web/status/${id}`,+ text,+ };+};++/**+ * Normalizes Market X recent-search output into bounded public posts.+ *+ * Before:+ * - `{ data: { data: [{ id: "1", text: "Hello", author_id: "2" }], includes: { users: [...] } } }`+ *+ * After:+ * - `[{ id: "1", text: "Hello", authorUsername: "ada", sourceUrl: "https://x.com/ada/status/1" }]`+ */+export const parseTwitterPosts = (+ value: unknown,+ maxCandidates: number,+): TwitterPost[] | undefined => {+ const records = walkExecutionRecords(value);+ const usernamesById = readIncludedUsers(records);+ const collection = records+ .map((record) => {+ if (Array.isArray(record.data)) return record.data;+ if (Array.isArray(record.posts)) return record.posts;+ if (Array.isArray(record.tweets)) return record.tweets;+ })+ .find((candidate): candidate is unknown[] => candidate !== undefined);+ if (!collection) {+ const isExplicitlyEmpty = records.some((record) => {+ const meta = toRecord(record.meta);+ return boundedNumber(meta?.result_count) === 0;+ });+ return isExplicitlyEmpty ? [] : undefined;+ }+ const finiteLimit = Number.isFinite(maxCandidates) ? Math.floor(maxCandidates) : 0;+ const limit = Math.min(Math.max(0, finiteLimit), 100);+ const posts = new Map<string, TwitterPost>();+ for (const candidate of collection.slice(0, limit)) {+ const post = normalizePost(candidate, usernamesById);+ if (post && !posts.has(post.id)) posts.set(post.id, post);+ }+ if (collection.length > 0 && limit > 0 && posts.size === 0) return;+ return [...posts.values()];+};++/**+ * Normalizes Market X authenticated-user output into a bounded profile.+ *+ * Before:+ * - `{ data: { data: { id: "2", username: "ada", name: "Ada" } } }`+ *+ * After:+ * - `{ id: "2", username: "ada", name: "Ada", sourceUrl: "https://x.com/ada" }`+ */+export const parseTwitterProfile = (value: unknown): TwitterProfile | undefined => {+ const records = walkExecutionRecords(value);+ const profile = records.find((record) => {+ const id = boundedString(record.id, MAX_ID_LENGTH);+ const username = readUsername(record.username);+ return Boolean(id && username);+ });+ if (!profile) return;+ const id = boundedString(profile.id, MAX_ID_LENGTH)!;+ const username = readUsername(profile.username)!;+ const name = boundedString(profile.name, MAX_NAME_LENGTH) ?? username;+ const createdAt = readTimestamp(profile.created_at);+ const description = boundedString(profile.description, MAX_DESCRIPTION_LENGTH);+ const location = boundedString(profile.location, MAX_LOCATION_LENGTH);+ const pinnedTweetId = boundedString(profile.pinned_tweet_id, MAX_ID_LENGTH);+ const usernamesById = readIncludedUsers(records);+ const includedTweets = records.flatMap((record) => {+ const includes = toRecord(record.includes);+ return Array.isArray(includes?.tweets) ? includes.tweets.slice(0, 16) : [];+ });+ const pinnedPost = includedTweets+ .map((post) => normalizePost(post, usernamesById))+ .find((post) => post?.id === pinnedTweetId);+ return {+ ...(createdAt ? { createdAt } : {}),+ ...(description ? { description } : {}),+ id,+ ...(location ? { location } : {}),+ metrics: readProfileMetrics(profile.public_metrics),+ name,+ ...(pinnedPost ? { pinnedPost } : {}),+ sourceUrl: `https://x.com/${username}`,+ username,+ ...(typeof profile.verified === 'boolean' ? { verified: profile.verified } : {}),+ };+};diff --git a/packages/connector-data/src/twitter/types.ts b/packages/connector-data/src/twitter/types.tsnew file mode 100644index 00000000000..511efebdb07--- /dev/null+++ b/packages/connector-data/src/twitter/types.ts@@ -0,0 +1,91 @@+/** Public engagement counters retained from an X profile. */+export interface TwitterProfileMetrics {+ /** Number of accounts following this profile. */+ followersCount?: number;+ /** Number of accounts this profile follows. */+ followingCount?: number;+ /** Number of public lists containing this profile. */+ listedCount?: number;+ /** Number of posts reported by X for this profile. */+ postCount?: number;+}++/** Public engagement counters retained from an X post. */+export interface TwitterPostMetrics {+ /** Number of bookmarks reported for this post, when visible. */+ bookmarkCount?: number;+ /** Number of impressions reported for this post, when visible. */+ impressionCount?: number;+ /** Number of likes reported for this post. */+ likeCount?: number;+ /** Number of quote posts reported for this post. */+ quoteCount?: number;+ /** Number of replies reported for this post. */+ replyCount?: number;+ /** Number of reposts reported for this post. */+ repostCount?: number;+}++/** Bounded public profile metadata for the authenticated X account. */+export interface TwitterProfile {+ /** ISO account creation timestamp, when returned by X. */+ createdAt?: string;+ /** Public profile biography. */+ description?: string;+ /** Stable X user identifier. */+ id: string;+ /** Public free-form profile location. */+ location?: string;+ /** Public engagement counters. */+ metrics: TwitterProfileMetrics;+ /** Display name shown by X. */+ name: string;+ /** Expanded pinned post, when the account has one and X returns it. */+ pinnedPost?: TwitterPost;+ /** Canonical public profile URL. */+ sourceUrl: string;+ /** X handle without the leading at-sign. */+ username: string;+ /** Whether X reports the account as verified. */+ verified?: boolean;+}++/** Bounded public post metadata returned by recent X search. */+export interface TwitterPost {+ /** Stable X identifier for the author, when returned. */+ authorId?: string;+ /** X handle for the author, when expanded. */+ authorUsername?: string;+ /** Conversation identifier used to group replies. */+ conversationId?: string;+ /** ISO creation timestamp, when returned by X. */+ createdAt?: string;+ /** Stable post identifier. */+ id: string;+ /** X user identifier being replied to, when applicable. */+ inReplyToUserId?: string;+ /** Public engagement counters. */+ metrics: TwitterPostMetrics;+ /** Relationship types such as replied_to, quoted, or retweeted. */+ referencedPostTypes: string[];+ /** Canonical public post URL. */+ sourceUrl: string;+ /** Bounded post text, including long-form note text when returned. */+ text: string;+}++/** Input for one bounded X recent-search request. */+export interface TwitterSearchRecentPostsInput {+ /** Maximum normalized posts returned to the caller. */+ maxResults?: number;+ /** X recent-search query, limited to the platform's seven-day window. */+ query: string;+}++/** Read-only X client used by onboarding source collectors. */+export interface TwitterConnectorClient {+ /** Loads public metadata for the authenticated X account. */+ getProfile: () => Promise<TwitterProfile>;+ /** Searches public posts from the most recent seven days. */+ searchRecentPosts: (input: TwitterSearchRecentPostsInput) => Promise<TwitterPost[]>;+}diff --git a/packages/const/src/composio.ts b/packages/const/src/composio.tsindex a8cc50add98..d1496826af4 100644--- a/packages/const/src/composio.ts+++ b/packages/const/src/composio.ts@@ -273,12 +273,12 @@ export const COMPOSIO_APP_TYPES: ComposioAppType[] = [author: 'Composio',authorUrl: 'https://composio.dev',description:- 'X (Twitter) is a social media platform for sharing real-time updates, news, and engaging with your audience',+ 'X is a social media platform for sharing real-time updates, news, and engaging with your audience',icon: SiX,identifier: 'twitter',- label: 'X (Twitter)',+ label: 'X',readme:- 'Connect to X (Twitter) to post updates, manage your timeline, and engage with your audience. Create content, monitor mentions, and build your social media presence through conversational AI.',+ 'Connect to X to post updates, manage your timeline, and engage with your audience. Create content, monitor mentions, and build your social media presence through conversational AI.',},{appSlug: 'GITHUB',diff --git a/packages/const/src/lobehubSkill.ts b/packages/const/src/lobehubSkill.tsindex fecf96b2e7a..93ea35968fc 100644--- a/packages/const/src/lobehubSkill.ts+++ b/packages/const/src/lobehubSkill.ts@@ -113,12 +113,12 @@ export const LOBEHUB_SKILL_PROVIDERS: LobehubSkillProviderType[] = [authorUrl: OFFICIAL_SITE,defaultVisible: true,description:- 'X (Twitter) is a social media platform for sharing real-time updates, news, and engaging with your audience through posts, replies, and direct messages.',+ 'X is a social media platform for sharing real-time updates, news, and engaging with your audience through posts, replies, and direct messages.',icon: SiX,id: 'twitter',readme:- 'Connect to X (Twitter) to post tweets, manage your timeline, and engage with your audience. Create content, schedule posts, monitor mentions, and build your social media presence through conversational AI.',- label: 'X (Twitter)',+ 'Connect to X to publish posts, manage your timeline, and engage with your audience. Create content, schedule posts, monitor mentions, and build your social media presence through conversational AI.',+ label: 'X',},{author: 'LobeHub',diff --git a/packages/prompts/src/chains/onboardingTaskRecommendation.test.ts b/packages/prompts/src/chains/onboardingTaskRecommendation.test.tsindex ccd4285e718..fa35290c8d2 100644--- a/packages/prompts/src/chains/onboardingTaskRecommendation.test.ts+++ b/packages/prompts/src/chains/onboardingTaskRecommendation.test.ts@@ -59,4 +59,14 @@ describe('chainOnboardingTaskRecommendation', () => {'Never claim that newer or unauthorized pages exist',);});++ /** @example X guidance separates authorship and keeps public social actions user-approved. */+ it('keeps X recommendations read-only by default', () => {+ const twitter = DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.providers.twitter;+ const principles = twitter.principles.join('\n');++ expect(principles).toContain('Keep authored posts distinct from third-party mentions');+ expect(principles).toContain('Never post, reply, like, repost');+ expect(twitter.examples.join('\n')).toContain('private prioritized shortlist');+ });});diff --git a/packages/prompts/src/chains/onboardingTaskRecommendation.ts b/packages/prompts/src/chains/onboardingTaskRecommendation.tsindex 806063034a6..cf0864c0996 100644--- a/packages/prompts/src/chains/onboardingTaskRecommendation.ts+++ b/packages/prompts/src/chains/onboardingTaskRecommendation.ts@@ -121,6 +121,19 @@ export const DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG = {'Describe incomplete authorization only as a possibility. Never claim that newer or unauthorized pages exist, and never ask the agent to bypass Notion access controls.',],},+ twitter: {+ examples: [+ 'Title: Prepare a reply shortlist for recent X questions. Instruction: Review the linked public mentions in the background, group genuine questions and useful feedback by topic, and return a private prioritized shortlist with concise draft replies and uncertainty called out. Do not post, reply, like, repost, follow, or send direct messages.',+ 'Title: Analyze discussion around the recent product launch post. Instruction: Compare the linked authored post with its supplied public discussion signals, summarize recurring reactions and unanswered questions, and return a private response brief plus suggested follow-up themes. Treat engagement as attention rather than approval, and do not perform any X action.',+ 'Title: Prepare the next X content brief from recent engineering posts. Instruction: Synthesize the linked authored posts into a private brief of recurring themes, audience questions, and two differentiated draft directions. Preserve the user’s demonstrated voice without inventing opinions, and leave publishing for explicit user approval.',+ ],+ principles: [+ 'Use only supplied authored posts and public mentions from the recent-search window; missing activity is not evidence that a topic or audience interest does not exist.',+ 'Keep authored posts distinct from third-party mentions, replies, and quotes. Never attribute another account’s statement or intent to the user.',+ 'Treat likes, reposts, replies, quotes, and view counts as attention signals rather than approval, urgency, or an obligation to respond.',+ 'Prefer private analysis, response triage, content briefs, and draft replies that can be reviewed later. Never post, reply, like, repost, quote, follow, unfollow, mute, block, bookmark, or send a direct message without later explicit user approval.',+ ],+ },},writing: {instructionPrinciples: [@@ -130,7 +143,7 @@ export const DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG = {'Preserve uncertainty from the evidence and state any user approval boundary explicitly.','Prefer tasks that can finish asynchronously without interrupting the user: gather evidence, analyze activity, summarize, compare, prioritize, or prepare a draft, checklist, report, or patch plan.','Minimize clarification requests by making conservative assumptions and recording them in the result. Ask the user only when a consequential choice or new authorization is required.',- 'Do not perform external side effects by default. Email sends, deletion, unsubscribe, archive, label changes, GitHub comments, review submission, approval, merge, close, label, and push operations require a later explicit user-approved action.',+ 'Do not perform external side effects by default. Email sends, deletion, unsubscribe, archive, label changes, GitHub comments, review submission, approval, merge, close, label, push, and X posting, replying, liking, reposting, following, or direct messaging require a later explicit user-approved action.',],maxSourcesPerRecommendation: 4,titlePrinciples: [