Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): 按端点适配 SuperGrok 搜索工具 (#2943)
Chris Zhangf76168c38f17
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.tsindex bdf0b455d5..1c4783282f 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts@@ -224,7 +224,7 @@ describe('PI native subscription forwarding', () => {}});- it('adds model-gated x_search to native general Grok requests after PI function tools', async () => {+ it('adds one x_search to native Grok 4.6 Responses after PI function tools', async () => {const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {status: 200,headers: { 'content-type': 'text/event-stream' },@@ -233,8 +233,12 @@ describe('PI native subscription forwarding', () => {fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],}));const parsedBody = {- model: 'grok-4.5',- tools: [{ type: 'function', name: 'read_file', parameters: { type: 'object' } }],+ model: 'grok-4.6',+ tools: [+ { type: 'function', name: 'read_file', parameters: { type: 'object' } },+ { type: 'live_search', sources: [{ type: 'x' }] },+ { type: 'x_search', from_date: '2026-08-01' },+ ],tool_choice: 'required',};@@ -253,11 +257,122 @@ describe('PI native subscription forwarding', () => {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' },+ { type: 'x_search', from_date: '2026-08-01' },]);expect(request.tool_choice).toEqual({ type: 'function', name: 'read_file' });});+ it.each([+ [+ 'keeps a configured x_search before a legacy declaration',+ [+ { type: 'x_search', from_date: '2026-08-01' },+ { type: 'live_search', sources: [{ type: 'x' }] },+ ],+ [{ type: 'x_search', from_date: '2026-08-01' }],+ ],+ [+ 'normalizes a lone legacy declaration',+ [{ type: 'live_search', sources: [{ type: 'x' }] }],+ [{ type: 'x_search' }],+ ],+ [+ 'keeps the first of multiple native declarations',+ [+ { type: 'x_search', from_date: '2026-08-01' },+ { type: 'x_search', to_date: '2026-08-18' },+ ],+ [{ type: 'x_search', from_date: '2026-08-01' }],+ ],+ ])('%s', async (_name, tools, expectedTools) => {+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const handler = getPiNativeSubscriptionHandler('xai', 'session-x-search-dedupe', deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const parsedBody = { model: 'grok-4.5', tools };++ await handler({+ rawBody: Buffer.from(JSON.stringify(parsedBody)),+ parsedBody,+ ctx: {+ reqId: 12,+ 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(expectedTools);+ });++ it.each([+ [+ 'normalizes a legacy search choice with its declaration',+ [{ type: 'live_search', sources: [{ type: 'x' }] }],+ { type: 'live_search' },+ [{ type: 'x_search' }],+ { type: 'x_search' },+ ],+ [+ 'keeps an absent choice absent while preferring a native declaration',+ [+ { type: 'live_search', sources: [{ type: 'x' }] },+ { type: 'x_search', from_date: '2026-08-01' },+ ],+ undefined,+ [{ type: 'x_search', from_date: '2026-08-01' }],+ undefined,+ ],+ [+ 'preserves a function choice across duplicate search spellings',+ [+ { type: 'function', name: 'read_file', parameters: { type: 'object' } },+ { type: 'live_search', sources: [{ type: 'x' }] },+ { type: 'x_search', from_date: '2026-08-01' },+ ],+ { type: 'function', name: 'read_file' },+ [+ { type: 'function', name: 'read_file', parameters: { type: 'object' } },+ { type: 'x_search', from_date: '2026-08-01' },+ ],+ { type: 'function', name: 'read_file' },+ ],+ ])('%s', async (_name, tools, toolChoice, expectedTools, expectedToolChoice) => {+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const handler = getPiNativeSubscriptionHandler('xai', 'session-x-search-choice', deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const parsedBody = {+ model: 'grok-4.5',+ tools,+ ...(toolChoice === undefined ? {} : { tool_choice: toolChoice }),+ };++ await handler({+ rawBody: Buffer.from(JSON.stringify(parsedBody)),+ parsedBody,+ ctx: {+ reqId: 13,+ 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(expectedTools);+ expect(request.tool_choice).toEqual(expectedToolChoice);+ });+it('preserves an existing native x_search declaration without duplicating it', async () => {const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {status: 200,@@ -291,6 +406,187 @@ describe('PI native subscription forwarding', () => {]);});+ it('removes xAI search tools from Chat Completions without changing PI function tools or tool_choice', async () => {+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('data: [DONE]\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const handler = getPiNativeSubscriptionHandler('xai', 'session-chat-search-filter', deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const functionTool = {+ type: 'function',+ function: {+ name: 'read_file',+ description: 'Read one file',+ parameters: { type: 'object', properties: { path: { type: 'string' } } },+ },+ };+ const parsedBody = {+ model: 'grok-4.6',+ tools: [+ { type: 'x_search', from_date: '2026-08-01' },+ functionTool,+ { type: 'live_search', sources: [{ type: 'x' }] },+ ],+ tool_choice: { type: 'function', function: { name: 'read_file' } },+ };++ await handler({+ rawBody: Buffer.from(JSON.stringify(parsedBody)),+ parsedBody,+ ctx: {+ reqId: 8,+ method: 'POST',+ url: '/v1/chat/completions',+ headers: { 'content-type': 'application/json' },+ },+ res: responseRecorder(),+ } as never);++ expect(fetchMock).toHaveBeenCalledWith(+ 'https://api.x.ai/v1/chat/completions',+ expect.any(Object),+ );+ const request = JSON.parse(Buffer.from(fetchMock.mock.calls[0]![1]?.body as Uint8Array).toString('utf8'));+ expect(request).toEqual({+ model: 'grok-4.6',+ tools: [functionTool],+ tool_choice: { type: 'function', function: { name: 'read_file' } },+ });+ });++ it.each([+ ['auto', 'auto'],+ ['required', 'required'],+ [+ { type: 'function', function: { name: 'read_file' } },+ { type: 'function', function: { name: 'read_file' } },+ ],+ [+ { type: 'x_search' },+ { type: 'function', function: { name: 'read_file' } },+ ],+ [+ { type: 'live_search' },+ { type: 'function', function: { name: 'read_file' } },+ ],+ ])(+ 'keeps Chat Completions tool controls consistent after removing search choice %j',+ async (toolChoice, expectedToolChoice) => {+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('data: [DONE]\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const handler = getPiNativeSubscriptionHandler('xai', 'session-chat-choice-filter', deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const functionTool = {+ type: 'function',+ function: { name: 'read_file', parameters: { type: 'object' } },+ };+ const parsedBody = {+ model: 'grok-4.6',+ tools: [{ type: 'x_search' }, functionTool],+ tool_choice: toolChoice,+ parallel_tool_calls: true,+ };++ await handler({+ rawBody: Buffer.from(JSON.stringify(parsedBody)),+ parsedBody,+ ctx: {+ reqId: 10,+ method: 'POST',+ url: '/v1/chat/completions',+ 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).toEqual({+ model: 'grok-4.6',+ tools: [functionTool],+ tool_choice: expectedToolChoice,+ parallel_tool_calls: true,+ });+ },+ );++ it.each([+ 'required',+ { type: 'x_search' },+ { type: 'live_search' },+ ])(+ 'removes dangling Chat Completions controls when search-only choice %j leaves no tools',+ async (toolChoice) => {+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('data: [DONE]\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const handler = getPiNativeSubscriptionHandler('xai', 'session-chat-empty-tools', deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const parsedBody = {+ model: 'grok-4.6',+ tools: [{ type: 'x_search' }, { type: 'live_search', sources: [{ type: 'x' }] }],+ tool_choice: toolChoice,+ parallel_tool_calls: true,+ };++ await handler({+ rawBody: Buffer.from(JSON.stringify(parsedBody)),+ parsedBody,+ ctx: {+ reqId: 11,+ method: 'POST',+ url: '/v1/chat/completions',+ 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).toEqual({ model: 'grok-4.6' });+ },+ );++ it('does not add a search tool to native Grok Chat Completions', async () => {+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('data: [DONE]\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const handler = getPiNativeSubscriptionHandler('xai', 'session-chat-no-search', deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const parsedBody = {+ model: 'grok-4.6',+ tools: [{+ type: 'function',+ function: { name: 'read_file', parameters: { type: 'object' } },+ }],+ tool_choice: 'required',+ };+ const rawBody = Buffer.from(JSON.stringify(parsedBody));++ await handler({+ rawBody,+ parsedBody,+ ctx: {+ reqId: 9,+ method: 'POST',+ url: '/v1/chat/completions',+ 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'))).toEqual(parsedBody);+ });+it.each(['grok-code-fast', 'grok-build-0.1'])('does not add x_search to native coding model %s',async (model) => {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.tsindex 96e6d350ca..8c355dfb84 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@@ -41,7 +41,7 @@ import {} from './chatgpt-bridge-auth-invalidation.js';import { buildChatgptBridgeHeaders } from './chatgpt-bridge-headers.js';import { recordXaiRateLimitSnapshot } from '../usageBroadcaster.js';-import { xaiServerSideTools } from './xai-server-side-tools.js';+import { XAI_X_SEARCH_TOOL_TYPE, xaiServerSideTools } from './xai-server-side-tools.js';import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from '../../shared/subscriptionModels.js';const zstdCompressAsync = promisify(zstdCompress);@@ -56,6 +56,7 @@ const OPENAI_TOKEN_URL = 'https://auth.openai.com/oauth/token';const REFRESH_MARGIN_SEC = 120;// token 刷新 fetch 超时 —— 刷新在 _refreshChain mutex 内串行,不设超时会拖住所有排队请求。const REFRESH_FETCH_TIMEOUT_MS = 15_000;+const XAI_LIVE_SEARCH_TOOL_TYPE = 'live_search';let _handler: ResponsesBridgeHandler | null = null;let _initialized = false;@@ -335,6 +336,12 @@ export function getResponsesBridgeHandler(): ResponsesBridgeHandler | null {}type PiNativeSubscriptionProvider = 'openai' | 'xai';+type PiNativeWireProtocol = 'openai-responses' | 'openai-chat';++interface PiNativeUpstream {+ url: string;+ wireProtocol: PiNativeWireProtocol;+}export interface PiNativeSubscriptionHandlerDeps {fetch: typeof outboundFetch;@@ -354,10 +361,10 @@ const defaultPiNativeSubscriptionHandlerDeps: PiNativeSubscriptionHandlerDeps =recordXaiRateLimit: recordXaiRateLimitSnapshot,};-function piNativeUpstreamUrl(+function piNativeUpstream(providerId: PiNativeSubscriptionProvider,requestUrl: string,-): string | null {+): PiNativeUpstream | null {let pathname: string;try {pathname = new URL(requestUrl, 'http://127.0.0.1').pathname;@@ -366,13 +373,20 @@ function piNativeUpstreamUrl(}if (providerId === 'openai') {return pathname === '/codex/responses'- ? 'https://chatgpt.com/backend-api/codex/responses'+ ? {+ url: 'https://chatgpt.com/backend-api/codex/responses',+ wireProtocol: 'openai-responses',+ }: null;}const normalized = pathname.startsWith('/v1/') ? pathname : `/v1${pathname}`;- return normalized === '/v1/responses' || normalized === '/v1/chat/completions'- ? `https://api.x.ai${normalized}`- : null;+ if (normalized === '/v1/responses') {+ return { url: `https://api.x.ai${normalized}`, wireProtocol: 'openai-responses' };+ }+ if (normalized === '/v1/chat/completions') {+ return { url: `https://api.x.ai${normalized}`, wireProtocol: 'openai-chat' };+ }+ return null;}function nativeResponseHeaders(response: Response): Record<string, string> {@@ -462,44 +476,147 @@ function parseJsonRecord(rawBody: Buffer): Record<string, unknown> | null {}}+function isXaiSearchToolType(value: unknown): boolean {+ return value === XAI_X_SEARCH_TOOL_TYPE || value === XAI_LIVE_SEARCH_TOOL_TYPE;+}++function chatFunctionToolName(tool: unknown): string | null {+ if (!isPlainRecord(tool) || tool.type !== 'function' || !isPlainRecord(tool.function)) {+ return null;+ }+ return typeof tool.function.name === 'string' ? tool.function.name : null;+}++function selectsRemovedXaiSearchTool(toolChoice: unknown): boolean {+ if (isXaiSearchToolType(toolChoice)) return true;+ return isPlainRecord(toolChoice) && isXaiSearchToolType(toolChoice.type);+}++function withoutNativeXaiChatSearchTools(+ body: Record<string, unknown>,+ existing: unknown[],+): Record<string, unknown> | null {+ const tools = existing.filter((tool) => (+ !isPlainRecord(tool) || !isXaiSearchToolType(tool.type)+ ));+ if (tools.length === existing.length) return null;++ const next = { ...body };+ if (tools.length === 0) {+ delete next.tools;+ delete next.tool_choice;+ delete next.parallel_tool_calls;+ return next;+ }++ next.tools = tools;+ if (selectsRemovedXaiSearchTool(next.tool_choice)) {+ const functionToolNames = tools.flatMap((tool) => {+ const name = chatFunctionToolName(tool);+ return name === null ? [] : [name];+ });+ if (functionToolNames.length === 1) {+ next.tool_choice = {+ type: 'function',+ function: { name: functionToolNames[0] },+ };+ } else {+ next.tool_choice = functionToolNames.length > 1 ? 'required' : 'auto';+ }+ }+ return next;+}+/*** 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.+ * Restore the same stable contract here while respecting the native endpoint.+ * Current xAI server-side search tools belong to Responses; Chat Completions'+ * legacy live_search path is deprecated. Strip either search spelling from Chat+ * requests while preserving PI function tools and tool_choice. For Responses,+ * normalize stale spellings, append one missing x_search declaration, and keep+ * forced-function narrowing from being satisfied by x_search instead.*/-function withNativeXaiServerSideTools(body: unknown): Record<string, unknown> | null {+function withNativeXaiServerSideTools(+ body: unknown,+ wireProtocol: PiNativeWireProtocol,+): Record<string, unknown> | null {if (!isPlainRecord(body) || typeof body.model !== 'string') return null;+ const existing = Array.isArray(body.tools) ? body.tools : [];+ if (wireProtocol === 'openai-chat') {+ return withoutNativeXaiChatSearchTools(body, existing);+ }+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 preferredXSearchTool = existing.find((tool) => (+ isPlainRecord(tool) && tool.type === XAI_X_SEARCH_TOOL_TYPE+ ));+ let searchToolDeclared = false;+ let toolsChanged = false;+ const tools = existing.flatMap((tool) => {+ if (+ !isPlainRecord(tool) ||+ (tool.type !== XAI_X_SEARCH_TOOL_TYPE && tool.type !== XAI_LIVE_SEARCH_TOOL_TYPE)+ ) {+ return [tool];+ }+ if (searchToolDeclared) {+ toolsChanged = true;+ return [];+ }+ searchToolDeclared = true;+ if (preferredXSearchTool !== undefined) {+ if (tool === preferredXSearchTool) return [tool];+ toolsChanged = true;+ return [preferredXSearchTool];+ }+ toolsChanged = true;+ // live_search options belong to the deprecated Chat Completions shape and+ // are not interchangeable with Responses x_search options.+ return [{ type: XAI_X_SEARCH_TOOL_TYPE }];+ });const declaredTypes = new Set(- existing.map((tool) => (+ tools.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 (missing.length > 0) {+ tools.push(...missing);+ toolsChanged = true;+ }+ let next = toolsChanged ? { ...body, tools } : body;++ if (+ isPlainRecord(body.tool_choice) &&+ body.tool_choice.type === XAI_LIVE_SEARCH_TOOL_TYPE+ ) {+ return {+ ...next,+ tool_choice: { type: XAI_X_SEARCH_TOOL_TYPE },+ };+ }if (body.tool_choice === 'required') {- const functionTools = tools.filter(- (tool) => isPlainRecord(tool) && tool.type === 'function' && typeof tool.name === 'string',- );- if (functionTools.length === 1) {+ const functionToolNames = tools.flatMap((tool) => {+ if (!isPlainRecord(tool) || tool.type !== 'function') return [];+ return typeof tool.name === 'string' ? [tool.name] : [];+ });+ if (functionToolNames.length === 1) {+ const name = functionToolNames[0]!;next = {...next,- tool_choice: { type: 'function', name: functionTools[0]!.name },+ tool_choice: { type: 'function', name },};return next;}}- return missing.length > 0 ? next : null;+ return toolsChanged ? next : null;}async function pipeNativeResponse(response: Response, res: Parameters<LocalRequestHandler>[0]['res']): Promise<void> {@@ -543,8 +660,8 @@ export function getPiNativeSubscriptionHandler(deps: PiNativeSubscriptionHandlerDeps = defaultPiNativeSubscriptionHandlerDeps,): LocalRequestHandler {return async ({ rawBody, parsedBody, ctx, res }) => {- const upstreamUrl = piNativeUpstreamUrl(providerId, ctx.url);- if (ctx.method !== 'POST' || !upstreamUrl) {+ const upstream = piNativeUpstream(providerId, ctx.url);+ if (ctx.method !== 'POST' || !upstream) {res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });res.end(JSON.stringify({ error: { message: 'Unsupported PI subscription endpoint.' } }));return;@@ -587,7 +704,9 @@ export function getPiNativeSubscriptionHandler(: parseJsonRecord(rawBody);const sanitized = parsed ? sanitizeXaiModelInputBody(parsed) : null;const current = sanitized ?? parsed;- const withServerTools = current ? withNativeXaiServerSideTools(current) : null;+ const withServerTools = current+ ? withNativeXaiServerSideTools(current, upstream.wireProtocol)+ : null;if (sanitized || withServerTools) {outboundBody = Buffer.from(JSON.stringify(withServerTools ?? current));// The proxy parsed a plain JSON request. After reserializing it the@@ -597,7 +716,7 @@ export function getPiNativeSubscriptionHandler(}if (contentEncoding) headers['content-encoding'] = contentEncoding;- const response = await deps.fetch(upstreamUrl, {+ const response = await deps.fetch(upstream.url, {method: 'POST',headers,body: new Uint8Array(outboundBody),