Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): preserve native xAI search tools

Chris799b94bacce2
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
index 0ea37fabe4..18e2a9e925 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
@@ -156,6 +156,102 @@ describe('PI native subscription forwarding', () => {
}
});
+ it('adds model-gated x_search to native general Grok requests after PI function tools', async () => {
+ const fetchMock = vi.fn(async () => new Response('event: done\n\n', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ }));
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-x-search', deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ }));
+ const parsedBody = {
+ model: 'grok-4.5',
+ tools: [{ type: 'function', name: 'read_file', parameters: { type: 'object' } }],
+ tool_choice: 'required',
+ };
+
+ await handler({
+ rawBody: Buffer.from(JSON.stringify(parsedBody)),
+ parsedBody,
+ ctx: {
+ reqId: 5,
+ method: 'POST',
+ url: '/v1/responses',
+ headers: { 'content-type': 'application/json' },
+ },
+ res: responseRecorder(),
+ } as never);
+
+ const request = JSON.parse(Buffer.from(fetchMock.mock.calls[0]![1]?.body as Uint8Array).toString('utf8'));
+ expect(request.tools).toEqual([
+ { type: 'function', name: 'read_file', parameters: { type: 'object' } },
+ { type: 'x_search' },
+ ]);
+ expect(request.tool_choice).toEqual({ type: 'function', name: 'read_file' });
+ });
+
+ it('preserves an existing native x_search declaration without duplicating it', async () => {
+ const fetchMock = vi.fn(async () => new Response('event: done\n\n', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ }));
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-x-search-existing', deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ }));
+ const parsedBody = {
+ model: 'grok-4.5',
+ tools: [{ type: 'x_search', from_date: '2026-08-01' }],
+ };
+ const rawBody = Buffer.from(JSON.stringify(parsedBody));
+
+ await handler({
+ rawBody,
+ parsedBody,
+ ctx: {
+ reqId: 6,
+ method: 'POST',
+ url: '/v1/responses',
+ headers: { 'content-type': 'application/json' },
+ },
+ res: responseRecorder(),
+ } as never);
+
+ const forwarded = Buffer.from(fetchMock.mock.calls[0]![1]?.body as Uint8Array);
+ expect(forwarded).toEqual(rawBody);
+ expect(JSON.parse(forwarded.toString('utf8')).tools).toEqual([
+ { type: 'x_search', from_date: '2026-08-01' },
+ ]);
+ });
+
+ it.each(['grok-code-fast', 'grok-build-0.1'])(
+ 'does not add x_search to native coding model %s',
+ async (model) => {
+ const fetchMock = vi.fn(async () => new Response('event: done\n\n', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ }));
+ const handler = getPiNativeSubscriptionHandler('xai', `session-${model}`, deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ }));
+ const parsedBody = { model };
+ const rawBody = Buffer.from(JSON.stringify(parsedBody));
+
+ await handler({
+ rawBody,
+ parsedBody,
+ ctx: {
+ reqId: 7,
+ method: 'POST',
+ url: '/v1/responses',
+ headers: { 'content-type': 'application/json' },
+ },
+ res: responseRecorder(),
+ } as never);
+
+ expect(Buffer.from(fetchMock.mock.calls[0]![1]?.body as Uint8Array)).toEqual(rawBody);
+ },
+ );
+
it('forwards xAI Chat Completions natively and invalidates the failed host token', async () => {
const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('{"error":"expired"}', {
status: 401,
diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
index a4a1546bb1..d963d249b7 100644
--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
@@ -229,7 +229,8 @@ export function createModelRoutingTransform(): RoutingTransform {
if (piSessionId && (piProviderId === 'openai' || piProviderId === 'xai')) {
return {
// PI has already built the provider-native request. The local handler
- // only authenticates and forwards it; no Claude protocol bridge runs.
+ // authenticates and forwards it; the xAI forwarder also restores its
+ // provider server tools, but no Claude protocol bridge runs.
localHandler: getPiNativeSubscriptionHandler(piProviderId, piSessionId),
};
}
diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
index 6c705795db..b86b90d62d 100644
--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
@@ -407,6 +407,50 @@ function recordNativeXaiRateLimit(
}
}
+function isPlainRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+/**
+ * PI already emits xAI-native payloads, so this path bypasses the Messages →
+ * Responses bridge that normally supplies xAI's model-gated server tools.
+ * Restore the same stable contract here: append missing tools after PI's own
+ * tools, preserve an existing declaration verbatim, and keep a forced single
+ * function call from being satisfied by x_search instead.
+ */
+function withNativeXaiServerSideTools(body: unknown): Record<string, unknown> | null {
+ if (!isPlainRecord(body) || typeof body.model !== 'string') return null;
+ const model = body.model.startsWith(XAI_MODEL_PREFIX)
+ ? body.model.slice(XAI_MODEL_PREFIX.length)
+ : body.model;
+ const serverTools = xaiServerSideTools(model);
+ if (serverTools.length === 0) return null;
+
+ const existing = Array.isArray(body.tools) ? body.tools : [];
+ const declaredTypes = new Set(
+ existing.map((tool) => (
+ isPlainRecord(tool) && typeof tool.type === 'string' ? tool.type : ''
+ )),
+ );
+ const missing = serverTools.filter((tool) => !declaredTypes.has(tool.type));
+ const tools = missing.length > 0 ? [...existing, ...missing] : existing;
+ let next = missing.length > 0 ? { ...body, tools } : body;
+
+ if (body.tool_choice === 'required') {
+ const functionTools = tools.filter(
+ (tool) => isPlainRecord(tool) && tool.type === 'function' && typeof tool.name === 'string',
+ );
+ if (functionTools.length === 1) {
+ next = {
+ ...next,
+ tool_choice: { type: 'function', name: functionTools[0]!.name },
+ };
+ return next;
+ }
+ }
+ return missing.length > 0 ? next : null;
+}
+
async function pipeNativeResponse(response: Response, res: Parameters<LocalRequestHandler>[0]['res']): Promise<void> {
res.writeHead(response.status, nativeResponseHeaders(response));
if (!response.body) {
@@ -439,15 +483,15 @@ async function pipeNativeResponse(response: Response, res: Parameters<LocalReque
/**
* Forward an already-native PI request. Unlike getResponsesBridgeHandler this
* performs no Messages/Responses conversion: PI constructs the provider's
- * native payload, while the host only swaps placeholder loopback credentials
- * for the connected account credential.
+ * native payload, while the host swaps placeholder loopback credentials for
+ * the connected account credential and restores xAI's model-gated server tools.
*/
export function getPiNativeSubscriptionHandler(
providerId: PiNativeSubscriptionProvider,
sessionId: string,
deps: PiNativeSubscriptionHandlerDeps = defaultPiNativeSubscriptionHandlerDeps,
): LocalRequestHandler {
- return async ({ rawBody, ctx, res }) => {
+ return async ({ rawBody, parsedBody, ctx, res }) => {
const upstreamUrl = piNativeUpstreamUrl(providerId, ctx.url);
if (ctx.method !== 'POST' || !upstreamUrl) {
res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
@@ -474,13 +518,23 @@ export function getPiNativeSubscriptionHandler(
}
headers['content-type'] = ctx.headers['content-type'] ?? 'application/json';
headers.accept = ctx.headers.accept ?? 'text/event-stream';
- const contentEncoding = ctx.headers['content-encoding'];
+ let outboundBody = rawBody;
+ let contentEncoding = ctx.headers['content-encoding'];
+ if (providerId === 'xai') {
+ const withServerTools = withNativeXaiServerSideTools(parsedBody);
+ if (withServerTools) {
+ outboundBody = Buffer.from(JSON.stringify(withServerTools));
+ // The proxy parsed a plain JSON request. After reserializing it the
+ // original content encoding, if any, no longer describes the bytes.
+ contentEncoding = undefined;
+ }
+ }
if (contentEncoding) headers['content-encoding'] = contentEncoding;
const response = await deps.fetch(upstreamUrl, {
method: 'POST',
headers,
- body: new Uint8Array(rawBody),
+ body: new Uint8Array(outboundBody),
signal: controller.signal,
});
if (providerId === 'xai' && response.ok) {