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(heterogeneous-agent): support Grok provider bindings (#18737)

AmAzing-e7afd7b24757
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 0a90d786aeb..0bce41f981a 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -817,6 +817,13 @@ export default class HeterogeneousAgentCtr {
) {
appendLoopbackNoProxy(env);
}
+ if (session.agentType === 'grok-build' && session.hostedProviderBinding) {
+ // Empty XAI_API_KEY values still count as configured in Grok and can
+ // trigger an empty-key probe. Remove both current and legacy inherited
+ // credentials so the managed model's env_key is the only BYOK source.
+ delete env.GROK_CODE_XAI_API_KEY;
+ delete env.XAI_API_KEY;
+ }
return env;
}
@@ -2028,6 +2035,7 @@ export default class HeterogeneousAgentCtr {
cause: error,
});
} finally {
+ await session.hostedProviderBinding?.cleanup();
if (session.grokAcpSession === acpSession) session.grokAcpSession = undefined;
}
}
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 0423033f32f..81a47e77085 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -1513,6 +1513,68 @@ describe('HeterogeneousAgentCtr', () => {
expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });
});
+ it('launches provider-bound Grok with a managed secret-free profile', async () => {
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'grok-build',
+ args: ['--model', 'stale-model', '--effort', 'high'],
+ command: 'grok',
+ env: {
+ GROK_CODE_XAI_API_KEY: 'stale-legacy-key',
+ GROK_CONFIG: 'untrusted',
+ XAI_API_KEY: 'stale-key',
+ },
+ providerBinding: {
+ apiConfig: { model: 'gpt-test', providerId: 'openai' },
+ kind: 'provider',
+ },
+ });
+
+ const originalLegacyApiKey = process.env.GROK_CODE_XAI_API_KEY;
+ const originalXaiApiKey = process.env.XAI_API_KEY;
+ process.env.GROK_CODE_XAI_API_KEY = 'inherited-legacy-key';
+ process.env.XAI_API_KEY = 'inherited-xai-key';
+ try {
+ await ctr.sendPrompt({ operationId: 'op-grok-provider', prompt: 'hello', sessionId });
+ } finally {
+ if (originalLegacyApiKey === undefined) delete process.env.GROK_CODE_XAI_API_KEY;
+ else process.env.GROK_CODE_XAI_API_KEY = originalLegacyApiKey;
+ if (originalXaiApiKey === undefined) delete process.env.XAI_API_KEY;
+ else process.env.XAI_API_KEY = originalXaiApiKey;
+ }
+
+ const options = grokAcpSessionConstructMock.mock.calls.at(-1)?.[0];
+ expect(options.args).toEqual([
+ '--effort',
+ 'high',
+ '--model',
+ expect.stringMatching(/^lobehub-provider-[\da-f]{16}$/),
+ ]);
+ expect(options.env).toEqual(
+ expect.objectContaining({
+ GROK_CONFIG: '',
+ GROK_DEFAULT_MODEL: '',
+ GROK_HOME: expect.stringContaining('/heteroAgent/bindings/grok-build/'),
+ LOBEHUB_GROK_API_KEY: 'provider-secret',
+ }),
+ );
+ expect(options.env).not.toHaveProperty('GROK_CODE_XAI_API_KEY');
+ expect(options.env).not.toHaveProperty('XAI_API_KEY');
+
+ const bindingsDir = path.join(appStoragePath, 'heteroAgent', 'bindings', 'grok-build');
+ const [bindingDir] = await readdir(bindingsDir);
+ const config = await readFile(path.join(bindingsDir, bindingDir, 'config.toml'), 'utf8');
+ expect(config).toContain('model = "gpt-test"');
+ expect(config).toContain('base_url = "https://api.openai.com/v1"');
+ expect(config).toContain('api_backend = "responses"');
+ expect(config).not.toContain('provider-secret');
+ expect(JSON.stringify(loggerInfoMock.mock.calls)).not.toContain('provider-secret');
+ expect(await readdir(path.join(appStoragePath, 'heteroAgent', 'runs'))).toEqual([]);
+ });
+
it.each([
['cancelSession', grokAcpSessionInterruptMock],
['stopSession', grokAcpSessionCloseMock],
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/grokBuild.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/grokBuild.test.ts
new file mode 100644
index 00000000000..61ff6299401
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/grokBuild.test.ts
@@ -0,0 +1,139 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PrepareProviderBindingContext } from '../types';
+import { grokBuildDriver, sanitizeGrokProviderBindingArgs } from './grokBuild';
+
+const bindingContext = (
+ protocol: PrepareProviderBindingContext['resolution']['protocol'],
+ endpoint: string,
+): PrepareProviderBindingContext => ({
+ args: [
+ '--model',
+ 'stale-model',
+ '--agent=untrusted-agent',
+ '--agent-profile',
+ '/untrusted/profile',
+ '--continue',
+ '--effort',
+ 'high',
+ ],
+ env: {
+ GROK_CONFIG: 'untrusted config',
+ GROK_DEFAULT_MODEL: 'stale-model',
+ GROK_HOME: '/user/grok',
+ GROK_CODE_XAI_API_KEY: 'stale-legacy-key',
+ KEEP_ME: 'yes',
+ LOBEHUB_GROK_API_KEY: 'stale-key',
+ XAI_API_KEY: 'stale-xai-key',
+ },
+ profileDir: '/managed/grok',
+ reference: {
+ apiConfig: { model: 'bound-model', providerId: 'provider-test' },
+ kind: 'provider',
+ },
+ resolution: {
+ agentType: 'grok-build',
+ apiConfig: { model: 'bound-model', providerId: 'provider-test' },
+ endpoint,
+ protocol,
+ providerId: 'provider-test',
+ runtimeConfig: {
+ config: {},
+ keyVaults: { apiKey: 'bound-key', baseURL: endpoint },
+ settings: {
+ sdkType: protocol === 'anthropic-messages' ? 'anthropic' : 'openai',
+ supportResponsesApi: protocol === 'openai-responses',
+ },
+ },
+ },
+ runDir: '/managed/run',
+});
+
+describe('grokBuildDriver provider binding', () => {
+ it.each([
+ [
+ 'openai-chat-completions',
+ 'https://gateway.example.com/v1/chat/completions/',
+ 'chat_completions',
+ 'https://gateway.example.com/v1',
+ 'bearer',
+ ],
+ [
+ 'openai-responses',
+ 'https://gateway.example.com/v1/responses/',
+ 'responses',
+ 'https://gateway.example.com/v1',
+ 'bearer',
+ ],
+ [
+ 'anthropic-messages',
+ 'https://gateway.example.com/anthropic/v1/messages/',
+ 'messages',
+ 'https://gateway.example.com/anthropic/v1',
+ 'x_api_key',
+ ],
+ ] as const)(
+ 'writes a secret-free %s profile and pins its managed alias',
+ async (protocol, endpoint, apiBackend, baseURL, authScheme) => {
+ const plan = await grokBuildDriver.prepareProviderBinding!(
+ bindingContext(protocol, endpoint),
+ );
+ const config = plan.profileFiles?.[0]?.content ?? '';
+ const alias = plan.args.at(-1);
+
+ expect(plan.args).toEqual(['--effort', 'high', '--model', alias]);
+ expect(alias).toMatch(/^lobehub-provider-[\da-f]{16}$/);
+ expect(plan.env).toMatchObject({
+ GROK_AGENT: '',
+ GROK_CONFIG: '',
+ GROK_CONFIG_PATH: '',
+ GROK_DEFAULT_MODEL: '',
+ GROK_HOME: '/managed/grok',
+ KEEP_ME: 'yes',
+ LOBEHUB_GROK_API_KEY: 'bound-key',
+ });
+ expect(plan.env.GROK_CODE_XAI_API_KEY).toBeUndefined();
+ expect(plan.env.XAI_API_KEY).toBeUndefined();
+ expect(config).toContain(`[model.${alias}]`);
+ expect(config).toContain('model = "bound-model"');
+ expect(config).toContain(`base_url = "${baseURL}"`);
+ expect(config).toContain('env_key = "LOBEHUB_GROK_API_KEY"');
+ expect(config).toContain(`api_backend = "${apiBackend}"`);
+ expect(config).toContain(`auth_scheme = "${authScheme}"`);
+ expect(config).toContain(`default = "${alias}"`);
+ expect(config).not.toContain('bound-key');
+ expect(config).not.toContain('stale-key');
+
+ if (protocol === 'anthropic-messages') {
+ expect(config).toContain('extra_headers = { "anthropic-version" = "2023-06-01" }');
+ } else {
+ expect(config).not.toContain('anthropic-version');
+ }
+ },
+ );
+
+ it('adds the Anthropic SDK v1 segment when the configured base URL omits it', async () => {
+ const plan = await grokBuildDriver.prepareProviderBinding!(
+ bindingContext('anthropic-messages', 'https://api.anthropic.com'),
+ );
+
+ expect(plan.profileFiles?.[0]?.content).toContain('base_url = "https://api.anthropic.com/v1"');
+ });
+
+ it('removes model, profile, agent, and resume overrides while preserving unrelated options', () => {
+ expect(
+ sanitizeGrokProviderBindingArgs([
+ '-m=old',
+ '--agent',
+ 'untrusted',
+ '--agent-profile=/untrusted',
+ '--resume',
+ 'old-session',
+ '--session-id=other-session',
+ '-c',
+ '--effort',
+ 'xhigh',
+ ]),
+ ).toEqual(['--effort', 'xhigh']);
+ });
+});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/grokBuild.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/grokBuild.ts
index ec74cf0a834..eb1f588314e 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/grokBuild.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/grokBuild.ts
@@ -1,12 +1,132 @@
+import { createHash } from 'node:crypto';
+
+import type { HeterogeneousProviderBindingProtocol } from '@lobechat/heterogeneous-agents';
import { buildGrokAcpArgs } from '@lobechat/heterogeneous-agents/spawn';
import type { HeterogeneousAgentDriver } from '../types';
+const HOST_API_KEY_ENV = 'LOBEHUB_GROK_API_KEY';
+const HOST_MODEL_ALIAS_PREFIX = 'lobehub-provider';
+
+const GROK_PROVIDER_BINDING_VALUE_FLAGS = [
+ '-m',
+ '--agent',
+ '--agent-profile',
+ '--model',
+ '--resume',
+ '--session-id',
+] as const;
+
+const GROK_PROVIDER_BINDING_BOOLEAN_FLAGS = ['-c', '--continue'] as const;
+
+const GROK_PROVIDER_BINDING_BLOCKED_ENV = [
+ 'GROK_AGENT',
+ 'GROK_CONFIG',
+ 'GROK_CONFIG_PATH',
+ 'GROK_DEFAULT_MODEL',
+] as const;
+
+const tomlString = (value: string): string => JSON.stringify(value);
+
+const stripTrailingSlashes = (value: string): string => {
+ let end = value.length;
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
+ return value.slice(0, end);
+};
+
+const stripOperationPath = (endpoint: string, operationPath: string): string => {
+ const normalized = stripTrailingSlashes(endpoint);
+ return normalized.endsWith(operationPath)
+ ? stripTrailingSlashes(normalized.slice(0, -operationPath.length))
+ : normalized;
+};
+
+const normalizeGrokBaseURL = (
+ endpoint: string,
+ protocol: HeterogeneousProviderBindingProtocol,
+): string => {
+ switch (protocol) {
+ case 'anthropic-messages': {
+ const baseURL = stripOperationPath(endpoint, '/messages');
+ return baseURL.endsWith('/v1') ? baseURL : `${baseURL}/v1`;
+ }
+ case 'openai-chat-completions': {
+ return stripOperationPath(endpoint, '/chat/completions');
+ }
+ case 'openai-responses': {
+ return stripOperationPath(endpoint, '/responses');
+ }
+ default: {
+ throw new Error(`Grok Build cannot use ${protocol}.`);
+ }
+ }
+};
+
+const getGrokApiBackend = (
+ protocol: HeterogeneousProviderBindingProtocol,
+): 'chat_completions' | 'messages' | 'responses' => {
+ switch (protocol) {
+ case 'anthropic-messages': {
+ return 'messages';
+ }
+ case 'openai-chat-completions': {
+ return 'chat_completions';
+ }
+ case 'openai-responses': {
+ return 'responses';
+ }
+ default: {
+ throw new Error(`Grok Build cannot use ${protocol}.`);
+ }
+ }
+};
+
+const buildModelAlias = (identity: string): string =>
+ `${HOST_MODEL_ALIAS_PREFIX}-${createHash('sha256').update(identity).digest('hex').slice(0, 16)}`;
+
+export const sanitizeGrokProviderBindingArgs = (source: string[]): string[] => {
+ const args: string[] = [];
+ for (let index = 0; index < source.length; index += 1) {
+ const arg = source[index];
+ if (
+ GROK_PROVIDER_BINDING_VALUE_FLAGS.includes(
+ arg as (typeof GROK_PROVIDER_BINDING_VALUE_FLAGS)[number],
+ )
+ ) {
+ index += 1;
+ continue;
+ }
+ if (
+ GROK_PROVIDER_BINDING_BOOLEAN_FLAGS.includes(
+ arg as (typeof GROK_PROVIDER_BINDING_BOOLEAN_FLAGS)[number],
+ ) ||
+ GROK_PROVIDER_BINDING_VALUE_FLAGS.some((flag) => arg.startsWith(`${flag}=`))
+ ) {
+ continue;
+ }
+ args.push(arg);
+ }
+ return args;
+};
+
+const sanitizeGrokProviderBindingEnv = (
+ source: Record<string, string> | undefined,
+): Record<string, string> => {
+ const env = { ...source };
+ delete env.GROK_HOME;
+ delete env[HOST_API_KEY_ENV];
+ delete env.GROK_CODE_XAI_API_KEY;
+ delete env.XAI_API_KEY;
+ // Empty values deliberately shadow variables inherited later by the spawn
+ // boundary, keeping model/profile selection inside the managed GROK_HOME.
+ for (const key of GROK_PROVIDER_BINDING_BLOCKED_ENV) env[key] = '';
+ return env;
+};
+
/**
* Grok Build uses the bidirectional ACP stdio transport in the controller.
- * This driver remains registered for descriptor consistency; its plan is only
- * a diagnostic representation and is never passed to the generic one-shot
- * spawn path.
+ * Its spawn plan is only a diagnostic representation and is never passed to
+ * the generic one-shot path; provider binding preparation is still owned here.
*/
export const grokBuildDriver: HeterogeneousAgentDriver = {
async buildSpawnPlan({ args }) {
@@ -14,4 +134,43 @@ export const grokBuildDriver: HeterogeneousAgentDriver = {
args: buildGrokAcpArgs(args),
};
},
+ prepareProviderBinding({ args, env, profileDir, resolution }) {
+ if (!resolution.endpoint) {
+ throw new Error('Grok Build provider binding requires an API endpoint.');
+ }
+
+ const apiKey = resolution.runtimeConfig.keyVaults.apiKey?.trim();
+ if (!apiKey) throw new Error('Grok Build provider binding requires an API key.');
+
+ const apiBackend = getGrokApiBackend(resolution.protocol);
+ const baseURL = normalizeGrokBaseURL(resolution.endpoint, resolution.protocol);
+ const alias = buildModelAlias(
+ [resolution.providerId, resolution.protocol, baseURL, resolution.apiConfig.model].join('\0'),
+ );
+ const isMessages = resolution.protocol === 'anthropic-messages';
+ const config = [
+ `[model.${alias}]`,
+ `name = ${tomlString('LobeHub Provider')}`,
+ `model = ${tomlString(resolution.apiConfig.model)}`,
+ `base_url = ${tomlString(baseURL)}`,
+ `env_key = ${tomlString(HOST_API_KEY_ENV)}`,
+ `api_backend = ${tomlString(apiBackend)}`,
+ `auth_scheme = ${tomlString(isMessages ? 'x_api_key' : 'bearer')}`,
+ ...(isMessages ? ['extra_headers = { "anthropic-version" = "2023-06-01" }'] : []),
+ '',
+ '[models]',
+ `default = ${tomlString(alias)}`,
+ '',
+ ].join('\n');
+
+ return {
+ args: [...sanitizeGrokProviderBindingArgs(args), '--model', alias],
+ env: {
+ ...sanitizeGrokProviderBindingEnv(env),
+ GROK_HOME: profileDir,
+ [HOST_API_KEY_ENV]: apiKey,
+ },
+ profileFiles: [{ content: config, path: 'config.toml' }],
+ };
+ },
};
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingHost.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingHost.test.ts
index 3c43e55bca5..ff8105144db 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingHost.test.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingHost.test.ts
@@ -154,6 +154,48 @@ describe('prepareHostedProviderBinding', () => {
expect(await readFile(path.join(first.profileDir, 'models.json'), 'utf8')).toBe('model-a');
expect(await readFile(path.join(second.profileDir, 'models.json'), 'utf8')).toBe('model-b');
});
+
+ it('isolates Grok profiles by model because the managed catalog is profile-scoped', async () => {
+ const driver: HeterogeneousAgentDriver = {
+ buildSpawnPlan: async () => ({ args: [] }),
+ prepareProviderBinding: ({ profileDir }) => ({
+ args: [],
+ env: { GROK_HOME: profileDir },
+ }),
+ };
+ const base = await makeParams(driver);
+ const firstParams = {
+ ...base,
+ agentType: 'grok-build',
+ reference: {
+ ...base.reference,
+ apiConfig: { ...base.reference.apiConfig, model: 'model-a' },
+ },
+ resolution: {
+ ...base.resolution,
+ agentType: 'grok-build' as const,
+ apiConfig: { ...base.resolution.apiConfig, model: 'model-a' },
+ },
+ };
+ const secondParams = {
+ ...firstParams,
+ reference: {
+ ...firstParams.reference,
+ apiConfig: { ...firstParams.reference.apiConfig, model: 'model-b' },
+ },
+ resolution: {
+ ...firstParams.resolution,
+ apiConfig: { ...firstParams.resolution.apiConfig, model: 'model-b' },
+ },
+ sessionId: 'session-test-2',
+ };
+
+ const first = await prepareHostedProviderBinding(firstParams);
+ const second = await prepareHostedProviderBinding(secondParams);
+
+ expect(second.profileDir).not.toBe(first.profileDir);
+ expect(second.bindingKey).not.toBe(first.bindingKey);
+ });
});
describe('prepareHostedServerDefaultBinding', () => {
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingHost.ts b/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingHost.ts
index dd9e0a9a16c..5fad2e9d9a3 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingHost.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/providerBindingHost.ts
@@ -102,18 +102,19 @@ export const prepareHostedProviderBinding = async (params: {
throw new Error(`${params.agentType} does not implement LobeHub Provider binding.`);
}
- // Pi persists its custom model definition in the reusable profile. Include
- // the selected upstream model so concurrent sessions cannot overwrite one
- // another's models.json or strand a resumable session without its model.
- // Other drivers retain their v1 identity and existing resume keys.
+ // Pi and Grok persist a custom model definition in the reusable profile.
+ // Include the selected upstream model so concurrent sessions cannot
+ // overwrite one another's model catalog or strand a resumable session
+ // without its model. Other drivers retain their v1 identity and resume keys.
const identityVersion = params.agentType === 'pi' ? 'v2' : 'v1';
+ const modelScopedProfile = params.agentType === 'pi' || params.agentType === 'grok-build';
const identity = [
identityVersion,
params.agentType,
params.reference.apiConfig.providerId,
params.resolution.protocol,
params.resolution.endpoint ?? '',
- ...(params.agentType === 'pi' ? [params.resolution.apiConfig.model] : []),
+ ...(modelScopedProfile ? [params.resolution.apiConfig.model] : []),
].join('\0');
const digest = hash(identity);
const bindingKey = `provider-binding:${identityVersion}:${digest}`;
@@ -235,11 +236,10 @@ const statMtimeMs = async (target: string): Promise<number | undefined> => {
/**
* Remove binding profiles that have not been used for `maxAgeMs` (default 30
* days). Stable profiles are normally keyed by `(agentType, providerId,
- * protocol, endpoint)`; Pi profiles additionally include the model because
- * models.json contains a model-specific catalog entry. Profiles are never
- * cleaned by the per-run cleanup, so deleting a provider, changing its
- * endpoint, or bumping the identity version would otherwise strand them (with
- * transcripts inside) forever.
+ * protocol, endpoint)` plus model when the agent stores a model catalog in its
+ * profile. They are never cleaned by the per-run cleanup, so deleting a provider,
+ * changing its endpoint, or bumping the identity version would otherwise strand
+ * them (with transcripts inside) forever.
*
* Profiles are considered used when `prepareHostedProviderBinding` or
* `prepareHostedServerDefaultBinding` touches their marker at session start;
diff --git a/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts b/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts
index 1e864b4501f..00af99d2b2f 100644
--- a/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts
@@ -226,8 +226,8 @@ describe('aiProviderRouter', () => {
const result = await caller.getAiProviderRuntimeState({});
expect(result.providerBindingAgentTypes).toEqual({
- 'anthropic-custom': ['claude-code', 'kimi-code', 'pi'],
- 'openai': ['codex', 'kimi-code', 'pi'],
+ 'anthropic-custom': ['claude-code', 'grok-build', 'kimi-code', 'pi'],
+ 'openai': ['codex', 'grok-build', 'kimi-code', 'pi'],
});
expect(JSON.stringify(result.providerBindingAgentTypes)).not.toContain('secret');
expect(JSON.stringify(result.providerBindingAgentTypes)).not.toContain('example.com');
diff --git a/packages/heterogeneous-agents/src/providerBinding/resolveBinding.test.ts b/packages/heterogeneous-agents/src/providerBinding/resolveBinding.test.ts
index 28b4f400737..2f00be7fd6d 100644
--- a/packages/heterogeneous-agents/src/providerBinding/resolveBinding.test.ts
+++ b/packages/heterogeneous-agents/src/providerBinding/resolveBinding.test.ts
@@ -226,6 +226,76 @@ describe('heterogeneous provider binding protocol resolver', () => {
expect(result.resolution?.modelMetadata).toEqual(modelMetadata);
});
+ it.each([
+ [
+ 'anthropic-messages',
+ 'anthropic-custom',
+ runtime('anthropic', {
+ keyVaults: { apiKey: 'test-key', baseURL: 'https://anthropic.example.com' },
+ }),
+ ],
+ [
+ 'openai-chat-completions',
+ 'chat-provider',
+ runtime('openai', {
+ keyVaults: { apiKey: 'test-key', baseURL: 'https://chat.example.com/v1' },
+ }),
+ ],
+ [
+ 'openai-responses',
+ 'responses-provider',
+ runtime('openai', {
+ config: { enableResponseApi: true },
+ keyVaults: { apiKey: 'test-key', baseURL: 'https://responses.example.com/v1' },
+ settings: { sdkType: 'openai', supportResponsesApi: true },
+ }),
+ ],
+ ] as const)('allows Grok Build on %s', (protocol, providerId, runtimeConfig) => {
+ const result = resolveHeterogeneousProviderBinding({
+ agentType: 'grok-build',
+ apiConfig: { model: 'bound-model', providerId },
+ providerEnabled: true,
+ runtimeConfig,
+ });
+
+ expect(result.resolution?.protocol).toBe(protocol);
+ });
+
+ it('uses official endpoints for Grok Build and rejects Google or missing custom endpoints', () => {
+ expect(
+ resolveHeterogeneousProviderBinding({
+ agentType: 'grok-build',
+ apiConfig: { model: 'gpt-test', providerId: 'openai' },
+ providerEnabled: true,
+ runtimeConfig: runtime('openai'),
+ }).resolution,
+ ).toMatchObject({ endpoint: 'https://api.openai.com/v1', protocol: 'openai-responses' });
+ expect(
+ resolveHeterogeneousProviderBinding({
+ agentType: 'grok-build',
+ apiConfig: { model: 'claude-test', providerId: 'anthropic' },
+ providerEnabled: true,
+ runtimeConfig: runtime('anthropic'),
+ }).resolution,
+ ).toMatchObject({ endpoint: 'https://api.anthropic.com', protocol: 'anthropic-messages' });
+ expect(
+ resolveHeterogeneousProviderBinding({
+ agentType: 'grok-build',
+ apiConfig: { model: 'gemini-test', providerId: 'google' },
+ providerEnabled: true,
+ runtimeConfig: runtime('google'),
+ }).error?.code,
+ ).toBe('protocolMismatch');
+ expect(
+ resolveHeterogeneousProviderBinding({
+ agentType: 'grok-build',
+ apiConfig: { model: 'chat-test', providerId: 'custom-openai' },
+ providerEnabled: true,
+ runtimeConfig: runtime('openai'),
+ }).error?.code,
+ ).toBe('endpointMissing');
+ });
+
it('validates credentials only inside the trusted host boundary', () => {
const input = {
agentType: 'claude-code',
diff --git a/packages/heterogeneous-agents/src/providerBinding/resolveBinding.ts b/packages/heterogeneous-agents/src/providerBinding/resolveBinding.ts
index d49a76f22eb..0eda738f442 100644
--- a/packages/heterogeneous-agents/src/providerBinding/resolveBinding.ts
+++ b/packages/heterogeneous-agents/src/providerBinding/resolveBinding.ts
@@ -11,6 +11,7 @@ import type {
export const HETEROGENEOUS_PROVIDER_BINDING_AGENT_TYPES = [
'claude-code',
'codex',
+ 'grok-build',
'kimi-code',
'pi',
] as const;
@@ -26,6 +27,10 @@ const CAPABILITIES: Partial<
agentType: 'codex',
protocols: ['openai-responses'],
},
+ 'grok-build': {
+ agentType: 'grok-build',
+ protocols: ['openai-responses', 'openai-chat-completions', 'anthropic-messages'],
+ },
'kimi-code': {
agentType: 'kimi-code',
protocols: ['anthropic-messages', 'openai-chat-completions'],
@@ -140,12 +145,12 @@ const resolveEndpointError = (
if (endpoint) return { endpoint };
const defaultEndpoint =
- agentType === 'pi' || protocol === 'openai-responses'
+ agentType === 'pi' || agentType === 'grok-build' || protocol === 'openai-responses'
? DEFAULT_PROVIDER_ENDPOINTS[protocol]?.[providerId]
: undefined;
if (defaultEndpoint) return { endpoint: defaultEndpoint };
- if (protocol === 'openai-responses' || agentType === 'pi') {
+ if (protocol === 'openai-responses' || agentType === 'pi' || agentType === 'grok-build') {
return { error: { code: 'endpointMissing', providerId } };
}