Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🔌 feat: Enable Pull Requests by Default With a Token Fallback (#16876)

Marco Beretta1692814a304f
diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js
index c6386d6867..22bbe5ccd0 100644
--- a/api/server/routes/__tests__/config.spec.js
+++ b/api/server/routes/__tests__/config.spec.js
@@ -671,43 +671,65 @@ describe('GET /api/config', () => {
expect(response.body.insightsEnabled).toBe(true);
});
- it.each([
- ['unset', undefined, false],
- ['disabled', { enabled: false }, false],
- ['enabled', { enabled: true }, true],
- ])(
- 'should advertise pull requests only when they are enabled (%s)',
- async (_label, pullRequests, expected) => {
+ describe('pull requests', () => {
+ const savedEnv = { GITHUB_TOKEN: process.env.GITHUB_TOKEN, GH_TOKEN: process.env.GH_TOKEN };
+ beforeEach(() => {
+ delete process.env.GITHUB_TOKEN;
+ delete process.env.GH_TOKEN;
+ delete process.env.GITHUB_PULL_REQUEST_TOKEN;
+ });
+ afterEach(() => {
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ it.each([
+ ['unset', undefined, 'tok', false],
+ ['switched off', { enabled: false, allowAllRepositories: true }, 'tok', false],
+ ['scoped but without any token', { allowAllRepositories: true }, undefined, false],
+ ['a token but no repository scope', { enabled: true }, 'tok', false],
+ ['scoped with a token, no enabled switch', { allowAllRepositories: true }, 'tok', true],
+ ['listed repositories with a token', { allowedRepositories: ['o/r'] }, 'tok', true],
+ ])(
+ 'should advertise pull requests only when they can work (%s)',
+ async (_label, pullRequests, token, expected) => {
+ if (token) process.env.GITHUB_TOKEN = token;
+ mockGetAppConfig.mockResolvedValue({
+ ...baseAppConfig,
+ endpoints: { agents: pullRequests ? { pullRequests } : {} },
+ });
+ const response = await request(createApp(mockUser)).get('/api/config');
+ expect(response.body.pullRequestsEnabled).toBe(expected);
+ /** The batch route's version rides with the flag, so a client never sees one without the other. */
+ if (expected) {
+ expect(response.body.pullRequestsBatchVersion).toBe(1);
+ expect(response.body.pullRequestsMaxConcurrentLookups).toBe(4);
+ } else {
+ expect(response.body).not.toHaveProperty('pullRequestsBatchVersion');
+ expect(response.body).not.toHaveProperty('pullRequestsMaxConcurrentLookups');
+ }
+ },
+ );
+
+ it('advertises the configured lookup limit so a fallback client can keep to it', async () => {
+ process.env.GITHUB_TOKEN = 'tok';
mockGetAppConfig.mockResolvedValue({
...baseAppConfig,
- endpoints: { agents: pullRequests ? { pullRequests } : {} },
+ endpoints: {
+ agents: { pullRequests: { allowAllRepositories: true, maxConcurrentLookups: 2 } },
+ },
});
const response = await request(createApp(mockUser)).get('/api/config');
- expect(response.body.pullRequestsEnabled).toBe(expected);
- /** The batch route's version rides with the flag, so a client never sees one without the other. */
- if (expected) {
- expect(response.body.pullRequestsBatchVersion).toBe(1);
- expect(response.body.pullRequestsMaxConcurrentLookups).toBe(4);
- } else {
- expect(response.body).not.toHaveProperty('pullRequestsBatchVersion');
- expect(response.body).not.toHaveProperty('pullRequestsMaxConcurrentLookups');
- }
- },
- );
-
- it('advertises the configured lookup limit so a fallback client can keep to it', async () => {
- mockGetAppConfig.mockResolvedValue({
- ...baseAppConfig,
- endpoints: { agents: { pullRequests: { enabled: true, maxConcurrentLookups: 2 } } },
+ expect(response.body.pullRequestsMaxConcurrentLookups).toBe(2);
});
- const response = await request(createApp(mockUser)).get('/api/config');
- expect(response.body.pullRequestsMaxConcurrentLookups).toBe(2);
- });
- it('should not advertise pull requests for a config with no endpoints', async () => {
- mockGetAppConfig.mockResolvedValue(baseAppConfig);
- const response = await request(createApp(mockUser)).get('/api/config');
- expect(response.body.pullRequestsEnabled).toBe(false);
+ it('should not advertise pull requests for a config with no endpoints', async () => {
+ mockGetAppConfig.mockResolvedValue(baseAppConfig);
+ const response = await request(createApp(mockUser)).get('/api/config');
+ expect(response.body.pullRequestsEnabled).toBe(false);
+ });
});
it('should advertise Langfuse fanout only when the toggle and collector URL are configured', async () => {
diff --git a/api/server/routes/config.js b/api/server/routes/config.js
index 62b0b7eb19..fa59dde953 100644
--- a/api/server/routes/config.js
+++ b/api/server/routes/config.js
@@ -332,7 +332,7 @@ router.get('/', async function (req, res) {
langfuseConnectionAccess,
insightsEnabled: isEnabled(process.env.ENABLE_INSIGHTS),
/** Lets the client skip the pull request lookup entirely when the feature is off. */
- ...resolvePullRequestCapabilities(appConfig),
+ ...resolvePullRequestCapabilities(appConfig, process.env),
compactionEnabled: appConfig?.summarization?.enabled !== false,
...(codeEnvironmentDecisionVersion != null ? { codeEnvironmentDecisionVersion } : {}),
mcpApps: resolveMCPAppsPolicy(
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index 446fe54004..e6a6edce3b 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -51,6 +51,7 @@ const {
isFatalAgentInitializationError,
codeExecutionAuthHeaders,
createLaneGitRecorder,
+ isPullRequestFeatureActive,
createAttachedWorkspaceBashTool,
createRepositoryInstructionSource,
createRepositoryInstructionLoader,
@@ -2368,7 +2369,10 @@ async function loadToolsForExecution({
workspaceId: codeExecutionContext.codeWorkspace.workspaceId,
workspaceInstanceId: codeExecutionContext.codeWorkspace.workspaceInstanceId,
onLaneGit: await createLaneGitRecorder({
- enabled: req.config?.endpoints?.agents?.pullRequests?.enabled === true,
+ enabled: isPullRequestFeatureActive(
+ req.config?.endpoints?.agents?.pullRequests,
+ process.env,
+ ),
user: req.user.id,
conversationId: conversationId ?? runtimeRequestBody?.conversationId,
repo: codeExecutionContext.codeWorkspace.environment?.repo,
diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.js
index 213827e73f..5e5180e985 100644
--- a/api/server/services/__tests__/ToolService.spec.js
+++ b/api/server/services/__tests__/ToolService.spec.js
@@ -227,6 +227,10 @@ function createEndpointsConfig(capabilities) {
};
}
+beforeAll(() => {
+ process.env.GITHUB_TOKEN = process.env.GITHUB_TOKEN || 'ghp_test';
+});
+
describe('ToolService - Action Capability Gating', () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -3230,7 +3234,7 @@ describe('ToolService - Action Capability Gating', () => {
AgentCapabilities.stateful_code_sessions,
];
const req = createMockReq(capabilities);
- req.config.endpoints[EModelEndpoint.agents].pullRequests = { enabled: true };
+ req.config.endpoints[EModelEndpoint.agents].pullRequests = { allowAllRepositories: true };
req.body = {
conversationId: 'body-convo',
codeWorkspaces: [{ environmentId: 'personal-machine', workspaceId: 'project-a' }],
@@ -3287,7 +3291,7 @@ describe('ToolService - Action Capability Gating', () => {
AgentCapabilities.stateful_code_sessions,
];
const req = createMockReq(capabilities);
- req.config.endpoints[EModelEndpoint.agents].pullRequests = { enabled: true };
+ req.config.endpoints[EModelEndpoint.agents].pullRequests = { allowAllRepositories: true };
req.resolvedConversation = {
conversationId: 'resolved-convo',
codeWorkspaces: [{ environmentId: 'personal-machine', workspaceId: 'project-a' }],
diff --git a/librechat.example.yaml b/librechat.example.yaml
index a22a981ad5..f1c89cf082 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -924,20 +924,27 @@ endpoints:
# completionReceiptBatching: true
# # Allow owners to cooperatively cancel ordinary background tools, including BYOM Bash.
# ordinaryToolCancellation: false
- # # (optional) Show a conversation's pull request in the chat header. Off by default. It needs
- # # a code worker built from LibreChat-AI/code-interpreter#311 or later that reports its
- # # branch, with CODEAPI_BRIDGE_LANE_GIT=true set on the Code API; without both, every chat
- # # simply shows no pull request. It also needs a GitHub token held on the server. Use a
- # # fine-grained token limited to the repositories involved, with read-only "Pull requests",
- # # "Checks" and "Contents" permissions. Without "Checks" every matched pull request fails to
- # # load, and without "Contents" a chat whose branch has moved on since its last command does.
+ # # (optional) Show a conversation's pull request in the chat header and the sidebar. It is on
+ # # as soon as the server has a GitHub token and a repository scope, with no switch needed:
+ # # the token is `token` below, else the first of GITHUB_PULL_REQUEST_TOKEN, GITHUB_TOKEN and
+ # # GH_TOKEN that is set, and the scope is `allowedRepositories` or `allowAllRepositories`.
+ # # Without either, every chat simply shows no pull request. It also needs a code worker built
+ # # from LibreChat-AI/code-interpreter#311 or later that reports its branch, with
+ # # CODEAPI_BRIDGE_LANE_GIT=true set on the Code API. Use a fine-grained token limited to the
+ # # repositories involved, with read-only "Pull requests", "Checks" and "Contents" permissions.
+ # # Without "Checks" every matched pull request fails to load, and without "Contents" a chat
+ # # whose branch has moved on since its last command does.
# pullRequests:
- # enabled: false
- # # Environment variable reference only, never the token itself.
+ # enabled: true # set false to turn the feature off
+ # # Environment variable reference only, never the token itself. Optional, see above.
# token: "${GITHUB_PULL_REQUEST_TOKEN}"
- # # Repositories the token may be used for, as owner/name or owner/*. Required: a worker
- # # reports its own repository, and only these are ever looked up with the server's token.
+ # # Repositories the token may be used for, as owner/name or owner/*. A worker reports its
+ # # own repository, and only these are ever looked up with the server's token.
# allowedRepositories: ["LibreChat-AI/LibreChat"]
+ # # Or look up every repository a worker reports, limited only by what the token can read.
+ # # Off by default: any user could then point the server's token at any repository it can
+ # # see, so use a read-only token scoped to the repositories you are willing to show.
+ # allowAllRepositories: false
# # Seconds a looked-up pull request is reused before GitHub is asked again (5 to 3600).
# cacheTtlSeconds: 30
# # Results cached per credential before the oldest is evicted (10 to 100000). Raise it when many
diff --git a/packages/api/src/pulls/capabilities.spec.ts b/packages/api/src/pulls/capabilities.spec.ts
index dd4288ad5e..7c93e93b2c 100644
--- a/packages/api/src/pulls/capabilities.spec.ts
+++ b/packages/api/src/pulls/capabilities.spec.ts
@@ -5,9 +5,12 @@ import { resolvePullRequestCapabilities } from './capabilities';
const configWith = (pullRequests?: Record<string, unknown>) =>
({ endpoints: { agents: pullRequests ? { pullRequests } : {} } }) as unknown as AppConfig;
+const env = { GITHUB_TOKEN: 't' };
+const scoped = { allowAllRepositories: true };
+
describe('resolvePullRequestCapabilities', () => {
it('advertises the flag, the batch version and the lookup limit together when the feature is on', () => {
- expect(resolvePullRequestCapabilities(configWith({ enabled: true }))).toEqual({
+ expect(resolvePullRequestCapabilities(configWith(scoped), env)).toEqual({
pullRequestsEnabled: true,
pullRequestsBatchVersion: PULL_REQUEST_BATCH_VERSION,
pullRequestsMaxConcurrentLookups: 4,
@@ -16,7 +19,7 @@ describe('resolvePullRequestCapabilities', () => {
it('advertises the configured lookup limit', () => {
expect(
- resolvePullRequestCapabilities(configWith({ enabled: true, maxConcurrentLookups: 2 })),
+ resolvePullRequestCapabilities(configWith({ ...scoped, maxConcurrentLookups: 2 }), env),
).toMatchObject({ pullRequestsMaxConcurrentLookups: 2 });
});
@@ -25,12 +28,24 @@ describe('resolvePullRequestCapabilities', () => {
['a null config', null],
['a config without endpoints', {} as AppConfig],
['no pull request settings', configWith()],
- ['the feature switched off', configWith({ enabled: false })],
- ['a non-true value', configWith({ enabled: 'yes' })],
+ ['the feature switched off', configWith({ ...scoped, enabled: false })],
+ ['no repository scope', configWith({ enabled: true })],
])('advertises neither the flag nor a version with %s', (_label, appConfig) => {
- const capabilities = resolvePullRequestCapabilities(appConfig);
+ const capabilities = resolvePullRequestCapabilities(appConfig, env);
expect(capabilities).toEqual({ pullRequestsEnabled: false });
expect(capabilities).not.toHaveProperty('pullRequestsBatchVersion');
expect(capabilities).not.toHaveProperty('pullRequestsMaxConcurrentLookups');
});
+
+ it('is on by default once a token exists and a scope is set, with no enabled switch', () => {
+ expect(resolvePullRequestCapabilities(configWith(scoped), env)).toMatchObject({
+ pullRequestsEnabled: true,
+ });
+ });
+
+ it('advertises nothing when there is no token to read with', () => {
+ expect(resolvePullRequestCapabilities(configWith(scoped), {})).toEqual({
+ pullRequestsEnabled: false,
+ });
+ });
});
diff --git a/packages/api/src/pulls/capabilities.ts b/packages/api/src/pulls/capabilities.ts
index 846d876d6e..9f481c3bf6 100644
--- a/packages/api/src/pulls/capabilities.ts
+++ b/packages/api/src/pulls/capabilities.ts
@@ -1,6 +1,7 @@
import { EModelEndpoint, PULL_REQUEST_BATCH_VERSION } from 'librechat-data-provider';
import type { TAgentsEndpoint } from 'librechat-data-provider';
import type { AppConfig } from '@librechat/data-schemas';
+import { isPullRequestFeatureActive } from './settings';
export type PullRequestCapabilities = {
pullRequestsEnabled: boolean;
@@ -13,14 +14,15 @@ export type PullRequestCapabilities = {
/**
* What the startup config tells a client about pull requests: whether the deployment turned the
- * feature on, and, once it has, which version of the batch route this server serves, so the
+ * feature on (by default whenever a token and a repository scope exist), and which version of the batch route this server serves, so the
* sidebar asks only a server that has it.
*/
export function resolvePullRequestCapabilities(
appConfig: Pick<AppConfig, 'endpoints'> | null | undefined,
+ env: Readonly<Record<string, string | undefined>> = {},
): PullRequestCapabilities {
const agents = appConfig?.endpoints?.[EModelEndpoint.agents] as TAgentsEndpoint | undefined;
- const enabled = agents?.pullRequests?.enabled === true;
+ const enabled = isPullRequestFeatureActive(agents?.pullRequests, env);
return {
pullRequestsEnabled: enabled,
...(enabled
diff --git a/packages/api/src/pulls/handler.spec.ts b/packages/api/src/pulls/handler.spec.ts
index dfbeaddede..f44e9de964 100644
--- a/packages/api/src/pulls/handler.spec.ts
+++ b/packages/api/src/pulls/handler.spec.ts
@@ -4,8 +4,8 @@ import type { ServerRequest } from '~/types';
import {
createConversationPullRequestHandler,
createConversationPullRequestsHandler,
- resolveTokenReference,
} from './handler';
+import { resolveTokenReference } from './settings';
jest.mock('@librechat/data-schemas', () => ({
...jest.requireActual('@librechat/data-schemas'),
@@ -140,6 +140,79 @@ describe('createConversationPullRequestHandler', () => {
expect(lookup).toHaveBeenCalledWith(expect.objectContaining({ head }));
});
+ describe('without an enabled switch or a token reference', () => {
+ const scoped = { allowedRepositories: ['o/r'] };
+
+ it('looks the pull request up, using the deployment GitHub token', async () => {
+ const { run, res, lookup } = setup({ settings: scoped, env: { GITHUB_TOKEN: 'ghp_deploy' } });
+ await run();
+ expect(lookup).toHaveBeenCalledWith(expect.objectContaining({ token: 'ghp_deploy' }));
+ expect(res.json).toHaveBeenCalledWith({ pullRequest: pr });
+ });
+
+ it('answers no pull request, and reads nothing, with no token anywhere', async () => {
+ const { run, res, lookup } = setup({ settings: scoped, env: {} });
+ await run();
+ expect(lookup).not.toHaveBeenCalled();
+ expect(res.json).toHaveBeenCalledWith({ pullRequest: null });
+ });
+
+ it('still reports a configured reference that does not resolve', async () => {
+ const { run, res } = setup({
+ settings: { ...scoped, token: '${MISSING}' },
+ env: { GITHUB_TOKEN: 'ghp_deploy' },
+ });
+ await run();
+ expect(res.status).toHaveBeenCalledWith(503);
+ expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ code: 'NOT_CONFIGURED' }));
+ });
+
+ it('is off when switched off, even with a token and a scope', async () => {
+ const { run, res, lookup } = setup({
+ settings: { ...scoped, enabled: false },
+ env: { GITHUB_TOKEN: 'ghp_deploy' },
+ });
+ await run();
+ expect(lookup).not.toHaveBeenCalled();
+ expect(res.json).toHaveBeenCalledWith({ pullRequest: null });
+ });
+ });
+
+ describe('allowAllRepositories', () => {
+ const lane = { branch: 'feat/x', head: null, repo: 'someone/else' };
+ const open = { allowAllRepositories: true };
+
+ it('looks up a repository nobody listed, when the administrator opted in', async () => {
+ const { run, lookup } = setup({
+ settings: open,
+ laneGit: lane,
+ env: { GITHUB_TOKEN: 'ghp_deploy' },
+ });
+ await run();
+ expect(lookup).toHaveBeenCalledWith(expect.objectContaining({ repo: 'someone/else' }));
+ });
+
+ it('passes the open scope on, so a fork named by the worker is authorized the same way', async () => {
+ const { run, lookup } = setup({
+ settings: open,
+ laneGit: lane,
+ env: { GITHUB_TOKEN: 'ghp_deploy' },
+ });
+ await run();
+ expect(lookup.mock.calls[0][0].allowedRepositories).toEqual(['*/*']);
+ });
+
+ it('does not look it up without the opt-in, even with a token', async () => {
+ const { run, lookup } = setup({
+ settings: { allowedRepositories: ['o/r'] },
+ laneGit: lane,
+ env: { GITHUB_TOKEN: 'ghp_deploy' },
+ });
+ await run();
+ expect(lookup).not.toHaveBeenCalled();
+ });
+ });
+
describe('repository allowlist', () => {
const lane = (repo: string) => ({ branch: 'feat/x', head: null, repo });
@@ -331,6 +404,18 @@ describe('createConversationPullRequestsHandler', () => {
return { run, res, lookup, getConvosLaneGit };
}
+ it('looks up any repository on the batch route too, when the administrator opted in', async () => {
+ const { run, lookup } = batch({
+ settings: { allowAllRepositories: true },
+ lanes: [
+ { conversationId: 'a', laneGit: { branch: 'feat/x', head: null, repo: 'someone/else' } },
+ ],
+ env: { GITHUB_TOKEN: 'ghp_deploy' },
+ });
+ await run({ conversationIds: ['a'] });
+ expect(lookup).toHaveBeenCalledWith(expect.objectContaining({ repo: 'someone/else' }));
+ });
+
it('answers each conversation in the order asked, from one owner-scoped read', async () => {
const { run, res, getConvosLaneGit, lookup } = batch();
await run({ conversationIds: ['b', 'a'] });
diff --git a/packages/api/src/pulls/handler.ts b/packages/api/src/pulls/handler.ts
index e04e8d7b46..7b5798f6ba 100644
--- a/packages/api/src/pulls/handler.ts
+++ b/packages/api/src/pulls/handler.ts
@@ -11,33 +11,23 @@ import type {
import type { AppConfig } from '@librechat/data-schemas';
import type { Response } from 'express';
import type { GetAppConfigOptions } from '~/app/service';
+import type { PullRequestSettings } from './settings';
import type { PullRequestLookup } from './types';
import type { ServerRequest } from '~/types';
+import { isPullRequestFeatureActive, resolvePullRequestToken } from './settings';
+import { ALL_REPOSITORIES, isAllowedRepository } from './repository';
import { getAppConfigOptionsFromUser } from '~/app/service';
-import { isAllowedRepository } from './repository';
import { getSafeErrorMetadata } from '~/utils';
const MAX_CONVERSATION_ID_LENGTH = 256;
-const TOKEN_REFERENCE = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
export type ConversationLaneGit = { branch: string | null; head: string | null; repo?: string };
-/** Resolves `${NAME}` against the environment; the config never holds the token itself. */
-export function resolveTokenReference(
- reference: string | undefined,
- env: Readonly<Record<string, string | undefined>>,
-): string | null {
- const name = reference == null ? undefined : TOKEN_REFERENCE.exec(reference)?.[1];
- if (name == null) return null;
- return env[name]?.trim() || null;
-}
-
const validConversationId = (value: string | undefined): value is string =>
value != null && value.trim() !== '' && value.length <= MAX_CONVERSATION_ID_LENGTH;
const NONE: TConversationPullRequestResponse = { pullRequest: null };
-type PullRequestSettings = NonNullable<TAgentsEndpoint['pullRequests']>;
type EligibleLane = { branch: string; head: string | null; repo: string };
/** Lookups in flight at once for one batch, unless configured. */
@@ -163,13 +153,17 @@ async function withDeadline<T>(work: Promise<T>, ms: number): Promise<T | typeof
}
}
+/** The list a lane's repository is checked against, and a fork's checks are authorized by. */
+const repositoryScope = (settings: PullRequestSettings): readonly string[] =>
+ settings.allowAllRepositories === true ? ALL_REPOSITORIES : (settings.allowedRepositories ?? []);
+
/** A lane the server's token may be used for: it names a branch and an allowed repository. */
function eligibleLane(
laneGit: ConversationLaneGit | null | undefined,
settings: PullRequestSettings,
): EligibleLane | null {
if (laneGit?.branch == null || laneGit.repo == null) return null;
- if (!isAllowedRepository(laneGit.repo, settings.allowedRepositories)) return null;
+ if (!isAllowedRepository(laneGit.repo, repositoryScope(settings))) return null;
return { branch: laneGit.branch, head: laneGit.head, repo: laneGit.repo };
}
@@ -183,7 +177,7 @@ function lookupInput(settings: PullRequestSettings, token: string, lane: Eligibl
ttlMs: (settings.cacheTtlSeconds ?? 30) * 1000,
cacheMaxEntries: settings.cacheMaxEntries ?? 500,
cacheMaxCredentials: settings.cacheMaxCredentials ?? 256,
- allowedRepositories: settings.allowedRepositories ?? [],
+ allowedRepositories: repositoryScope(settings),
limits: {
requestTimeoutMs: (settings.requestTimeoutSeconds ?? 10) * 1000,
lookupTimeoutMs: (settings.lookupTimeoutSeconds ?? 30) * 1000,
@@ -258,7 +252,7 @@ export function createConversationPullRequestHandler(deps: {
]);
const settings = (appConfig.endpoints?.[EModelEndpoint.agents] as TAgentsEndpoint | undefined)
?.pullRequests;
- if (settings?.enabled !== true) {
+ if (!settings || !isPullRequestFeatureActive(settings, deps.env)) {
res.status(200).json(NONE);
return;
}
@@ -272,7 +266,7 @@ export function createConversationPullRequestHandler(deps: {
return;
}
- const token = resolveTokenReference(settings.token, deps.env);
+ const token = resolvePullRequestToken(settings.token, deps.env);
if (token == null) {
logger.warn('[PullRequests] Enabled without a usable token reference');
res.status(503).json({ error: 'Pull requests are not configured', code: 'NOT_CONFIGURED' });
@@ -354,7 +348,7 @@ export function createConversationPullRequestsHandler(deps: {
const none = (): TConversationPullRequestsResponse => ({
results: ids.map((conversationId) => ({ conversationId, pullRequest: null })),
});
- if (settings?.enabled !== true) {
+ if (!settings || !isPullRequestFeatureActive(settings, deps.env)) {
res.status(200).json(none());
return;
}
@@ -379,7 +373,7 @@ export function createConversationPullRequestsHandler(deps: {
* A missing token is a fact about the conversations that needed one, not about the request:
* those entries say so, and every other conversation keeps its correct "no pull request".
*/
- const token = resolveTokenReference(settings.token, deps.env);
+ const token = resolvePullRequestToken(settings.token, deps.env);
if (token == null) {
logger.warn('[PullRequests] Enabled without a usable token reference');
res.status(200).json({
diff --git a/packages/api/src/pulls/index.ts b/packages/api/src/pulls/index.ts
index 7c5127bb32..f76b51e1a2 100644
--- a/packages/api/src/pulls/index.ts
+++ b/packages/api/src/pulls/index.ts
@@ -2,6 +2,7 @@ export * from './types';
export * from './github';
export * from './lookup';
export * from './handler';
+export * from './settings';
export * from './transport';
export * from './repository';
export * from './capabilities';
diff --git a/packages/api/src/pulls/repository.spec.ts b/packages/api/src/pulls/repository.spec.ts
new file mode 100644
index 0000000000..b1cacc1ba4
--- /dev/null
+++ b/packages/api/src/pulls/repository.spec.ts
@@ -0,0 +1,21 @@
+import { ALL_REPOSITORIES, isAllowedRepository } from './repository';
+
+describe('isAllowedRepository', () => {
+ it.each([
+ ['o/r', ['o/r'], true],
+ ['O/R', ['o/r'], true],
+ ['o/other', ['o/r'], false],
+ ['o/other', ['o/*'], true],
+ ['x/r', ['o/*'], false],
+ ['o/r', [], false],
+ ['o/r', undefined, false],
+ ])('%s against %j is %s', (repo, allowed, expected) => {
+ expect(isAllowedRepository(repo, allowed)).toBe(expected);
+ });
+
+ it('matches any repository for the opt-in list, and only for it', () => {
+ expect(isAllowedRepository('any/thing', ALL_REPOSITORIES)).toBe(true);
+ expect(isAllowedRepository('o/r', ['*/r'])).toBe(true);
+ expect(isAllowedRepository('o/r', ['o/r2'])).toBe(false);
+ });
+});
diff --git a/packages/api/src/pulls/repository.ts b/packages/api/src/pulls/repository.ts
index 3677cd0ba9..85f5114f2b 100644
--- a/packages/api/src/pulls/repository.ts
+++ b/packages/api/src/pulls/repository.ts
@@ -1,8 +1,17 @@
+/**
+ * What `allowAllRepositories` stands for. The config schema cannot produce it (an owner must be a
+ * real name), so only the explicit opt-in can put it in a list.
+ */
+export const ALL_REPOSITORIES: readonly string[] = ['*/*'];
+
/** `owner/name` or `owner/*`, compared without case as GitHub does. Nothing else matches. */
export function isAllowedRepository(repo: string, allowed: readonly string[] | undefined): boolean {
const [owner, name] = repo.toLowerCase().split('/');
return (allowed ?? []).some((entry) => {
const [allowedOwner, allowedName] = entry.toLowerCase().split('/');
- return allowedOwner === owner && (allowedName === '*' || allowedName === name);
+ return (
+ (allowedOwner === '*' || allowedOwner === owner) &&
+ (allowedName === '*' || allowedName === name)
+ );
});
}
diff --git a/packages/api/src/pulls/settings.spec.ts b/packages/api/src/pulls/settings.spec.ts
new file mode 100644
index 0000000000..fb2aa65ecd
--- /dev/null
+++ b/packages/api/src/pulls/settings.spec.ts
@@ -0,0 +1,87 @@
+import {
+ isPullRequestFeatureActive,
+ resolvePullRequestToken,
+ resolveTokenReference,
+} from './settings';
+
+describe('resolvePullRequestToken', () => {
+ it('prefers the configured reference over any fallback', () => {
+ expect(
+ resolvePullRequestToken('${MY_TOKEN}', { MY_TOKEN: 'mine', GITHUB_TOKEN: 'other' }),
+ ).toBe('mine');
+ });
+
+ it('does not fall back when the configured reference does not resolve', () => {
+ expect(resolvePullRequestToken('${MY_TOKEN}', { GITHUB_TOKEN: 'other' })).toBeNull();
+ expect(resolvePullRequestToken('not-a-reference', { GITHUB_TOKEN: 'other' })).toBeNull();
+ });
+
+ it.each([
+ [
+ 'GITHUB_PULL_REQUEST_TOKEN',
+ { GITHUB_PULL_REQUEST_TOKEN: 'a', GITHUB_TOKEN: 'b', GH_TOKEN: 'c' },
+ 'a',
+ ],
+ ['GITHUB_TOKEN', { GITHUB_TOKEN: ' b ', GH_TOKEN: 'c' }, 'b'],
+ ['GH_TOKEN', { GH_TOKEN: 'c' }, 'c'],
+ ])('falls back to %s, in that order', (_name, env, expected) => {
+ expect(resolvePullRequestToken(undefined, env)).toBe(expected);
+ });
+
+ it('is null when no token exists anywhere, or only a blank one', () => {
+ expect(resolvePullRequestToken(undefined, {})).toBeNull();
+ expect(resolvePullRequestToken(undefined, { GITHUB_TOKEN: ' ' })).toBeNull();
+ });
+});
+
+describe('resolveTokenReference', () => {
+ it.each([
+ ['${GH_TOKEN}', { GH_TOKEN: ' abc ' }, 'abc'],
+ ['${GH_TOKEN}', {}, null],
+ ['literal-token', { 'literal-token': 'x' }, null],
+ [undefined, { GH_TOKEN: 'x' }, null],
+ ])('resolves %s', (reference, env, expected) => {
+ expect(resolveTokenReference(reference, env)).toBe(expected);
+ });
+});
+
+describe('isPullRequestFeatureActive', () => {
+ const env = { GITHUB_TOKEN: 't' };
+
+ it('is on without any switch once there is a token and a list of repositories', () => {
+ expect(isPullRequestFeatureActive({ allowedRepositories: ['o/r'] }, env)).toBe(true);
+ });
+
+ it('is on with the opt-in to every repository, and no list', () => {
+ expect(isPullRequestFeatureActive({ allowAllRepositories: true }, env)).toBe(true);
+ });
+
+ it('stays dormant without a repository scope, so a worker cannot name its own', () => {
+ expect(isPullRequestFeatureActive({}, env)).toBe(false);
+ expect(isPullRequestFeatureActive(undefined, env)).toBe(false);
+ expect(isPullRequestFeatureActive({ allowedRepositories: [] }, env)).toBe(false);
+ expect(isPullRequestFeatureActive({ allowAllRepositories: false }, env)).toBe(false);
+ });
+
+ it('stays dormant without any token', () => {
+ expect(isPullRequestFeatureActive({ allowAllRepositories: true }, {})).toBe(false);
+ });
+
+ it('counts a configured reference as a token even before it resolves, so the failure is visible', () => {
+ expect(
+ isPullRequestFeatureActive({ token: '${MISSING}', allowAllRepositories: true }, {}),
+ ).toBe(true);
+ });
+
+ it('is off when an administrator turns it off, whatever else is set', () => {
+ expect(isPullRequestFeatureActive({ enabled: false, allowAllRepositories: true }, env)).toBe(
+ false,
+ );
+ });
+
+ it('is on when explicitly enabled and fully scoped', () => {
+ expect(isPullRequestFeatureActive({ enabled: true, allowAllRepositories: true }, env)).toBe(
+ true,
+ );
+ });
+});
diff --git a/packages/api/src/pulls/settings.ts b/packages/api/src/pulls/settings.ts
new file mode 100644
index 0000000000..f5f0152be6
--- /dev/null
+++ b/packages/api/src/pulls/settings.ts
@@ -0,0 +1,48 @@
+import type { TAgentsEndpoint } from 'librechat-data-provider';
+
+export type PullRequestSettings = NonNullable<TAgentsEndpoint['pullRequests']>;
+
+const TOKEN_REFERENCE = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
+
+/**
+ * Tried in order when `token` is not configured, so a deployment that already holds a GitHub token
+ * for something else gets pull requests without more setup. A token named in the config always
+ * wins, and one that does not resolve is reported instead of silently replaced.
+ */
+const TOKEN_ENV_FALLBACKS = ['GITHUB_PULL_REQUEST_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN'] as const;
+
+type Env = Readonly<Record<string, string | undefined>>;
+
+/** Resolves `${NAME}` against the environment; the config never holds the token itself. */
+export function resolveTokenReference(reference: string | undefined, env: Env): string | null {
+ const name = reference == null ? undefined : TOKEN_REFERENCE.exec(reference)?.[1];
+ if (name == null) return null;
+ return env[name]?.trim() || null;
+}
+
+/** The configured token reference, else the first fallback variable that is set. */
+export function resolvePullRequestToken(reference: string | undefined, env: Env): string | null {
+ if (reference != null) return resolveTokenReference(reference, env);
+ for (const name of TOKEN_ENV_FALLBACKS) {
+ const value = env[name]?.trim();
+ if (value) return value;
+ }
+ return null;
+}
+
+/**
+ * Whether pull requests can do anything on this deployment. The feature is on unless an
+ * administrator turns it off, and it stays dormant, advertising nothing and recording nothing,
+ * until there is both a token to read with and a scope of repositories to read: either a list, or
+ * the explicit opt-in to every repository the token can see.
+ */
+export function isPullRequestFeatureActive(
+ settings: Partial<PullRequestSettings> | null | undefined,
+ env: Env,
+): boolean {
+ if (settings?.enabled === false) return false;
+ if (settings?.token == null && resolvePullRequestToken(undefined, env) == null) return false;
+ return (
+ settings?.allowAllRepositories === true || (settings?.allowedRepositories?.length ?? 0) > 0
+ );
+}
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index b84bdf48c0..d375cf4875 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -1118,7 +1118,7 @@ describe('agent pull request config', () => {
const parse = (pullRequests?: unknown) =>
configSchema.safeParse({ version: '1.0', endpoints: { agents: { pullRequests } } });
- it('is off by default and absent when not configured', () => {
+ it('is absent when not configured, and has no switch of its own until one is set', () => {
const absent = configSchema.parse({ version: '1.0', endpoints: { agents: {} } });
expect(absent.endpoints?.agents?.pullRequests).toBeUndefined();
const empty = configSchema.parse({
@@ -1126,7 +1126,6 @@ describe('agent pull request config', () => {
endpoints: { agents: { pullRequests: {} } },
});
expect(empty.endpoints?.agents?.pullRequests).toEqual({
- enabled: false,
cacheTtlSeconds: 30,
requestTimeoutSeconds: 10,
lookupTimeoutSeconds: 30,
@@ -1151,13 +1150,19 @@ describe('agent pull request config', () => {
expect(parse(enabled).success).toBe(true);
});
- it('requires a token reference when enabled', () => {
- expect(parse({ ...enabled, token: undefined }).success).toBe(false);
+ it("needs no token reference, so the deployment's own GitHub token can be used", () => {
+ expect(parse({ ...enabled, token: undefined }).success).toBe(true);
+ expect(parse({ allowAllRepositories: true }).success).toBe(true);
+ });
+
+ it('accepts the opt-in to every repository, and nothing but a boolean for it', () => {
+ expect(parse({ allowAllRepositories: true }).success).toBe(true);
+ expect(parse({ allowAllRepositories: false }).success).toBe(true);
+ expect(parse({ allowAllRepositories: 'yes' }).success).toBe(false);
});
- it('requires at least one allowed repository when enabled, so a worker cannot name its own', () => {
- expect(parse({ ...enabled, allowedRepositories: undefined }).success).toBe(false);
- expect(parse({ ...enabled, allowedRepositories: [] }).success).toBe(false);
+ it('can be switched off explicitly', () => {
+ expect(parse({ enabled: false }).success).toBe(true);
});
it.each(['LibreChat-AI/*', 'o/r', 'My.Org/my_repo-2'])('accepts the repository %s', (repo) => {
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 950be640dd..bd3befd1a1 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -1859,17 +1859,25 @@ export const agentsEndpointSchema = baseEndpointSchema
})
.optional(),
/** Header pull request chip: finds the pull request for the branch a conversation's code
- * workspace reports, using a server-held GitHub token. Off unless an administrator opts in. */
+ * workspace reports, using a server-held GitHub token. On by default once a token is found
+ * (`token`, else `GITHUB_PULL_REQUEST_TOKEN`, `GITHUB_TOKEN` or `GH_TOKEN`) and a repository
+ * scope is set; `enabled: false` turns it off. */
pullRequests: z
.object({
- enabled: z.boolean().optional().default(false),
+ enabled: z.boolean().optional(),
/** Environment variable reference holding a read-only GitHub token, e.g.
- * `${GITHUB_PULL_REQUEST_TOKEN}`. Never the token itself. */
+ * `${GITHUB_PULL_REQUEST_TOKEN}`. Never the token itself. Optional: without it the first
+ * of `GITHUB_PULL_REQUEST_TOKEN`, `GITHUB_TOKEN` and `GH_TOKEN` that is set is used. */
token: pullRequestTokenReferenceSchema.optional(),
/** Repositories the token may be used for, as `owner/name` or `owner/*`. A worker reports
* its own repository, so without this list a user could point the server's token at any
* repository it can read. */
allowedRepositories: z.array(pullRequestRepositorySchema).max(256).optional(),
+ /** Look up every repository a worker reports, limited only by what the token can read.
+ * Off by default: a worker names its own repository, so with this on any user can point
+ * the server's token at any repository it can see. Use a read-only token scoped to the
+ * repositories you are willing to show. */
+ allowAllRepositories: z.boolean().optional(),
/** Seconds a looked-up pull request is reused before GitHub is asked again. */
cacheTtlSeconds: z.number().int().min(5).max(3600).optional().default(30),
/** Pull requests cached per credential before the oldest is evicted. Size it to the
@@ -1906,22 +1914,6 @@ export const agentsEndpointSchema = baseEndpointSchema
/** Candidates compared with that commit before the search gives up. Each is one request. */
maxHeadComparisons: z.number().int().min(0).max(20).optional().default(3),
})
- .superRefine((value, ctx) => {
- if (value.enabled && !value.token) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ['token'],
- message: 'A token reference is required when pull requests are enabled',
- });
- }
- if (value.enabled && (value.allowedRepositories?.length ?? 0) === 0) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ['allowedRepositories'],
- message: 'At least one allowed repository is required when pull requests are enabled',
- });
- }
- })
.optional(),
/** Conversational background-task delivery policy. Automatic completion wakeups are
* enabled unless an administrator explicitly restores poll-only behavior. */
@@ -3156,7 +3148,8 @@ export type TStartupConfig = {
langfuseFanoutEnabled?: boolean;
langfuseConnectionAccess?: boolean;
insightsEnabled?: boolean;
- /** `endpoints.agents.pullRequests.enabled`; the header does not ask for a pull request without it. */
+ /** Whether pull requests are active (on unless turned off, with a token and a repository scope);
+ * the header does not ask for a pull request without it. */
pullRequestsEnabled?: boolean;
/** Present with `pullRequestsEnabled` once this server has the batch route the sidebar uses. */
pullRequestsBatchVersion?: typeof PULL_REQUEST_BATCH_VERSION;