Skip to content

🤯 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.

✨ feat(connector-data): add GitHub client (#17319)

Neko0cca74f7c931
diff --git a/package.json b/package.json
index a662b0ec4a1..0bca49732ce 100644
--- a/package.json
+++ b/package.json
@@ -262,6 +262,7 @@
"@lobechat/chat-adapter-qq": "workspace:*",
"@lobechat/chat-adapter-wechat": "workspace:*",
"@lobechat/config": "workspace:*",
+ "@lobechat/connector-data": "workspace:*",
"@lobechat/const": "workspace:*",
"@lobechat/context-engine": "workspace:*",
"@lobechat/conversation-flow": "workspace:*",
@@ -390,6 +391,7 @@
"nodemailer": "^9.0.3",
"numeral": "^2.0.6",
"nuqs": "^2.8.9",
+ "octokit": "^5.0.0",
"officeparser": "5.1.1",
"ogl": "^1.0.11",
"oidc-provider": "^9.8.6",
diff --git a/packages/connector-data/package.json b/packages/connector-data/package.json
new file mode 100644
index 00000000000..d857adc6efc
--- /dev/null
+++ b/packages/connector-data/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "@lobechat/connector-data",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": {
+ "types": "./src/index.ts",
+ "default": "./src/index.ts"
+ },
+ "./github": {
+ "types": "./src/github/index.ts",
+ "default": "./src/github/index.ts"
+ }
+ },
+ "main": "./src/index.ts",
+ "scripts": {
+ "test": "vitest run --silent='passed-only'"
+ },
+ "dependencies": {
+ "debug": "^4.4.3",
+ "octokit": "^5.0.0",
+ "zod": "^3.25.76"
+ },
+ "devDependencies": {
+ "@types/debug": "^4.1.13"
+ }
+}
diff --git a/packages/connector-data/src/errors.test.ts b/packages/connector-data/src/errors.test.ts
new file mode 100644
index 00000000000..eea5017fef3
--- /dev/null
+++ b/packages/connector-data/src/errors.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+
+import { ConnectorDataError } from './errors';
+
+describe('ConnectorDataError', () => {
+ it('exposes a sanitized connector failure contract', () => {
+ const unsafeInput = {
+ code: 'github_request_failed',
+ message: 'upstream response body with token=secret',
+ operation: 'listRepositories',
+ provider: 'github',
+ retryable: false,
+ } as const;
+ const error = new ConnectorDataError(unsafeInput);
+
+ expect(error).toBeInstanceOf(Error);
+ expect(error).toMatchObject({
+ code: 'github_request_failed',
+ message: 'github listRepositories failed',
+ name: 'ConnectorDataError',
+ operation: 'listRepositories',
+ provider: 'github',
+ retryable: false,
+ });
+ expect(error.message).not.toContain(unsafeInput.message);
+ });
+});
diff --git a/packages/connector-data/src/errors.ts b/packages/connector-data/src/errors.ts
new file mode 100644
index 00000000000..ac7272492e6
--- /dev/null
+++ b/packages/connector-data/src/errors.ts
@@ -0,0 +1,25 @@
+export type ConnectorDataProvider = 'github';
+
+export interface ConnectorDataErrorOptions {
+ code: string;
+ operation: string;
+ provider: ConnectorDataProvider;
+ retryable: boolean;
+}
+
+export class ConnectorDataError extends Error {
+ readonly code: string;
+ readonly operation: string;
+ readonly provider: ConnectorDataProvider;
+ readonly retryable: boolean;
+
+ constructor({ code, operation, provider, retryable }: ConnectorDataErrorOptions) {
+ super(`${provider} ${operation} failed`);
+
+ this.name = 'ConnectorDataError';
+ this.code = code;
+ this.operation = operation;
+ this.provider = provider;
+ this.retryable = retryable;
+ }
+}
diff --git a/packages/connector-data/src/github/client.test.ts b/packages/connector-data/src/github/client.test.ts
new file mode 100644
index 00000000000..8b43074d070
--- /dev/null
+++ b/packages/connector-data/src/github/client.test.ts
@@ -0,0 +1,356 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createGitHubConnectorClient } from './client';
+import type { GitHubConnectorTransport } from './graphql/client';
+
+const profileResult = {
+ viewer: {
+ bio: 'Building tools.',
+ company: '@lobehub',
+ location: 'Shanghai',
+ login: 'neko',
+ name: 'Neko',
+ pronouns: 'they/them',
+ websiteUrl: `https://lobehub.com/\u0000${'x'.repeat(600)}`,
+ },
+};
+
+const createTransport = () => {
+ const calls: Array<{ operation: string; variables: Record<string, unknown> }> = [];
+ const listRepositoryContributors = vi.fn(async () => [
+ { contributions: 9, login: ' neko\u0000 ' },
+ { contributions: 8, login: 'alice' },
+ { contributions: 7, login: 'bob' },
+ { contributions: 6, login: 'carol' },
+ { contributions: 5, login: 'dave' },
+ { contributions: 4, login: 'excluded' },
+ ]);
+ const transport: GitHubConnectorTransport = {
+ getAuthenticatedUser: async () => ({ id: 98_765, login: 'neko' }),
+ listRepositoryContributors,
+ request: async ({ operation, variables }) => {
+ calls.push({ operation, variables });
+ if (operation === 'ConnectorDataGitHubProfile') return profileResult;
+ if (operation === 'ConnectorDataGitHubRepositories') {
+ return {
+ viewer: {
+ pinnedItems: {
+ nodes: [
+ {
+ description: 'AI framework',
+ forkCount: 3,
+ issues: { totalCount: 4 },
+ nameWithOwner: 'lobehub/lobehub',
+ primaryLanguage: { name: 'TypeScript' },
+ pullRequests: { totalCount: 5 },
+ repositoryTopics: { nodes: [{ topic: { name: 'ai' } }] },
+ stargazerCount: 70_000,
+ },
+ ],
+ },
+ pullRequests: {
+ nodes: [
+ {
+ number: 42,
+ repository: { nameWithOwner: 'acme/external' },
+ title: 'Improve agent support',
+ updatedAt: '2026-07-08T00:00:00Z',
+ },
+ ],
+ },
+ repositories: {
+ nodes: [
+ {
+ description: 'Recent work',
+ nameWithOwner: 'neko/shiori',
+ primaryLanguage: null,
+ pushedAt: null,
+ stargazerCount: 80,
+ },
+ ],
+ },
+ },
+ };
+ }
+ if (operation === 'ConnectorDataGitHubContributions') {
+ return {
+ viewer: {
+ contributionsCollection: {
+ commitContributionsByRepository: [
+ {
+ contributions: {
+ nodes: [{ commitCount: 7, occurredAt: '2026-07-12T00:00:00Z' }],
+ },
+ repository: { nameWithOwner: 'lobehub/lobehub' },
+ },
+ ],
+ issueContributions: { nodes: [] },
+ pullRequestContributions: {
+ nodes: [
+ {
+ occurredAt: '2026-07-10T00:00:00Z',
+ pullRequest: {
+ repository: { nameWithOwner: 'lobehub/lobehub' },
+ title: 'Add understanding pipeline',
+ },
+ },
+ ],
+ },
+ pullRequestReviewContributions: { nodes: [] },
+ },
+ },
+ };
+ }
+ if (operation === 'ConnectorDataGitHubOrganizations') {
+ return {
+ viewer: {
+ organizations: {
+ nodes: [
+ {
+ description: 'Making AI accessible.',
+ followers: { totalCount: 12 },
+ login: 'lobehub',
+ name: 'LobeHub',
+ repositories: { totalCount: 42 },
+ },
+ ],
+ },
+ },
+ };
+ }
+ if (operation === 'ConnectorDataGitHubProfileReadme') {
+ return { viewer: { repository: { object: { text: '# Neko\nBuild useful tools.' } } } };
+ }
+ throw new Error(`Unexpected operation: ${operation}`);
+ },
+ };
+
+ return { calls, listRepositoryContributors, transport };
+};
+
+describe('createGitHubConnectorClient', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('returns a normalized authenticated user profile', async () => {
+ const { calls, transport } = createTransport();
+ const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });
+
+ await expect(client.getUserProfile()).resolves.toEqual({
+ bio: 'Building tools.',
+ company: '@lobehub',
+ externalAccountId: '98765',
+ location: 'Shanghai',
+ login: 'neko',
+ name: 'Neko',
+ pronouns: 'they/them',
+ websiteUrl: `https://lobehub.com/${'x'.repeat(480)}...`,
+ });
+ expect(calls).toEqual([
+ {
+ operation: 'ConnectorDataGitHubProfile',
+ variables: {},
+ },
+ ]);
+ expect(JSON.stringify(calls)).not.toContain('test-token');
+ });
+
+ it('lists normalized repository and contribution resources', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime('2026-07-17T12:34:56.789Z');
+ const { calls, transport } = createTransport();
+ const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });
+
+ await expect(client.listPinnedRepositories()).resolves.toEqual([
+ {
+ description: 'AI framework',
+ forkCount: 3,
+ issueCount: 4,
+ nameWithOwner: 'lobehub/lobehub',
+ primaryLanguage: 'TypeScript',
+ pullRequestCount: 5,
+ stargazerCount: 70_000,
+ topics: ['ai'],
+ },
+ ]);
+ await expect(client.listRecentRepositories()).resolves.toEqual([
+ {
+ description: 'Recent work',
+ nameWithOwner: 'neko/shiori',
+ stargazerCount: 80,
+ topics: [],
+ },
+ ]);
+ await expect(client.listRecentPullRequests()).resolves.toEqual([
+ {
+ number: 42,
+ repository: 'acme/external',
+ title: 'Improve agent support',
+ updatedAt: '2026-07-08T00:00:00Z',
+ },
+ ]);
+ await expect(client.listRecentContributions()).resolves.toEqual([
+ {
+ count: 7,
+ occurredAt: '2026-07-12T00:00:00Z',
+ repository: 'lobehub/lobehub',
+ title: '7 commits',
+ type: 'commit',
+ },
+ {
+ count: 1,
+ occurredAt: '2026-07-10T00:00:00Z',
+ repository: 'lobehub/lobehub',
+ title: 'Add understanding pipeline',
+ type: 'pull_request',
+ },
+ ]);
+ expect(calls).toContainEqual({
+ operation: 'ConnectorDataGitHubRepositories',
+ variables: { first: 12, pullFirst: 4 },
+ });
+ expect(calls).toContainEqual({
+ operation: 'ConnectorDataGitHubContributions',
+ variables: {
+ contributionFirst: 10,
+ from: '2026-01-18T12:34:56.789Z',
+ },
+ });
+ });
+
+ it('deduplicates concurrent repository requests', async () => {
+ const { calls, transport } = createTransport();
+ const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });
+
+ await Promise.all([client.listPinnedRepositories(), client.listRecentRepositories()]);
+
+ expect(
+ calls.filter(({ operation }) => operation === 'ConnectorDataGitHubRepositories'),
+ ).toHaveLength(1);
+ });
+
+ it('clears a rejected profile request so a later call can recover', async () => {
+ vi.useFakeTimers();
+ let healthy = false;
+ const request = vi.fn(async ({ operation }: { operation: string }) => {
+ if (operation !== 'ConnectorDataGitHubProfile') throw new Error('Unexpected operation');
+ if (!healthy) throw Object.assign(new Error('temporary outage'), { status: 503 });
+ return profileResult;
+ });
+ const transport: GitHubConnectorTransport = {
+ getAuthenticatedUser: async () => ({ id: 98_765, login: 'neko' }),
+ listRepositoryContributors: async () => [],
+ request,
+ };
+ const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });
+ const first = client.getUserProfile();
+ const firstRejection = expect(first).rejects.toMatchObject({ retryable: true });
+
+ await vi.runAllTimersAsync();
+ await firstRejection;
+ healthy = true;
+
+ await expect(client.getUserProfile()).resolves.toMatchObject({ login: 'neko' });
+ expect(request).toHaveBeenCalledTimes(4);
+ });
+
+ it('normalizes and bounds repository contributors in the loader', async () => {
+ const { listRepositoryContributors, transport } = createTransport();
+ const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });
+
+ await expect(client.listRepositoryContributors('lobehub/lobehub')).resolves.toEqual([
+ { contributionCount: 9, login: 'neko' },
+ { contributionCount: 8, login: 'alice' },
+ { contributionCount: 7, login: 'bob' },
+ { contributionCount: 6, login: 'carol' },
+ { contributionCount: 5, login: 'dave' },
+ ]);
+ expect(listRepositoryContributors).toHaveBeenCalledWith({
+ owner: 'lobehub',
+ perPage: 5,
+ repository: 'lobehub',
+ });
+
+ await expect(client.listRepositoryContributors('invalid')).resolves.toEqual([]);
+ await expect(client.listRepositoryContributors('/missing-owner')).resolves.toEqual([]);
+ expect(listRepositoryContributors).toHaveBeenCalledOnce();
+ });
+
+ it('does not expose repository input in contributor errors', async () => {
+ const sensitiveRepository = 'token-sensitive-owner/private-repository';
+ const transport: GitHubConnectorTransport = {
+ getAuthenticatedUser: async () => ({ id: 98_765, login: 'neko' }),
+ listRepositoryContributors: vi.fn().mockRejectedValue({ status: 401 }),
+ request: vi.fn(),
+ };
+ const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });
+
+ const error = await client
+ .listRepositoryContributors(sensitiveRepository)
+ .catch((reason) => reason);
+
+ expect(error).toMatchObject({
+ message: 'github listRepositoryContributors failed',
+ operation: 'listRepositoryContributors',
+ });
+ expect(JSON.stringify(error)).not.toContain(sensitiveRepository);
+ });
+
+ it('lists normalized organizations', async () => {
+ const { calls, transport } = createTransport();
+ const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });
+
+ await expect(client.listUserOrganizations()).resolves.toEqual([
+ {
+ description: 'Making AI accessible.',
+ followerCount: 12,
+ login: 'lobehub',
+ name: 'LobeHub',
+ repositoryCount: 42,
+ },
+ ]);
+ expect(calls).toContainEqual({
+ operation: 'ConnectorDataGitHubOrganizations',
+ variables: {},
+ });
+ });
+
+ it('loads the profile README using the authenticated login', async () => {
+ const { calls, transport } = createTransport();
+ const client = createGitHubConnectorClient({ accessToken: 'test-token', transport });
+
+ await expect(client.getUserProfileReadme()).resolves.toBe('# Neko\nBuild useful tools.');
+ expect(calls).toContainEqual({
+ operation: 'ConnectorDataGitHubProfileReadme',
+ variables: { name: 'neko' },
+ });
+ });
+
+ it('creates an Octokit-backed client when only an access token is supplied', async () => {
+ const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const request = new Request(input, init);
+ const body = request.method === 'POST' ? await request.clone().json() : undefined;
+ const data =
+ typeof body === 'object' && body && 'query' in body
+ ? { data: profileResult }
+ : { id: 1, login: 'octocat' };
+ return new Response(JSON.stringify(data), {
+ headers: { 'content-type': 'application/json' },
+ status: 200,
+ });
+ });
+ vi.stubGlobal('fetch', fetch);
+ const client = createGitHubConnectorClient({ accessToken: 'production-token' });
+
+ await expect(client.getUserProfile()).resolves.toMatchObject({
+ externalAccountId: '1',
+ login: 'neko',
+ });
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(fetch.mock.calls.map(([input, init]) => new Request(input, init).url)).toEqual([
+ 'https://api.github.com/graphql',
+ 'https://api.github.com/user',
+ ]);
+ });
+});
diff --git a/packages/connector-data/src/github/client.ts b/packages/connector-data/src/github/client.ts
new file mode 100644
index 00000000000..11c982fce7d
--- /dev/null
+++ b/packages/connector-data/src/github/client.ts
@@ -0,0 +1,71 @@
+import type { GitHubConnectorTransport } from './graphql/client';
+import { createGitHubGraphQLClient, createOctokitTransport } from './graphql/client';
+import {
+ loadContributions,
+ loadOrganizations,
+ loadProfileBundle,
+ loadProfileReadme,
+ loadRepositories,
+ loadRepositoryContributors,
+ loadUserProfile,
+} from './loaders';
+import type {
+ GitHubContribution,
+ GitHubOrganization,
+ GitHubPullRequest,
+ GitHubRepository,
+ GitHubRepositoryContributor,
+ GitHubUserProfile,
+} from './types';
+
+export interface GitHubConnectorClient {
+ getUserProfile: () => Promise<GitHubUserProfile>;
+ getUserProfileReadme: () => Promise<string | undefined>;
+ listPinnedRepositories: () => Promise<GitHubRepository[]>;
+ listRecentContributions: () => Promise<GitHubContribution[]>;
+ listRecentPullRequests: () => Promise<GitHubPullRequest[]>;
+ listRecentRepositories: () => Promise<GitHubRepository[]>;
+ listRepositoryContributors: (repository: string) => Promise<GitHubRepositoryContributor[]>;
+ listUserOrganizations: () => Promise<GitHubOrganization[]>;
+}
+
+export interface CreateGitHubConnectorClientOptions {
+ accessToken: string;
+ /** @internal Tests and custom protocol adapters only. */
+ transport?: GitHubConnectorTransport;
+}
+
+const createRecoverableMemo = <T>(load: () => Promise<T>) => {
+ let promise: Promise<T> | undefined;
+
+ return () => {
+ promise ??= load().catch((error) => {
+ promise = undefined;
+ throw error;
+ });
+ return promise;
+ };
+};
+
+export const createGitHubConnectorClient = ({
+ accessToken,
+ transport = createOctokitTransport(accessToken),
+}: CreateGitHubConnectorClientOptions): GitHubConnectorClient => {
+ const graphqlClient = createGitHubGraphQLClient(transport);
+ const getProfileBundle = createRecoverableMemo(() => loadProfileBundle(graphqlClient));
+ const getRepositories = createRecoverableMemo(() => loadRepositories(graphqlClient));
+
+ return {
+ getUserProfile: async () => loadUserProfile(await getProfileBundle(), transport),
+ getUserProfileReadme: async () => {
+ const { viewer } = await getProfileBundle();
+ return loadProfileReadme(graphqlClient, viewer.login);
+ },
+ listPinnedRepositories: async () => (await getRepositories()).pinned,
+ listRecentContributions: () => loadContributions(graphqlClient),
+ listRecentPullRequests: async () => (await getRepositories()).pulls,
+ listRecentRepositories: async () => (await getRepositories()).recent,
+ listRepositoryContributors: (repository) => loadRepositoryContributors(transport, repository),
+ listUserOrganizations: () => loadOrganizations(graphqlClient),
+ };
+};
diff --git a/packages/connector-data/src/github/formatter.test.ts b/packages/connector-data/src/github/formatter.test.ts
new file mode 100644
index 00000000000..9fd4c0bd178
--- /dev/null
+++ b/packages/connector-data/src/github/formatter.test.ts
@@ -0,0 +1,232 @@
+import { describe, expect, it } from 'vitest';
+
+import { toGitHubUserContextMarkdown } from './formatter';
+import type { GitHubUserContext } from './types';
+
+const context: GitHubUserContext = {
+ organizations: [
+ {
+ description: 'Making AI accessible.',
+ followerCount: 12,
+ login: 'lobehub',
+ name: 'LobeHub',
+ repositoryCount: 42,
+ },
+ ],
+ pinnedRepositories: [
+ {
+ description: 'AI application framework',
+ forkCount: 3000,
+ issueCount: 100,
+ nameWithOwner: 'lobehub/lobehub',
+ primaryLanguage: 'TypeScript',
+ pullRequestCount: 500,
+ stargazerCount: 70_000,
+ topics: ['ai', 'agent'],
+ },
+ ],
+ profile: {
+ bio: 'Building tools for humans and agents.',
+ company: '@lobehub',
+ externalAccountId: '98765',
+ location: 'Shanghai',
+ login: 'neko',
+ name: 'Neko',
+ pronouns: 'they/them',
+ websiteUrl: 'https://lobehub.com',
+ },
+ profileReadme: [
+ '# Hi, I am Neko',
+ '#### Hello',
+ '<picture>',
+ '<source srcset="https://example.com/stats.svg" />',
+ '</picture>',
+ '> [!TIP]',
+ '> I build creative AI products.',
+ '#### Languages & Frameworks I use',
+ '#### Public sessions shared',
+ '> Full list: https://github.com/neko/talks',
+ '| Talk | Cover |',
+ '| --- | --- |',
+ '#### Highlights',
+ '- Agent workspace',
+ ].join('\n'),
+ recentContributions: [
+ {
+ count: 1,
+ occurredAt: '2026-07-09T00:00:00Z',
+ repository: 'lobehub/lobehub',
+ title: 'Reviewed: Refine agent runtime',
+ type: 'pull_request_review',
+ },
+ {
+ count: 1,
+ occurredAt: '2026-07-10T00:00:00Z',
+ repository: 'lobehub/lobehub',
+ title: 'Add understanding pipeline',
+ type: 'pull_request',
+ },
+ {
+ count: 7,
+ occurredAt: '2026-07-12T00:00:00Z',
+ repository: 'lobehub/lobehub',
+ title: '7 commits',
+ type: 'commit',
+ },
+ ],
+ recentPullRequests: [
+ {
+ number: 42,
+ repository: 'acme/external',
+ title: 'Improve external agent support',
+ updatedAt: '2026-07-08T00:00:00Z',
+ },
+ ],
+ recentRepositories: [
+ {
+ description: 'A personal knowledge tool',
+ nameWithOwner: 'neko/shiori',
+ primaryLanguage: 'TypeScript',
+ pushedAt: '2026-07-08T00:00:00Z',
+ stargazerCount: 80,
+ topics: [],
+ },
+ ],
+ repositoryContributors: {
+ 'lobehub/lobehub': [
+ { contributionCount: 500, login: 'neko' },
+ { contributionCount: 90, login: 'alice' },
+ ],
+ },
+};
+
+describe('toGitHubUserContextMarkdown', () => {
+ it('preserves the stable evidence sections and formatting', () => {
+ const markdown = toGitHubUserContextMarkdown(context);
+
+ expect(markdown).toContain('## GitHub Profile');
+ expect(markdown).toContain('Name: Neko');
+ expect(markdown).toContain('GitHub: neko');
+ expect(markdown).toContain('Pronouns: they/them');
+ expect(markdown).toContain('Website: https://lobehub.com');
+ expect(markdown).toContain('Organizations:\n- LobeHub (@lobehub)');
+ expect(markdown).not.toContain('## Organizations');
+ expect(markdown).toContain('## Profile README');
+ expect(markdown).toContain('Intro: I build creative AI products.');
+ expect(markdown).toContain(
+ 'Sections: Hello, Languages & Frameworks I use, Public sessions shared, Highlights',
+ );
+ expect(markdown).toContain('Public sessions shared: Full list: https://github.com/neko/talks');
+ expect(markdown).not.toContain('srcset=');
+ expect(markdown).not.toContain('| --- |');
+ expect(markdown).toContain(
+ '- lobehub/lobehub — AI application framework (language: TypeScript, stars: 70000, forks: 3000, topics: ai, agent, contributors sampled: 2, top contributors: neko, alice)',
+ );
+ expect(markdown).toContain('2026-07-12:\n- committed 7 commits to lobehub/lobehub');
+ expect(markdown).toContain(
+ '2026-07-10:\n- opened 1 pull request in lobehub/lobehub\n - Add understanding pipeline',
+ );
+ expect(markdown).toContain(
+ '2026-07-09:\n- reviewed 1 pull request in lobehub/lobehub\n - Reviewed: Refine agent runtime',
+ );
+ expect(markdown.split('\n').filter((line) => line.startsWith('#'))).toEqual([
+ '## GitHub Profile',
+ '## Profile README',
+ '## Pinned Repositories',
+ '## Recent Contribution History',
+ ]);
+ });
+
+ it('uses recent repositories and pull requests when primary evidence is absent', () => {
+ const markdown = toGitHubUserContextMarkdown({
+ profile: context.profile,
+ recentContributions: [],
+ recentPullRequests: context.recentPullRequests,
+ recentRepositories: context.recentRepositories,
+ });
+
+ expect(markdown).toContain('## Recent Repositories');
+ expect(markdown).toContain(
+ '- neko/shiori - A personal knowledge tool (language: TypeScript; stars: 80; pushed: 2026-07-08)',
+ );
+ expect(markdown).toContain('## Recent Pull Request Samples');
+ expect(markdown).toContain('- acme/external#42: Improve external agent support (2026-07-08)');
+ });
+
+ it('bounds README headings, prose, contribution count, and total output', () => {
+ const profileReadme = Array.from(
+ { length: 300 },
+ (_, index) => `## Heading ${index} ${'x'.repeat(500)}\n${'body '.repeat(600)}`,
+ ).join('\n');
+ const recentContributions = Array.from({ length: 100 }, (_, index) => ({
+ count: 1,
+ occurredAt: `2026-07-${String((index % 28) + 1).padStart(2, '0')}T00:00:00Z`,
+ repository: 'lobehub/lobehub',
+ title: `Contribution ${index}`,
+ type: 'issue' as const,
+ }));
+
+ const markdown = toGitHubUserContextMarkdown(
+ { profile: context.profile, profileReadme, recentContributions },
+ { maxLength: 6000 },
+ );
+ const readme = markdown.split('## Profile README\n\n')[1].split('\n\n## ')[0];
+ const sectionsLine = readme.split('\n').find((line) => line.startsWith('Sections:'));
+ const introLine = readme.split('\n').find((line) => line.startsWith('Intro:'));
+ const headings = sectionsLine?.slice('Sections: '.length).split(', ') ?? [];
+
+ expect(headings.length).toBeLessThanOrEqual(24);
+ expect(Math.max(...headings.map((heading) => heading.length))).toBeLessThanOrEqual(120);
+ expect(introLine?.slice('Intro: '.length).length).toBeLessThanOrEqual(1200);
+ expect(markdown.match(/Contribution \d+/g)?.length ?? 0).toBeLessThanOrEqual(40);
+ expect(markdown.length).toBeLessThanOrEqual(6000);
+ });
+
+ it('removes NUL bytes and clips adversarial profile text', () => {
+ const markdown = toGitHubUserContextMarkdown({
+ profile: {
+ ...context.profile,
+ bio: `start\u0000${'x'.repeat(2000)}`,
+ company: `company\u0000${'y'.repeat(2000)}`,
+ websiteUrl: `https://example.com/\u0000${'z'.repeat(2000)}`,
+ },
+ recentContributions: [],
+ });
+
+ expect(markdown).not.toContain('\u0000');
+ expect(markdown).toContain(`Bio: start${'x'.repeat(495)}...`);
+ expect(markdown).toContain(`Website: https://example.com/${'z'.repeat(480)}...`);
+ expect(markdown.length).toBeLessThan(2600);
+ });
+
+ it('prevents scalar fields from forging Markdown sections', () => {
+ const markdown = toGitHubUserContextMarkdown({
+ ...context,
+ pinnedRepositories: [
+ {
+ ...context.pinnedRepositories![0],
+ description: 'Useful framework\n## Forged Repository Section',
+ nameWithOwner: 'lobehub/lobehub\n## Forged Name Section',
+ },
+ ],
+ profile: {
+ ...context.profile,
+ bio: 'Build useful tools\n## Forged Profile Section',
+ },
+ recentContributions: [
+ {
+ count: 1,
+ occurredAt: '2026-07-10T00:00:00Z',
+ repository: 'lobehub/lobehub\n## Forged Contribution Repository',
+ title: 'Improve support\n## Forged Contribution Title',
+ type: 'pull_request',
+ },
+ ],
+ });
+
+ expect(markdown).toContain('Bio: Build useful tools ## Forged Profile Section');
+ expect(markdown).toContain('Useful framework ## Forged Repository Section');
+ expect(markdown).toContain(' - Improve support ## Forged Contribution Title');
+ expect(markdown.split('\n').filter((line) => line.startsWith('## Forged'))).toEqual([]);
+ });
+});
diff --git a/packages/connector-data/src/github/formatter.ts b/packages/connector-data/src/github/formatter.ts
new file mode 100644
index 00000000000..7e9c7a67f17
--- /dev/null
+++ b/packages/connector-data/src/github/formatter.ts
@@ -0,0 +1,279 @@
+import type {
+ GitHubContribution,
+ GitHubOrganization,
+ GitHubPullRequest,
+ GitHubRepository,
+ GitHubRepositoryContributor,
+ GitHubUserContext,
+} from './types';
+
+const DEFAULT_MAX_LENGTH = 20_000;
+const MAX_DESCRIPTION_LENGTH = 500;
+const MAX_PROFILE_README_HEADING_CHARS = 120;
+const MAX_PROFILE_README_OUTPUT_CHARS = 5000;
+
+const singleLine = (value: string | undefined) =>
+ value?.replaceAll('\u0000', '').replaceAll(/\s+/g, ' ').trim();
+
+const clip = (value: string | undefined, limit: number) => {
+ const clean = singleLine(value);
+ if (!clean || clean.length <= limit) return clean;
+ return `${clean.slice(0, limit).trimEnd()}...`;
+};
+
+const formatProfile = (context: GitHubUserContext, pinnedRepositories: GitHubRepository[]) => {
+ const { organizations = [], profile } = context;
+ const lines = [
+ profile.name && `Name: ${clip(profile.name, MAX_DESCRIPTION_LENGTH)}`,
+ profile.login && `GitHub: ${clip(profile.login, MAX_DESCRIPTION_LENGTH)}`,
+ profile.pronouns && `Pronouns: ${clip(profile.pronouns, MAX_DESCRIPTION_LENGTH)}`,
+ profile.bio && `Bio: ${clip(profile.bio, MAX_DESCRIPTION_LENGTH)}`,
+ profile.company && `Company: ${clip(profile.company, MAX_DESCRIPTION_LENGTH)}`,
+ profile.location && `Location: ${clip(profile.location, MAX_DESCRIPTION_LENGTH)}`,
+ profile.websiteUrl && `Website: ${clip(profile.websiteUrl, MAX_DESCRIPTION_LENGTH)}`,
+ ].filter(Boolean);
+ if (organizations.length > 0) {
+ lines.push('Organizations:');
+ lines.push(...organizations.map(formatOrganization));
+ }
+ if (pinnedRepositories.length > 0) {
+ lines.push(
+ `Pinned: ${pinnedRepositories
+ .map(({ nameWithOwner }) => clip(nameWithOwner, MAX_DESCRIPTION_LENGTH))
+ .filter(Boolean)
+ .join(', ')}`,
+ );
+ }
+
+ return ['## GitHub Profile', '', ...lines].join('\n');
+};
+
+const formatOrganization = (organization: GitHubOrganization) => {
+ const name = clip(organization.name, MAX_DESCRIPTION_LENGTH);
+ const login = clip(organization.login, MAX_DESCRIPTION_LENGTH);
+ const label = name && login && name !== login ? `${name} (@${login})` : (name ?? login);
+ const details = [
+ organization.followerCount !== undefined && `${organization.followerCount} followers`,
+ organization.repositoryCount !== undefined && `${organization.repositoryCount} repos`,
+ clip(organization.description, MAX_DESCRIPTION_LENGTH),
+ ].filter(Boolean);
+ return `- ${label}${details.length > 0 ? ` (${details.join('; ')})` : ''}`;
+};
+
+const cleanReadmeLines = (selectedLines: string[]) => {
+ const output: string[] = [];
+ let htmlBlock: string | undefined;
+ for (const rawLine of selectedLines) {
+ const line = rawLine.replaceAll('\u0000', '').trim();
+ if (htmlBlock) {
+ if (line.includes(`</${htmlBlock}>`)) htmlBlock = undefined;
+ continue;
+ }
+ const htmlBlockStart = ['picture', 'div', 'table'].find((tag) =>
+ line.toLowerCase().startsWith(`<${tag}`),
+ );
+ if (htmlBlockStart) {
+ if (!line.includes(`</${htmlBlockStart}>`)) htmlBlock = htmlBlockStart;
+ continue;
+ }
+ if (!line || line.startsWith('#') || line.startsWith('<') || line.startsWith('|')) continue;
+ if (line.startsWith('![') || line.startsWith('[!')) continue;
+ const unquoted = line.startsWith('>') ? line.slice(1).trim() : line;
+ if (!unquoted || unquoted.startsWith('[!') || unquoted.startsWith('![')) continue;
+ output.push(unquoted);
+ }
+ return output.join(' ');
+};
+
+const formatProfileReadme = (profileReadme: string | undefined) => {
+ if (!profileReadme) return '';
+
+ const lines = profileReadme
+ // Constants: default max profile readme source characters
+ .slice(0, 40_000)
+ .replaceAll('\r\n', '\n')
+ .split('\n');
+
+ const sections = lines
+ .map((line, index) => {
+ let level = 0;
+ while (line[level] === '#') level += 1;
+ if (level < 2 || level > 4 || line[level] !== ' ') return;
+ return {
+ index,
+ title: line
+ .slice(level + 1)
+ .replaceAll(/[*_`]/g, '')
+ .replaceAll('\u0000', '')
+ .trim()
+ .slice(0, MAX_PROFILE_README_HEADING_CHARS),
+ };
+ })
+ .filter((section): section is { index: number; title: string } => Boolean(section))
+ // Constants: default max profile readme headings
+ .slice(0, 24);
+
+ const firstSectionIndex = sections[0]?.index ?? lines.length;
+ const firstSectionEnd = sections[1]?.index ?? lines.length;
+ const intro = cleanReadmeLines([
+ ...lines.slice(0, firstSectionIndex),
+ ...lines.slice(firstSectionIndex + 1, firstSectionEnd),
+ ]);
+
+ const publicSection = sections.find((section) => /public sessions|公开分享/i.test(section.title));
+ const publicSectionContent = publicSection
+ ? cleanReadmeLines(
+ lines.slice(
+ publicSection.index + 1,
+ sections.find((section) => section.index > publicSection.index)?.index ?? lines.length,
+ ),
+ )
+ : undefined;
+
+ const MAX_PROFILE_README_PROSE_CHARS = 1200;
+ const summary = [
+ intro && `Intro: ${clip(intro, MAX_PROFILE_README_PROSE_CHARS - 3)}`,
+ sections.length > 0 && `Sections: ${sections.map(({ title }) => title).join(', ')}`,
+ publicSection &&
+ publicSectionContent &&
+ `${publicSection.title}: ${clip(publicSectionContent, MAX_PROFILE_README_PROSE_CHARS - 3)}`,
+ ].filter(Boolean);
+
+ if (summary.length === 0) return '';
+
+ // Constants: default max profile readme output characters
+ return ['## Profile README', '', ...summary].join('\n').slice(0, MAX_PROFILE_README_OUTPUT_CHARS);
+};
+
+const formatPinnedRepositories = (
+ repositories: GitHubRepository[],
+ contributorsByRepository: Record<string, GitHubRepositoryContributor[]>,
+) => {
+ if (repositories.length === 0) return '';
+ return [
+ '## Pinned Repositories',
+ '',
+ ...repositories.map((repository) => {
+ const contributors = contributorsByRepository[repository.nameWithOwner] ?? [];
+
+ const details = [
+ repository.primaryLanguage &&
+ `language: ${clip(repository.primaryLanguage, MAX_DESCRIPTION_LENGTH)}`,
+ repository.stargazerCount !== undefined && `stars: ${repository.stargazerCount}`,
+ repository.forkCount !== undefined && `forks: ${repository.forkCount}`,
+ repository.topics.length > 0 &&
+ `topics: ${repository.topics
+ .map((topic) => clip(topic, MAX_DESCRIPTION_LENGTH))
+ .filter(Boolean)
+ .join(', ')}`,
+ contributors.length > 0 && `contributors sampled: ${contributors.length}`,
+ contributors.length > 0 &&
+ `top contributors: ${contributors
+ .map(({ login }) => clip(login, MAX_DESCRIPTION_LENGTH) ?? 'unknown')
+ .join(', ')}`,
+ ].filter(Boolean);
+
+ const description = clip(repository.description, MAX_DESCRIPTION_LENGTH);
+ return `- ${clip(repository.nameWithOwner, MAX_DESCRIPTION_LENGTH) ?? 'Repository'}${description ? ` — ${description}` : ''}${
+ details.length > 0 ? ` (${details.join(', ')})` : ''
+ }`;
+ }),
+ ].join('\n');
+};
+
+const formatRecentRepositories = (repositories: GitHubRepository[]) => {
+ if (repositories.length === 0) return '';
+ return [
+ '## Recent Repositories',
+ '',
+ ...repositories.map((repository) => {
+ const details = [
+ repository.primaryLanguage &&
+ `language: ${clip(repository.primaryLanguage, MAX_DESCRIPTION_LENGTH)}`,
+ repository.stargazerCount !== undefined && `stars: ${repository.stargazerCount}`,
+ repository.pushedAt && `pushed: ${singleLine(repository.pushedAt)?.slice(0, 10)}`,
+ ].filter(Boolean);
+
+ return `- ${clip(repository.nameWithOwner, MAX_DESCRIPTION_LENGTH) ?? 'Repository'}${repository.description ? ` - ${clip(repository.description, MAX_DESCRIPTION_LENGTH)}` : ''}${details.length > 0 ? ` (${details.join('; ')})` : ''}`;
+ }),
+ ].join('\n');
+};
+
+const formatPullRequests = (pullRequests: GitHubPullRequest[]) => {
+ if (pullRequests.length === 0) return '';
+ return [
+ '## Recent Pull Request Samples',
+ '',
+ ...pullRequests.map(
+ (pullRequest) =>
+ `- ${clip(pullRequest.repository, MAX_DESCRIPTION_LENGTH) ?? 'Repository'}#${pullRequest.number ?? '?'}: ${clip(pullRequest.title, MAX_DESCRIPTION_LENGTH) ?? 'Untitled pull request'}${pullRequest.updatedAt ? ` (${singleLine(pullRequest.updatedAt)?.slice(0, 10)})` : ''}`,
+ ),
+ ].join('\n');
+};
+
+const formatContributions = (input: GitHubContribution[]) => {
+ const contributions = [...input]
+ .sort((left, right) => String(right.occurredAt).localeCompare(String(left.occurredAt)))
+ // Constants: default max contributions
+ .slice(0, 40);
+
+ if (contributions.length === 0) return '';
+
+ const dates = new Map<string, Map<string, GitHubContribution[]>>();
+ for (const contribution of contributions) {
+ const date = singleLine(contribution.occurredAt)?.slice(0, 10) ?? 'Unknown date';
+ const key = `${contribution.type}:${singleLine(contribution.repository) ?? 'Unknown repository'}`;
+ const groups = dates.get(date) ?? new Map<string, GitHubContribution[]>();
+ groups.set(key, [...(groups.get(key) ?? []), contribution]);
+ dates.set(date, groups);
+ }
+
+ const lines = ['## Recent Contribution History', ''];
+ for (const [date, groups] of dates) {
+ lines.push(`${date}:`);
+
+ for (const group of groups.values()) {
+ const first = group[0];
+ const repository = clip(first.repository, MAX_DESCRIPTION_LENGTH) ?? 'Unknown repository';
+ const count = group.reduce((total, item) => total + (item.count ?? 1), 0);
+ const noun = count === 1 ? 'pull request' : 'pull requests';
+ if (first.type === 'commit')
+ lines.push(`- committed ${count} commit${count === 1 ? '' : 's'} to ${repository}`);
+ if (first.type === 'issue')
+ lines.push(`- opened ${count} issue${count === 1 ? '' : 's'} in ${repository}`);
+ if (first.type === 'pull_request') lines.push(`- opened ${count} ${noun} in ${repository}`);
+ if (first.type === 'pull_request_review')
+ lines.push(`- reviewed ${count} ${noun} in ${repository}`);
+ if (first.type !== 'commit')
+ lines.push(...group.map(({ title }) => ` - ${clip(title, MAX_DESCRIPTION_LENGTH)}`));
+ }
+ }
+
+ return lines.join('\n');
+};
+
+export interface ToGitHubUserContextMarkdownOptions {
+ maxLength?: number;
+}
+
+export const toGitHubUserContextMarkdown = (
+ context: GitHubUserContext,
+ { maxLength = DEFAULT_MAX_LENGTH }: ToGitHubUserContextMarkdownOptions = {},
+) => {
+ const pinnedRepositories = context.pinnedRepositories ?? [];
+ const recentContributions = context.recentContributions ?? [];
+ const hasPrimaryProfileEvidence = Boolean(
+ context.profileReadme || pinnedRepositories.length > 0 || recentContributions.length > 0,
+ );
+
+ const sections = [
+ formatProfile(context, pinnedRepositories),
+ formatProfileReadme(context.profileReadme),
+ formatPinnedRepositories(pinnedRepositories, context.repositoryContributors ?? {}),
+ hasPrimaryProfileEvidence ? '' : formatRecentRepositories(context.recentRepositories ?? []),
+ hasPrimaryProfileEvidence ? '' : formatPullRequests(context.recentPullRequests ?? []),
+ formatContributions(recentContributions),
+ ].filter(Boolean);
+
+ return sections.join('\n\n').replaceAll('\u0000', '').slice(0, Math.max(0, maxLength));
+};
diff --git a/packages/connector-data/src/github/graphql/client.test.ts b/packages/connector-data/src/github/graphql/client.test.ts
new file mode 100644
index 00000000000..fb5f9afdcde
--- /dev/null
+++ b/packages/connector-data/src/github/graphql/client.test.ts
@@ -0,0 +1,203 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
+
+import { ConnectorDataError } from '../../errors';
+import type { GitHubConnectorTransport } from './client';
+import { createOctokitTransport, execute } from './client';
+
+const log = vi.hoisted(() => vi.fn());
+const octokit = vi.hoisted(() =>
+ vi.fn(function OctokitMock(_options: {
+ auth: string;
+ retry: { enabled: boolean };
+ throttle: {
+ onRateLimit: () => boolean;
+ onSecondaryRateLimit: () => boolean;
+ };
+ }) {
+ return {
+ graphql: vi.fn(),
+ rest: {
+ repos: { listContributors: vi.fn() },
+ users: { getAuthenticated: vi.fn() },
+ },
+ };
+ }),
+);
+
+vi.mock('debug', () => ({
+ default: vi.fn(() => log),
+}));
+vi.mock('octokit', () => ({ Octokit: octokit }));
+
+const createTransport = (
+ request: GitHubConnectorTransport['request'],
+): GitHubConnectorTransport => ({
+ getAuthenticatedUser: async () => ({ id: 1, login: 'neko' }),
+ listRepositoryContributors: async () => [],
+ request,
+});
+
+const schema = z.object({ viewer: z.object({ login: z.string() }).strict() }).strict();
+
+describe('GitHub GraphQL execute', () => {
+ afterEach(() => {
+ log.mockClear();
+ vi.useRealTimers();
+ });
+
+ it('disables Octokit retries because connector retry owns the policy', () => {
+ createOctokitTransport('test-token');
+
+ const [options] = octokit.mock.calls.at(-1)!;
+ expect(options).toMatchObject({
+ auth: 'test-token',
+ retry: { enabled: false },
+ throttle: {
+ onRateLimit: expect.any(Function),
+ onSecondaryRateLimit: expect.any(Function),
+ },
+ });
+ expect(options.throttle.onRateLimit()).toBe(false);
+ expect(options.throttle.onSecondaryRateLimit()).toBe(false);
+ });
+
+ it('retries a transient request and validates the successful response', async () => {
+ vi.useFakeTimers();
+ const request = vi
+ .fn()
+ .mockRejectedValueOnce(Object.assign(new Error('temporary'), { status: 503 }))
+ .mockResolvedValueOnce({ viewer: { login: 'neko' } });
+ const result = execute({
+ operation: 'TestProfile',
+ query: 'query TestProfile { viewer { login } }',
+ schema,
+ transport: createTransport(request),
+ variables: {},
+ });
+
+ await vi.runAllTimersAsync();
+
+ await expect(result).resolves.toEqual({ viewer: { login: 'neko' } });
+ expect(request).toHaveBeenCalledTimes(2);
+ });
+
+ it('sanitizes strict schema failures', async () => {
+ const transport = createTransport(
+ vi.fn().mockResolvedValue({
+ upstreamBody: 'token=secret-upstream-body',
+ viewer: { login: 'neko' },
+ }),
+ );
+
+ const error = await execute({
+ operation: 'TestProfile',
+ query: 'query TestProfile { viewer { login } }',
+ schema,
+ transport,
+ variables: {},
+ }).catch((reason) => reason);
+
+ expect(error).toBeInstanceOf(ConnectorDataError);
+ expect(error).toMatchObject({
+ code: 'github_response_invalid',
+ message: 'github TestProfile failed',
+ operation: 'TestProfile',
+ retryable: false,
+ });
+ const diagnostic = JSON.stringify({ error, logs: log.mock.calls });
+ expect(diagnostic).not.toMatch(/secret-upstream-body|token=|upstreamBody/);
+ });
+
+ it('sanitizes terminal upstream failures', async () => {
+ const transport = createTransport(
+ vi
+ .fn()
+ .mockRejectedValue(
+ Object.assign(new Error('401 token=secret-upstream-body'), { status: 401 }),
+ ),
+ );
+
+ const error = await execute({
+ operation: 'TestProfile',
+ query: 'query TestProfile { viewer { login } }',
+ schema,
+ transport,
+ variables: {},
+ }).catch((reason) => reason);
+
+ expect(error).toMatchObject({
+ code: 'github_request_failed',
+ message: 'github TestProfile failed',
+ retryable: false,
+ });
+ expect(log).toHaveBeenCalledWith('GraphQL request failed: %O', {
+ errorName: 'Error',
+ operation: 'TestProfile',
+ status: 401,
+ });
+ expect(JSON.stringify({ error, logs: log.mock.calls })).not.toMatch(
+ /secret-upstream-body|token=/,
+ );
+ });
+
+ it('logs only safe GraphQL error types and paths', async () => {
+ const errors = [
+ {
+ data: { token: 'secret-data' },
+ extensions: { response: 'secret-extension' },
+ message: 'token=secret-message',
+ path: ['viewer', 'contributionsCollection', 0, 'secret path segment'],
+ type: 'RESOURCE_LIMITS_EXCEEDED',
+ },
+ {
+ message: 'secret-second-message',
+ path: ['viewer', 'repositories'],
+ type: 'unsafe type=secret',
+ },
+ ...Array.from({ length: 8 }, (_, index) => ({
+ message: `secret-overflow-${index}`,
+ path: ['viewer', `field${index}`],
+ type: 'NOT_FOUND',
+ })),
+ ];
+ const upstreamError = Object.assign(new Error('token=secret-upstream-body'), {
+ errors,
+ name: 'GraphqlResponseError',
+ status: 200,
+ });
+ const transport = createTransport(vi.fn().mockRejectedValue(upstreamError));
+
+ const error = await execute({
+ operation: 'TestProfile',
+ query: 'query TestProfile { viewer { login } }',
+ schema,
+ transport,
+ variables: { token: 'secret-variable' },
+ }).catch((reason) => reason);
+
+ expect(error).toMatchObject({
+ code: 'github_request_failed',
+ retryable: false,
+ });
+ expect(log).toHaveBeenCalledWith('GraphQL request failed: %O', {
+ errorName: 'GraphqlResponseError',
+ errors: [
+ {
+ path: ['viewer', 'contributionsCollection', 0, '[redacted]'],
+ type: 'RESOURCE_LIMITS_EXCEEDED',
+ },
+ { path: ['viewer', 'repositories'] },
+ ...Array.from({ length: 6 }, (_, index) => ({
+ path: ['viewer', `field${index}`],
+ type: 'NOT_FOUND',
+ })),
+ ],
+ operation: 'TestProfile',
+ status: 200,
+ });
+ expect(JSON.stringify(log.mock.calls)).not.toMatch(
+ /secret-data|secret-extension|secret-message|secret-upstream-body|secret-variable|unsafe type/,
+ );
+ });
+});
diff --git a/packages/connector-data/src/github/graphql/client.ts b/packages/connector-data/src/github/graphql/client.ts
new file mode 100644
index 00000000000..ef7b8d6a47b
--- /dev/null
+++ b/packages/connector-data/src/github/graphql/client.ts
@@ -0,0 +1,185 @@
+import debug from 'debug';
+import { Octokit } from 'octokit';
+import type { z } from 'zod';
+
+import { ConnectorDataError } from '../../errors';
+import { withConnectorRetry } from '../../retry';
+
+const log = debug('lobe-server:connector-data:github');
+const MAX_ISSUES = 8;
+const MAX_PATH_SEGMENTS = 8;
+const SAFE_ERROR_NAME = /^[a-z][a-z0-9]{0,63}$/i;
+const SAFE_GRAPHQL_ERROR_TYPE = /^[A-Z][A-Z0-9_]{0,63}$/;
+const SAFE_PATH_SEGMENT = /^[a-z_$][\w$]{0,63}$/i;
+const declineOctokitRetry = () => false;
+
+export interface GitHubGraphQLRequest<Variables extends Record<string, unknown>> {
+ operation: string;
+ query: string;
+ variables: Variables;
+}
+
+/** @internal Test seam and protocol adapter. */
+export interface GitHubConnectorTransport {
+ getAuthenticatedUser: () => Promise<{ id: number | string; login: string }>;
+ listRepositoryContributors: (input: {
+ owner: string;
+ perPage: number;
+ repository: string;
+ }) => Promise<Array<{ contributions?: number; login?: string | null }>>;
+ request: <Variables extends Record<string, unknown>>(
+ input: GitHubGraphQLRequest<Variables>,
+ ) => Promise<unknown>;
+}
+
+export interface GitHubGraphQLClient {
+ execute: <Response, Variables extends Record<string, unknown>>(input: {
+ operation: string;
+ query: string;
+ schema: z.ZodType<Response>;
+ variables: Variables;
+ }) => Promise<Response>;
+}
+
+interface ExecuteOptions<Response, Variables extends Record<string, unknown>> {
+ operation: string;
+ query: string;
+ schema: z.ZodType<Response>;
+ transport: GitHubConnectorTransport;
+ variables: Variables;
+}
+
+const getErrorName = (error: unknown): string => {
+ if (!(error instanceof Error) || !SAFE_ERROR_NAME.test(error.name)) return 'Error';
+
+ return error.name;
+};
+
+const getErrorStatus = (error: unknown): number | undefined => {
+ if (typeof error !== 'object' || error === null) return;
+
+ const { response, status, statusCode } = error as {
+ response?: { status?: unknown };
+ status?: unknown;
+ statusCode?: unknown;
+ };
+ const candidate = status ?? statusCode ?? response?.status;
+
+ return typeof candidate === 'number' && Number.isFinite(candidate) ? candidate : undefined;
+};
+
+const getIssuePath = (path: readonly unknown[]): Array<number | string> =>
+ path.slice(0, MAX_PATH_SEGMENTS).map((segment) => {
+ if (typeof segment === 'number' && Number.isSafeInteger(segment)) return segment;
+ if (typeof segment === 'string' && SAFE_PATH_SEGMENT.test(segment)) return segment;
+
+ return '[redacted]';
+ });
+
+const getGraphQLErrors = (
+ error: unknown,
+): Array<{ path?: Array<number | string>; type?: string }> | undefined => {
+ if (typeof error !== 'object' || error === null || !('errors' in error)) return;
+
+ const { errors } = error as { errors?: unknown };
+ if (!Array.isArray(errors)) return;
+
+ return errors.slice(0, MAX_ISSUES).flatMap((entry) => {
+ if (typeof entry !== 'object' || entry === null) return [];
+
+ const { path, type } = entry as { path?: unknown; type?: unknown };
+ const diagnostic = {
+ ...(Array.isArray(path) ? { path: getIssuePath(path) } : {}),
+ ...(typeof type === 'string' && SAFE_GRAPHQL_ERROR_TYPE.test(type) ? { type } : {}),
+ };
+
+ return Object.keys(diagnostic).length > 0 ? [diagnostic] : [];
+ });
+};
+
+/** @internal GraphQL protocol execution with retry and strict response validation. */
+export const execute = async <Response, Variables extends Record<string, unknown>>({
+ operation,
+ query,
+ schema,
+ transport,
+ variables,
+}: ExecuteOptions<Response, Variables>): Promise<Response> =>
+ withConnectorRetry(
+ async () => {
+ let response: unknown;
+
+ try {
+ response = await transport.request({ operation, query, variables });
+ } catch (error) {
+ const errors = getGraphQLErrors(error);
+ const status = getErrorStatus(error);
+ log('GraphQL request failed: %O', {
+ errorName: getErrorName(error),
+ ...(errors === undefined ? {} : { errors }),
+ operation,
+ ...(status === undefined ? {} : { status }),
+ });
+ throw error;
+ }
+
+ const result = schema.safeParse(response);
+ if (result.success) return result.data;
+
+ log('GraphQL response validation failed: %O', {
+ issues: result.error.issues.slice(0, MAX_ISSUES).map(({ code, path }) => ({
+ code,
+ path: getIssuePath(path),
+ })),
+ operation,
+ });
+ throw new ConnectorDataError({
+ code: 'github_response_invalid',
+ operation,
+ provider: 'github',
+ retryable: false,
+ });
+ },
+ {
+ code: 'github_request_failed',
+ operation,
+ provider: 'github',
+ },
+ );
+
+/** @internal */
+export const createOctokitTransport = (accessToken: string): GitHubConnectorTransport => {
+ const octokit = new Octokit({
+ auth: accessToken,
+ retry: { enabled: false },
+ throttle: {
+ onRateLimit: declineOctokitRetry,
+ onSecondaryRateLimit: declineOctokitRetry,
+ },
+ });
+
+ return {
+ getAuthenticatedUser: async () => {
+ const response = await octokit.rest.users.getAuthenticated();
+ return { id: response.data.id, login: response.data.login };
+ },
+ listRepositoryContributors: async ({ owner, perPage, repository }) => {
+ const response = await octokit.rest.repos.listContributors({
+ owner,
+ per_page: perPage,
+ repo: repository,
+ });
+ return response.data.map(({ contributions, login }) => ({
+ contributions,
+ login,
+ }));
+ },
+ request: ({ query, variables }) => octokit.graphql(query, variables),
+ };
+};
+
+export const createGitHubGraphQLClient = (
+ transport: GitHubConnectorTransport,
+): GitHubGraphQLClient => ({
+ execute: (input) => execute({ ...input, transport }),
+});
diff --git a/packages/connector-data/src/github/graphql/queries/contributions.test.ts b/packages/connector-data/src/github/graphql/queries/contributions.test.ts
new file mode 100644
index 00000000000..477e177fa72
--- /dev/null
+++ b/packages/connector-data/src/github/graphql/queries/contributions.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+
+import { CONTRIBUTIONS_QUERY } from './contributions';
+
+describe('CONTRIBUTIONS_QUERY', () => {
+ it('bounds recent contributions without reducing signal limits', () => {
+ expect(CONTRIBUTIONS_QUERY).toContain(
+ 'query ConnectorDataGitHubContributions($contributionFirst: Int!, $from: DateTime!)',
+ );
+ expect(CONTRIBUTIONS_QUERY).toContain('contributionsCollection(from: $from)');
+ expect(CONTRIBUTIONS_QUERY).toContain('commitContributionsByRepository(maxRepositories: 10)');
+ expect(CONTRIBUTIONS_QUERY).toContain(
+ 'contributions(first: 3, orderBy: { field: OCCURRED_AT, direction: DESC })',
+ );
+ expect(CONTRIBUTIONS_QUERY).toContain(
+ 'pullRequestContributions(first: $contributionFirst, orderBy: { direction: DESC })',
+ );
+ });
+});
diff --git a/packages/connector-data/src/github/graphql/queries/contributions.ts b/packages/connector-data/src/github/graphql/queries/contributions.ts
new file mode 100644
index 00000000000..62f1baee0c8
--- /dev/null
+++ b/packages/connector-data/src/github/graphql/queries/contributions.ts
@@ -0,0 +1,142 @@
+import { z } from 'zod';
+
+const RepositoryReferenceSchema = z.object({ nameWithOwner: z.string() }).strict();
+const ContributionSubjectSchema = z
+ .object({
+ repository: RepositoryReferenceSchema,
+ title: z.string(),
+ })
+ .strict();
+
+export const CONTRIBUTIONS_QUERY = /* GraphQL */ `
+ query ConnectorDataGitHubContributions($contributionFirst: Int!, $from: DateTime!) {
+ viewer {
+ contributionsCollection(from: $from) {
+ commitContributionsByRepository(maxRepositories: 10) {
+ contributions(first: 3, orderBy: { field: OCCURRED_AT, direction: DESC }) {
+ nodes {
+ commitCount
+ occurredAt
+ }
+ }
+ repository {
+ nameWithOwner
+ }
+ }
+ issueContributions(first: $contributionFirst, orderBy: { direction: DESC }) {
+ nodes {
+ issue {
+ repository {
+ nameWithOwner
+ }
+ title
+ }
+ occurredAt
+ }
+ }
+ pullRequestContributions(first: $contributionFirst, orderBy: { direction: DESC }) {
+ nodes {
+ occurredAt
+ pullRequest {
+ repository {
+ nameWithOwner
+ }
+ title
+ }
+ }
+ }
+ pullRequestReviewContributions(first: $contributionFirst, orderBy: { direction: DESC }) {
+ nodes {
+ occurredAt
+ pullRequestReview {
+ pullRequest {
+ repository {
+ nameWithOwner
+ }
+ title
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+`;
+
+export interface ContributionsQueryVariables {
+ contributionFirst: number;
+ from: string;
+}
+
+export const ContributionsCollectionSchema = z
+ .object({
+ commitContributionsByRepository: z.array(
+ z
+ .object({
+ contributions: z
+ .object({
+ nodes: z.array(
+ z
+ .object({
+ commitCount: z.number(),
+ occurredAt: z.string(),
+ })
+ .strict()
+ .nullable(),
+ ),
+ })
+ .strict(),
+ repository: RepositoryReferenceSchema,
+ })
+ .strict()
+ .nullable(),
+ ),
+ issueContributions: z
+ .object({
+ nodes: z.array(
+ z
+ .object({
+ issue: ContributionSubjectSchema,
+ occurredAt: z.string(),
+ })
+ .strict()
+ .nullable(),
+ ),
+ })
+ .strict(),
+ pullRequestContributions: z
+ .object({
+ nodes: z.array(
+ z
+ .object({
+ occurredAt: z.string(),
+ pullRequest: ContributionSubjectSchema,
+ })
+ .strict()
+ .nullable(),
+ ),
+ })
+ .strict(),
+ pullRequestReviewContributions: z
+ .object({
+ nodes: z.array(
+ z
+ .object({
+ occurredAt: z.string(),
+ pullRequestReview: z.object({ pullRequest: ContributionSubjectSchema }).strict(),
+ })
+ .strict()
+ .nullable(),
+ ),
+ })
+ .strict(),
+ })
+ .strict();
+
+export const ContributionsQueryResponseSchema = z
+ .object({
+ viewer: z.object({ contributionsCollection: ContributionsCollectionSchema }).strict(),
+ })
+ .strict();
+
+export type ContributionsQueryResponse = z.infer<typeof ContributionsQueryResponseSchema>;
diff --git a/packages/connector-data/src/github/graphql/queries/organizations.ts b/packages/connector-data/src/github/graphql/queries/organizations.ts
new file mode 100644
index 00000000000..6a8746ad954
--- /dev/null
+++ b/packages/connector-data/src/github/graphql/queries/organizations.ts
@@ -0,0 +1,52 @@
+import { z } from 'zod';
+
+export const ORGANIZATIONS_QUERY = /* GraphQL */ `
+ query ConnectorDataGitHubOrganizations {
+ viewer {
+ organizations(first: 20) {
+ nodes {
+ description
+ followers(first: 1) {
+ totalCount
+ }
+ login
+ name
+ repositories(first: 1) {
+ totalCount
+ }
+ }
+ }
+ }
+ }
+`;
+
+export type OrganizationsQueryVariables = Record<PropertyKey, never>;
+
+const CountConnectionSchema = z.object({ totalCount: z.number() }).strict();
+
+export const OrganizationsQueryResponseSchema = z
+ .object({
+ viewer: z
+ .object({
+ organizations: z
+ .object({
+ nodes: z.array(
+ z
+ .object({
+ description: z.string().nullable(),
+ followers: CountConnectionSchema,
+ login: z.string(),
+ name: z.string().nullable(),
+ repositories: CountConnectionSchema,
+ })
+ .strict()
+ .nullable(),
+ ),
+ })
+ .strict(),
+ })
+ .strict(),
+ })
+ .strict();
+
+export type OrganizationsQueryResponse = z.infer<typeof OrganizationsQueryResponseSchema>;
diff --git a/packages/connector-data/src/github/graphql/queries/profile.ts b/packages/connector-data/src/github/graphql/queries/profile.ts
new file mode 100644
index 00000000000..fa2c8056704
--- /dev/null
+++ b/packages/connector-data/src/github/graphql/queries/profile.ts
@@ -0,0 +1,35 @@
+import { z } from 'zod';
+
+export const PROFILE_QUERY = /* GraphQL */ `
+ query ConnectorDataGitHubProfile {
+ viewer {
+ bio
+ company
+ location
+ login
+ name
+ pronouns
+ websiteUrl
+ }
+ }
+`;
+
+export type ProfileQueryVariables = Record<PropertyKey, never>;
+
+export const ProfileQueryResponseSchema = z
+ .object({
+ viewer: z
+ .object({
+ bio: z.string().nullable(),
+ company: z.string().nullable(),
+ location: z.string().nullable(),
+ login: z.string(),
+ name: z.string().nullable(),
+ pronouns: z.string().nullable(),
+ websiteUrl: z.string().nullable(),
+ })
+ .strict(),
+ })
+ .strict();
+
+export type ProfileQueryResponse = z.infer<typeof ProfileQueryResponseSchema>;
diff --git a/packages/connector-data/src/github/graphql/queries/profileReadme.ts b/packages/connector-data/src/github/graphql/queries/profileReadme.ts
new file mode 100644
index 00000000000..af85e5f5af1
--- /dev/null
+++ b/packages/connector-data/src/github/graphql/queries/profileReadme.ts
@@ -0,0 +1,36 @@
+import { z } from 'zod';
+
+export const PROFILE_README_QUERY = /* GraphQL */ `
+ query ConnectorDataGitHubProfileReadme($name: String!) {
+ viewer {
+ repository(name: $name) {
+ object(expression: "HEAD:README.md") {
+ ... on Blob {
+ text
+ }
+ }
+ }
+ }
+ }
+`;
+
+export interface ProfileReadmeQueryVariables {
+ name: string;
+}
+
+export const ProfileReadmeQueryResponseSchema = z
+ .object({
+ viewer: z
+ .object({
+ repository: z
+ .object({
+ object: z.object({ text: z.string() }).strict().nullable(),
+ })
+ .strict()
+ .nullable(),
+ })
+ .strict(),
+ })
+ .strict();
+
+export type ProfileReadmeQueryResponse = z.infer<typeof ProfileReadmeQueryResponseSchema>;
diff --git a/packages/connector-data/src/github/graphql/queries/repositories.ts b/packages/connector-data/src/github/graphql/queries/repositories.ts
new file mode 100644
index 00000000000..2d29208b0f2
--- /dev/null
+++ b/packages/connector-data/src/github/graphql/queries/repositories.ts
@@ -0,0 +1,108 @@
+import { z } from 'zod';
+
+const CountConnectionSchema = z.object({ totalCount: z.number() }).strict();
+const LanguageSchema = z.object({ name: z.string() }).strict();
+const TopicSchema = z.object({ topic: z.object({ name: z.string() }).strict() }).strict();
+
+export const GitHubRepositoryNodeSchema = z
+ .object({
+ description: z.string().nullable(),
+ forkCount: z.number().optional(),
+ issues: CountConnectionSchema.optional(),
+ nameWithOwner: z.string(),
+ primaryLanguage: LanguageSchema.nullable(),
+ pullRequests: CountConnectionSchema.optional(),
+ pushedAt: z.string().nullable().optional(),
+ repositoryTopics: z
+ .object({ nodes: z.array(TopicSchema.nullable()) })
+ .strict()
+ .optional(),
+ stargazerCount: z.number(),
+ })
+ .strict();
+
+export const GitHubPullRequestNodeSchema = z
+ .object({
+ number: z.number(),
+ repository: z.object({ nameWithOwner: z.string() }).strict(),
+ title: z.string(),
+ updatedAt: z.string(),
+ })
+ .strict();
+
+export const REPOSITORIES_QUERY = /* GraphQL */ `
+ query ConnectorDataGitHubRepositories($first: Int!, $pullFirst: Int!) {
+ viewer {
+ pinnedItems(first: 8, types: REPOSITORY) {
+ nodes {
+ ... on Repository {
+ description
+ forkCount
+ issues(first: 1) {
+ totalCount
+ }
+ nameWithOwner
+ primaryLanguage {
+ name
+ }
+ pullRequests(first: 1) {
+ totalCount
+ }
+ repositoryTopics(first: 10) {
+ nodes {
+ topic {
+ name
+ }
+ }
+ }
+ stargazerCount
+ }
+ }
+ }
+ pullRequests(first: $pullFirst, orderBy: { field: UPDATED_AT, direction: DESC }) {
+ nodes {
+ number
+ repository {
+ nameWithOwner
+ }
+ title
+ updatedAt
+ }
+ }
+ repositories(
+ first: $first
+ ownerAffiliations: OWNER
+ orderBy: { field: PUSHED_AT, direction: DESC }
+ ) {
+ nodes {
+ description
+ nameWithOwner
+ primaryLanguage {
+ name
+ }
+ pushedAt
+ stargazerCount
+ }
+ }
+ }
+ }
+`;
+
+export interface RepositoriesQueryVariables {
+ first: number;
+ pullFirst: number;
+}
+
+export const RepositoriesQueryResponseSchema = z
+ .object({
+ viewer: z
+ .object({
+ pinnedItems: z.object({ nodes: z.array(GitHubRepositoryNodeSchema.nullable()) }).strict(),
+ pullRequests: z.object({ nodes: z.array(GitHubPullRequestNodeSchema.nullable()) }).strict(),
+ repositories: z.object({ nodes: z.array(GitHubRepositoryNodeSchema.nullable()) }).strict(),
+ })
+ .strict(),
+ })
+ .strict();
+
+export type RepositoriesQueryResponse = z.infer<typeof RepositoriesQueryResponseSchema>;
diff --git a/packages/connector-data/src/github/index.ts b/packages/connector-data/src/github/index.ts
new file mode 100644
index 00000000000..e42a3160262
--- /dev/null
+++ b/packages/connector-data/src/github/index.ts
@@ -0,0 +1,3 @@
+export * from './client';
+export * from './formatter';
+export * from './types';
diff --git a/packages/connector-data/src/github/loaders.ts b/packages/connector-data/src/github/loaders.ts
new file mode 100644
index 00000000000..9d1cb1e9790
--- /dev/null
+++ b/packages/connector-data/src/github/loaders.ts
@@ -0,0 +1,265 @@
+import { withConnectorRetry } from '../retry';
+import type { GitHubConnectorTransport, GitHubGraphQLClient } from './graphql/client';
+import {
+ CONTRIBUTIONS_QUERY,
+ ContributionsQueryResponseSchema,
+} from './graphql/queries/contributions';
+import {
+ ORGANIZATIONS_QUERY,
+ OrganizationsQueryResponseSchema,
+} from './graphql/queries/organizations';
+import { PROFILE_QUERY, ProfileQueryResponseSchema } from './graphql/queries/profile';
+import {
+ PROFILE_README_QUERY,
+ ProfileReadmeQueryResponseSchema,
+} from './graphql/queries/profileReadme';
+import {
+ REPOSITORIES_QUERY,
+ RepositoriesQueryResponseSchema,
+} from './graphql/queries/repositories';
+import type {
+ GitHubContribution,
+ GitHubOrganization,
+ GitHubPullRequest,
+ GitHubRepository,
+ GitHubRepositoryContributor,
+ GitHubUserProfile,
+} from './types';
+
+const MAX_CONTRIBUTIONS = 40;
+const MAX_CONTRIBUTORS = 5;
+const MAX_PROFILE_FIELD_LENGTH = 500;
+const MAX_PROFILE_README_SOURCE_CHARS = 40_000;
+const RECENT_CONTRIBUTION_WINDOW_MS = 180 * 24 * 60 * 60 * 1000;
+
+const clean = (value: string | null | undefined) => {
+ const normalized = value?.replaceAll('\u0000', '').trim();
+ return normalized || undefined;
+};
+
+const cleanBounded = (value: string | null | undefined, limit: number) => {
+ const normalized = clean(value);
+ if (!normalized || normalized.length <= limit) return normalized;
+ return `${normalized.slice(0, limit).trimEnd()}...`;
+};
+
+const normalizeRepository = (repository: {
+ description: string | null;
+ forkCount?: number;
+ issues?: { totalCount: number };
+ nameWithOwner: string;
+ primaryLanguage: { name: string } | null;
+ pullRequests?: { totalCount: number };
+ pushedAt?: string | null;
+ repositoryTopics?: { nodes: Array<{ topic: { name: string } } | null> };
+ stargazerCount: number;
+}): GitHubRepository => ({
+ description: clean(repository.description),
+ forkCount: repository.forkCount,
+ issueCount: repository.issues?.totalCount,
+ nameWithOwner: repository.nameWithOwner,
+ primaryLanguage: clean(repository.primaryLanguage?.name),
+ pullRequestCount: repository.pullRequests?.totalCount,
+ pushedAt: clean(repository.pushedAt),
+ stargazerCount: repository.stargazerCount,
+ topics:
+ repository.repositoryTopics?.nodes
+ .flatMap((node) => clean(node?.topic.name) ?? [])
+ .slice(0, 10) ?? [],
+});
+
+const normalizePullRequest = (pullRequest: {
+ number: number;
+ repository: { nameWithOwner: string };
+ title: string;
+ updatedAt: string;
+}): GitHubPullRequest => ({
+ number: pullRequest.number,
+ repository: clean(pullRequest.repository.nameWithOwner),
+ title: clean(pullRequest.title),
+ updatedAt: pullRequest.updatedAt,
+});
+
+export const loadProfileBundle = async (client: GitHubGraphQLClient) =>
+ client.execute({
+ operation: 'ConnectorDataGitHubProfile',
+ query: PROFILE_QUERY,
+ schema: ProfileQueryResponseSchema,
+ variables: {},
+ });
+
+export const loadUserProfile = async (
+ profileBundle: Awaited<ReturnType<typeof loadProfileBundle>>,
+ transport: GitHubConnectorTransport,
+): Promise<GitHubUserProfile> => {
+ const authenticated = await withConnectorRetry(() => transport.getAuthenticatedUser(), {
+ code: 'github_request_failed',
+ operation: 'getAuthenticatedUser',
+ provider: 'github',
+ });
+ const { viewer } = profileBundle;
+
+ return {
+ bio: clean(viewer.bio),
+ company: clean(viewer.company),
+ externalAccountId: String(authenticated.id),
+ location: clean(viewer.location),
+ login: viewer.login,
+ name: clean(viewer.name),
+ pronouns: clean(viewer.pronouns),
+ websiteUrl: cleanBounded(viewer.websiteUrl, MAX_PROFILE_FIELD_LENGTH),
+ };
+};
+
+export const loadOrganizations = async (
+ client: GitHubGraphQLClient,
+): Promise<GitHubOrganization[]> => {
+ const response = await client.execute({
+ operation: 'ConnectorDataGitHubOrganizations',
+ query: ORGANIZATIONS_QUERY,
+ schema: OrganizationsQueryResponseSchema,
+ variables: {},
+ });
+
+ return response.viewer.organizations.nodes.flatMap((organization) =>
+ organization
+ ? [
+ {
+ description: clean(organization.description),
+ followerCount: organization.followers.totalCount,
+ login: clean(organization.login),
+ name: clean(organization.name),
+ repositoryCount: organization.repositories.totalCount,
+ },
+ ]
+ : [],
+ );
+};
+
+export const loadProfileReadme = async (
+ client: GitHubGraphQLClient,
+ login: string,
+): Promise<string | undefined> => {
+ const response = await client.execute({
+ operation: 'ConnectorDataGitHubProfileReadme',
+ query: PROFILE_README_QUERY,
+ schema: ProfileReadmeQueryResponseSchema,
+ variables: { name: login },
+ });
+ const text = clean(response.viewer.repository?.object?.text);
+
+ return text?.slice(0, MAX_PROFILE_README_SOURCE_CHARS);
+};
+
+export const loadRepositories = async (client: GitHubGraphQLClient) => {
+ const response = await client.execute({
+ operation: 'ConnectorDataGitHubRepositories',
+ query: REPOSITORIES_QUERY,
+ schema: RepositoriesQueryResponseSchema,
+ variables: { first: 12, pullFirst: 4 },
+ });
+
+ return {
+ pinned: response.viewer.pinnedItems.nodes.flatMap((item) =>
+ item ? [normalizeRepository(item)] : [],
+ ),
+ pulls: response.viewer.pullRequests.nodes.flatMap((item) =>
+ item ? [normalizePullRequest(item)] : [],
+ ),
+ recent: response.viewer.repositories.nodes.flatMap((item) =>
+ item ? [normalizeRepository(item)] : [],
+ ),
+ };
+};
+
+export const loadContributions = async (
+ client: GitHubGraphQLClient,
+): Promise<GitHubContribution[]> => {
+ const response = await client.execute({
+ operation: 'ConnectorDataGitHubContributions',
+ query: CONTRIBUTIONS_QUERY,
+ schema: ContributionsQueryResponseSchema,
+ variables: {
+ contributionFirst: 10,
+ from: new Date(Date.now() - RECENT_CONTRIBUTION_WINDOW_MS).toISOString(),
+ },
+ });
+ const collection = response.viewer.contributionsCollection;
+ const contributions: GitHubContribution[] = [];
+
+ for (const item of collection.pullRequestContributions.nodes) {
+ if (!item) continue;
+ contributions.push({
+ count: 1,
+ occurredAt: item.occurredAt,
+ repository: item.pullRequest.repository.nameWithOwner,
+ title: item.pullRequest.title,
+ type: 'pull_request',
+ });
+ }
+ for (const item of collection.issueContributions.nodes) {
+ if (!item) continue;
+ contributions.push({
+ count: 1,
+ occurredAt: item.occurredAt,
+ repository: item.issue.repository.nameWithOwner,
+ title: item.issue.title,
+ type: 'issue',
+ });
+ }
+ for (const item of collection.pullRequestReviewContributions.nodes) {
+ if (!item) continue;
+ const pullRequest = item.pullRequestReview.pullRequest;
+ contributions.push({
+ count: 1,
+ occurredAt: item.occurredAt,
+ repository: pullRequest.repository.nameWithOwner,
+ title: `Reviewed: ${pullRequest.title}`,
+ type: 'pull_request_review',
+ });
+ }
+ for (const group of collection.commitContributionsByRepository) {
+ if (!group) continue;
+ for (const item of group.contributions.nodes) {
+ if (!item?.commitCount) continue;
+ contributions.push({
+ count: item.commitCount,
+ occurredAt: item.occurredAt,
+ repository: group.repository.nameWithOwner,
+ title: `${item.commitCount} commit${item.commitCount === 1 ? '' : 's'}`,
+ type: 'commit',
+ });
+ }
+ }
+
+ return contributions
+ .sort((left, right) => String(right.occurredAt).localeCompare(String(left.occurredAt)))
+ .slice(0, MAX_CONTRIBUTIONS);
+};
+
+export const loadRepositoryContributors = async (
+ transport: GitHubConnectorTransport,
+ repository: string,
+): Promise<GitHubRepositoryContributor[]> => {
+ const [owner, repositoryName, ...rest] = repository.split('/');
+ if (!owner || !repositoryName || rest.length > 0) return [];
+
+ const contributors = await withConnectorRetry(
+ () =>
+ transport.listRepositoryContributors({
+ owner,
+ perPage: MAX_CONTRIBUTORS,
+ repository: repositoryName,
+ }),
+ {
+ code: 'github_request_failed',
+ operation: 'listRepositoryContributors',
+ provider: 'github',
+ },
+ );
+
+ return contributors.slice(0, MAX_CONTRIBUTORS).map(({ contributions, login }) => ({
+ contributionCount: contributions,
+ login: clean(login),
+ }));
+};
diff --git a/packages/connector-data/src/github/types.ts b/packages/connector-data/src/github/types.ts
new file mode 100644
index 00000000000..fbbc9554947
--- /dev/null
+++ b/packages/connector-data/src/github/types.ts
@@ -0,0 +1,61 @@
+export interface GitHubUserProfile {
+ bio?: string;
+ company?: string;
+ externalAccountId: string;
+ location?: string;
+ login: string;
+ name?: string;
+ pronouns?: string;
+ websiteUrl?: string;
+}
+
+export interface GitHubOrganization {
+ description?: string;
+ followerCount?: number;
+ login?: string;
+ name?: string;
+ repositoryCount?: number;
+}
+
+export interface GitHubRepository {
+ description?: string;
+ forkCount?: number;
+ issueCount?: number;
+ nameWithOwner: string;
+ primaryLanguage?: string;
+ pullRequestCount?: number;
+ pushedAt?: string;
+ stargazerCount?: number;
+ topics: string[];
+}
+
+export interface GitHubPullRequest {
+ number?: number;
+ repository?: string;
+ title?: string;
+ updatedAt?: string;
+}
+
+export interface GitHubRepositoryContributor {
+ contributionCount?: number;
+ login?: string;
+}
+
+export interface GitHubContribution {
+ count?: number;
+ occurredAt?: string;
+ repository?: string;
+ title: string;
+ type: 'commit' | 'issue' | 'pull_request' | 'pull_request_review';
+}
+
+export interface GitHubUserContext {
+ organizations?: GitHubOrganization[];
+ pinnedRepositories?: GitHubRepository[];
+ profile: GitHubUserProfile;
+ profileReadme?: string;
+ recentContributions?: GitHubContribution[];
+ recentPullRequests?: GitHubPullRequest[];
+ recentRepositories?: GitHubRepository[];
+ repositoryContributors?: Record<string, GitHubRepositoryContributor[]>;
+}
diff --git a/packages/connector-data/src/index.ts b/packages/connector-data/src/index.ts
new file mode 100644
index 00000000000..1ed6574a7c6
--- /dev/null
+++ b/packages/connector-data/src/index.ts
@@ -0,0 +1,3 @@
+export * from './errors';
+export * from './github';
+export * from './retry';
diff --git a/packages/connector-data/src/retry.test.ts b/packages/connector-data/src/retry.test.ts
new file mode 100644
index 00000000000..3129c0fed1a
--- /dev/null
+++ b/packages/connector-data/src/retry.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { ConnectorDataError } from './errors';
+import { withConnectorRetry } from './retry';
+
+const retryOptions = {
+ code: 'github_request_failed',
+ delay: async () => {},
+ operation: 'listRepositories',
+ provider: 'github',
+} as const;
+
+describe('withConnectorRetry', () => {
+ it('retries a transient 503 and succeeds on the third total attempt', async () => {
+ const operation = vi
+ .fn<() => Promise<string>>()
+ .mockRejectedValueOnce({ status: 503 })
+ .mockRejectedValueOnce({ status: 503 })
+ .mockResolvedValueOnce('ok');
+
+ await expect(withConnectorRetry(operation, retryOptions)).resolves.toBe('ok');
+ expect(operation).toHaveBeenCalledTimes(3);
+ });
+
+ it.each([401, 403, 404])('does not retry status %i', async (status) => {
+ const operation = vi.fn<() => Promise<never>>().mockRejectedValue({
+ message: 'unsafe upstream response body with token=secret',
+ status,
+ });
+
+ await expect(withConnectorRetry(operation, retryOptions)).rejects.toMatchObject({
+ code: 'github_request_failed',
+ message: 'github listRepositories failed',
+ operation: 'listRepositories',
+ provider: 'github',
+ retryable: false,
+ });
+ expect(operation).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([501, 505])('does not retry non-transient server status %i', async (status) => {
+ const operation = vi.fn<() => Promise<never>>().mockRejectedValue({ status });
+
+ await expect(withConnectorRetry(operation, retryOptions)).rejects.toBeInstanceOf(
+ ConnectorDataError,
+ );
+ expect(operation).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([500, 502, 503, 504])('retries transient server status %i', async (status) => {
+ const operation = vi
+ .fn<() => Promise<string>>()
+ .mockRejectedValueOnce({ status })
+ .mockResolvedValueOnce('ok');
+
+ await expect(withConnectorRetry(operation, retryOptions)).resolves.toBe('ok');
+ expect(operation).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([{ code: 'ETIMEDOUT' }, { status: 503 }])(
+ 'marks an exhausted transient error as retryable',
+ async (upstreamError) => {
+ const operation = vi.fn<() => Promise<never>>().mockRejectedValue(upstreamError);
+
+ await expect(withConnectorRetry(operation, retryOptions)).rejects.toMatchObject({
+ message: 'github listRepositories failed',
+ retryable: true,
+ });
+ expect(operation).toHaveBeenCalledTimes(3);
+ },
+ );
+
+ it('preserves a terminal ConnectorDataError', async () => {
+ const upstreamError = new ConnectorDataError({
+ code: 'github_invalid_request',
+ operation: 'getRepository',
+ provider: 'github',
+ retryable: false,
+ });
+
+ await expect(
+ withConnectorRetry(async () => {
+ throw upstreamError;
+ }, retryOptions),
+ ).rejects.toBe(upstreamError);
+ });
+
+ it('sanitizes an unknown terminal error', async () => {
+ const unsafeMessage = 'upstream response token=secret';
+
+ await expect(
+ withConnectorRetry(async () => {
+ throw new Error(unsafeMessage);
+ }, retryOptions),
+ ).rejects.toEqual(
+ expect.objectContaining({
+ code: 'github_request_failed',
+ message: 'github listRepositories failed',
+ operation: 'listRepositories',
+ provider: 'github',
+ retryable: false,
+ }),
+ );
+
+ try {
+ await withConnectorRetry(async () => {
+ throw new Error(unsafeMessage);
+ }, retryOptions);
+ } catch (error) {
+ expect(error).toBeInstanceOf(ConnectorDataError);
+ expect((error as Error).message).not.toContain(unsafeMessage);
+ }
+ });
+});
diff --git a/packages/connector-data/src/retry.ts b/packages/connector-data/src/retry.ts
new file mode 100644
index 00000000000..578c2a37315
--- /dev/null
+++ b/packages/connector-data/src/retry.ts
@@ -0,0 +1,100 @@
+import type { ConnectorDataErrorOptions, ConnectorDataProvider } from './errors';
+import { ConnectorDataError } from './errors';
+
+const DEFAULT_ATTEMPTS = 3;
+const FIRST_RETRY_DELAY_MS = 250;
+const SECOND_RETRY_DELAY_MS = 500;
+const TRANSIENT_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);
+const TRANSIENT_NETWORK_CODES = new Set([
+ 'ECONNABORTED',
+ 'ECONNRESET',
+ 'EHOSTUNREACH',
+ 'ENETUNREACH',
+ 'ETIMEDOUT',
+]);
+
+export type ConnectorRetryDelay = (milliseconds: number) => Promise<void>;
+
+export interface ConnectorRetryOptions {
+ code: string;
+ delay?: ConnectorRetryDelay;
+ operation: string;
+ provider: ConnectorDataProvider;
+}
+
+const defaultDelay: ConnectorRetryDelay = async (milliseconds) => {
+ await new Promise((resolve) => setTimeout(resolve, milliseconds));
+};
+
+const getRetryDelay = (attempt: number) =>
+ attempt === 0 ? FIRST_RETRY_DELAY_MS : SECOND_RETRY_DELAY_MS;
+
+const getErrorStatus = (error: unknown): number | undefined => {
+ if (typeof error !== 'object' || error === null) return;
+
+ const { response, status, statusCode } = error as {
+ response?: { status?: unknown };
+ status?: unknown;
+ statusCode?: unknown;
+ };
+ const candidate = status ?? statusCode ?? response?.status;
+
+ return typeof candidate === 'number' ? candidate : undefined;
+};
+
+const getErrorCode = (error: unknown): string | undefined => {
+ if (typeof error !== 'object' || error === null || !('code' in error)) return;
+
+ const { code } = error as { code?: unknown };
+ return typeof code === 'string' ? code : undefined;
+};
+
+const isTransientError = (error: unknown) => {
+ if (error instanceof ConnectorDataError) return error.retryable;
+
+ const status = getErrorStatus(error);
+ if (status !== undefined) {
+ if (status === 401 || status === 403 || status === 404) return false;
+
+ return TRANSIENT_HTTP_STATUSES.has(status);
+ }
+
+ const code = getErrorCode(error);
+ return code !== undefined && TRANSIENT_NETWORK_CODES.has(code);
+};
+
+export const withConnectorRetry = async <T>(
+ operation: () => Promise<T>,
+ { code, delay = defaultDelay, operation: operationName, provider }: ConnectorRetryOptions,
+): Promise<T> => {
+ for (let attempt = 0; attempt < DEFAULT_ATTEMPTS; attempt += 1) {
+ try {
+ return await operation();
+ } catch (error) {
+ const retryable = isTransientError(error);
+ const canRetry = attempt < DEFAULT_ATTEMPTS - 1 && retryable;
+
+ if (canRetry) {
+ await delay(getRetryDelay(attempt));
+ continue;
+ }
+
+ if (error instanceof ConnectorDataError) throw error;
+
+ const errorOptions: ConnectorDataErrorOptions = {
+ code,
+ operation: operationName,
+ provider,
+ retryable,
+ };
+ throw new ConnectorDataError(errorOptions);
+ }
+ }
+
+ throw new ConnectorDataError({
+ code,
+ operation: operationName,
+ provider,
+ retryable: false,
+ });
+};
diff --git a/packages/connector-data/vitest.config.mts b/packages/connector-data/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/connector-data/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});