@scoheart/x-search-mcp 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +3 -3
  2. package/TOOL.md +8 -6
  3. package/dist/package.json +2 -1
  4. package/dist/src/auth.d.ts.map +1 -1
  5. package/dist/src/auth.js +61 -46
  6. package/dist/src/auth.js.map +1 -1
  7. package/dist/src/call-log.d.ts.map +1 -1
  8. package/dist/src/call-log.js +52 -33
  9. package/dist/src/call-log.js.map +1 -1
  10. package/dist/src/device-login.d.ts +46 -0
  11. package/dist/src/device-login.d.ts.map +1 -0
  12. package/dist/src/device-login.js +72 -0
  13. package/dist/src/device-login.js.map +1 -0
  14. package/dist/src/multi-user/service.js +2 -2
  15. package/dist/src/multi-user/service.js.map +1 -1
  16. package/dist/src/search-input.d.ts +43 -0
  17. package/dist/src/search-input.d.ts.map +1 -0
  18. package/dist/src/search-input.js +105 -0
  19. package/dist/src/search-input.js.map +1 -0
  20. package/dist/src/search-response.d.ts +6 -0
  21. package/dist/src/search-response.d.ts.map +1 -0
  22. package/dist/src/search-response.js +125 -0
  23. package/dist/src/search-response.js.map +1 -0
  24. package/dist/src/search.d.ts +3 -19
  25. package/dist/src/search.d.ts.map +1 -1
  26. package/dist/src/search.js +54 -312
  27. package/dist/src/search.js.map +1 -1
  28. package/dist/src/server.d.ts +2 -0
  29. package/dist/src/server.d.ts.map +1 -1
  30. package/dist/src/server.js +61 -158
  31. package/dist/src/server.js.map +1 -1
  32. package/dist/src/tool-contract.d.ts +150 -0
  33. package/dist/src/tool-contract.d.ts.map +1 -0
  34. package/dist/src/tool-contract.js +83 -0
  35. package/dist/src/tool-contract.js.map +1 -0
  36. package/examples/codex.toml +1 -1
  37. package/examples/mcp.json +1 -1
  38. package/package.json +2 -1
  39. package/src/auth.ts +59 -46
  40. package/src/call-log.ts +52 -31
  41. package/src/device-login.ts +84 -0
  42. package/src/multi-user/service.ts +2 -2
  43. package/src/search-input.ts +113 -0
  44. package/src/search-response.ts +127 -0
  45. package/src/search.ts +127 -418
  46. package/src/server.ts +66 -170
  47. package/src/tool-contract.ts +90 -0
package/src/search.ts CHANGED
@@ -1,218 +1,20 @@
1
- import { sendHttpRequest, HttpError } from './http.js';
1
+ import { sendHttpRequest, HttpError, type SendHttpResponse } from './http.js';
2
2
  import { loadConfig } from './config.js';
3
3
  import { writeCallLog } from './call-log.js';
4
4
  import { getValidOAuthAccessToken, forceRefreshToken, oauthRequired } from './auth.js';
5
- import type {
6
- XSearchInput,
7
- XSearchResult,
8
- InlineCitation,
9
- ServerSideCall,
10
- AuthMode,
11
- CallLogAttempt,
12
- } from './types.js';
5
+ import { validateSearchParams } from './search-input.js';
6
+ import { normalizeSearchResponse } from './search-response.js';
7
+ import type { XSearchResult, CallLogAttempt } from './types.js';
13
8
 
14
- const XAI_RESPONSES_URL = 'https://api.x.ai/v1/responses';
15
- const ALLOWED_PARAM_KEYS = new Set([
16
- 'query',
17
- 'allowed_x_handles',
18
- 'excluded_x_handles',
19
- 'from_date',
20
- 'to_date',
21
- 'enable_image_understanding',
22
- 'enable_video_understanding',
23
- 'auth_mode',
24
- ]);
25
-
26
- const X_SEARCH_INTERNAL_TOOLS = new Set([
27
- 'x_keyword_search',
28
- 'x_semantic_search',
29
- 'x_user_search',
30
- 'x_thread_fetch',
31
- ]);
32
-
33
- function isLeapYear(year: number): boolean {
34
- return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
35
- }
9
+ export { validateCalendarDate, validateAndNormalizeHandles, validateSearchParams } from './search-input.js';
36
10
 
37
- /**
38
- * Validate a real calendar date string formatted as YYYY-MM-DD.
39
- * Prevents JavaScript auto-rollover bugs (e.g. Feb 30 -> Mar 2).
40
- */
41
- export function validateCalendarDate(dateStr: string, fieldName: string): { year: number; month: number; day: number } {
42
- if (typeof dateStr !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
43
- throw new Error(`Validation error: ${fieldName} must be formatted as YYYY-MM-DD, got: ${dateStr}`);
44
- }
45
-
46
- const [yStr, mStr, dStr] = dateStr.split('-');
47
- const year = Number.parseInt(yStr, 10);
48
- const month = Number.parseInt(mStr, 10);
49
- const day = Number.parseInt(dStr, 10);
50
-
51
- if (month < 1 || month > 12) {
52
- throw new Error(`Validation error: ${fieldName} has invalid month: ${month}`);
53
- }
54
-
55
- const daysInMonth = [
56
- 31,
57
- isLeapYear(year) ? 29 : 28,
58
- 31,
59
- 30,
60
- 31,
61
- 30,
62
- 31,
63
- 31,
64
- 30,
65
- 31,
66
- 30,
67
- 31,
68
- ];
69
-
70
- const maxDays = daysInMonth[month - 1];
71
- if (day < 1 || day > maxDays) {
72
- throw new Error(`Validation error: ${fieldName} has invalid day ${day} for month ${month} of year ${year}`);
73
- }
74
-
75
- return { year, month, day };
76
- }
77
-
78
- /**
79
- * Normalize and validate X handles.
80
- * Strips leading '@' and validates length and character set.
81
- */
82
- export function validateAndNormalizeHandles(handles: any[], fieldName: string): string[] {
83
- if (!Array.isArray(handles)) {
84
- throw new Error(`Validation error: ${fieldName} must be an array of strings`);
85
- }
86
- if (handles.length > 10) {
87
- throw new Error(`Validation error: ${fieldName} cannot exceed 10 handles`);
88
- }
89
-
90
- return handles.map((h, idx) => {
91
- if (typeof h !== 'string') {
92
- throw new Error(`Validation error: ${fieldName}[${idx}] must be a string`);
93
- }
94
- const clean = h.replace(/^@+/, '').trim();
95
- if (!/^[A-Za-z0-9_]{1,15}$/.test(clean)) {
96
- throw new Error(`Validation error: handle "${h}" in ${fieldName} must be 1-15 characters matching [A-Za-z0-9_]`);
97
- }
98
- return clean;
99
- });
100
- }
101
-
102
- /**
103
- * Validate all parameters strictly according to specification before resolving credentials.
104
- */
105
- export function validateSearchParams(params: Record<string, any>): XSearchInput {
106
- if (!params || typeof params !== 'object') {
107
- throw new Error('Validation error: parameters must be an object');
108
- }
109
-
110
- // Reject unknown fields
111
- for (const key of Object.keys(params)) {
112
- if (!ALLOWED_PARAM_KEYS.has(key)) {
113
- throw new Error(`Validation error: unknown field "${key}" is not allowed`);
114
- }
115
- }
116
-
117
- // Query validation
118
- if (typeof params.query !== 'string') {
119
- throw new Error('Validation error: "query" must be a string');
120
- }
121
- const trimmedQuery = params.query.trim();
122
- if (!trimmedQuery) {
123
- throw new Error('Validation error: "query" cannot be empty');
124
- }
125
- if (trimmedQuery.length > 16000) {
126
- throw new Error(`Validation error: "query" exceeds maximum length of 16000 characters (got ${trimmedQuery.length})`);
127
- }
128
-
129
- // Handle lists validation
130
- let allowed: string[] | undefined = undefined;
131
- if (params.allowed_x_handles !== undefined) {
132
- allowed = validateAndNormalizeHandles(params.allowed_x_handles, 'allowed_x_handles');
133
- }
134
-
135
- let excluded: string[] | undefined = undefined;
136
- if (params.excluded_x_handles !== undefined) {
137
- excluded = validateAndNormalizeHandles(params.excluded_x_handles, 'excluded_x_handles');
138
- }
139
-
140
- if (allowed && allowed.length > 0 && excluded && excluded.length > 0) {
141
- throw new Error('Validation error: allowed_x_handles and excluded_x_handles cannot both be non-empty');
142
- }
143
-
144
- // Date validation
145
- if (params.from_date !== undefined) {
146
- validateCalendarDate(params.from_date, 'from_date');
147
- }
148
- if (params.to_date !== undefined) {
149
- validateCalendarDate(params.to_date, 'to_date');
150
- }
151
-
152
- if (params.from_date && params.to_date) {
153
- if (params.from_date >= params.to_date) {
154
- throw new Error(`Validation error: from_date (${params.from_date}) must be strictly earlier than to_date (${params.to_date})`);
155
- }
156
- }
157
-
158
- if (params.from_date) {
159
- const todayUtc = new Date().toISOString().slice(0, 10);
160
- if (params.from_date > todayUtc) {
161
- throw new Error(`Validation error: from_date (${params.from_date}) cannot be later than today UTC (${todayUtc})`);
162
- }
163
- }
164
-
165
- // Media flags
166
- if (params.enable_image_understanding !== undefined && typeof params.enable_image_understanding !== 'boolean') {
167
- throw new Error('Validation error: enable_image_understanding must be a boolean');
168
- }
169
- if (params.enable_video_understanding !== undefined && typeof params.enable_video_understanding !== 'boolean') {
170
- throw new Error('Validation error: enable_video_understanding must be a boolean');
171
- }
172
-
173
- // Auth mode
174
- if (params.auth_mode !== undefined && !['auto', 'api_key', 'oauth'].includes(params.auth_mode)) {
175
- throw new Error(`Validation error: auth_mode must be one of 'auto', 'api_key', 'oauth', got: ${params.auth_mode}`);
176
- }
177
-
178
- return {
179
- query: trimmedQuery,
180
- allowed_x_handles: allowed,
181
- excluded_x_handles: excluded,
182
- from_date: params.from_date,
183
- to_date: params.to_date,
184
- enable_image_understanding: params.enable_image_understanding,
185
- enable_video_understanding: params.enable_video_understanding,
186
- auth_mode: params.auth_mode as AuthMode,
187
- };
188
- }
189
-
190
- function sanitizeUrls(rawUrls: any[]): string[] {
191
- if (!Array.isArray(rawUrls)) return [];
192
- const valid: string[] = [];
193
- for (const u of rawUrls) {
194
- if (typeof u === 'string') {
195
- try {
196
- const parsed = new URL(u);
197
- if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
198
- valid.push(u);
199
- }
200
- } catch {
201
- // Skip invalid URL
202
- }
203
- }
204
- }
205
- return [...new Set(valid)];
206
- }
11
+ const XAI_RESPONSES_URL = 'https://api.x.ai/v1/responses';
207
12
 
208
13
  export interface ExecuteSearchOptions {
209
14
  signal?: AbortSignal;
210
15
  resolveApiKey?: () => Promise<string>;
211
16
  }
212
17
 
213
- /**
214
- * Execute x_search call against xAI responses API.
215
- */
216
18
  function errorInfo(err: any): { code: string; message: string; status: number | null } {
217
19
  return {
218
20
  code: err?.code || 'SEARCH_ERROR',
@@ -229,11 +31,12 @@ function attemptFromError(err: any): CallLogAttempt {
229
31
  };
230
32
  }
231
33
 
34
+ /** Execute x_search against the xAI Responses API. */
232
35
  export async function executeSearch(rawParams: Record<string, any>, { signal, resolveApiKey }: ExecuteSearchOptions = {}): Promise<XSearchResult> {
233
36
  const startedAt = new Date().toISOString();
234
37
  const startedMs = Date.now();
235
38
  const attempts: CallLogAttempt[] = [];
236
- let requestBody: Record<string, any> | null = null;
39
+ let requestBody: Record<string, unknown> | null = null;
237
40
  let credentialSource: 'api_key' | 'oauth' | null = null;
238
41
  let billingMode: 'api_metered' | 'subscription_oauth' | null = null;
239
42
  let model = '';
@@ -264,247 +67,153 @@ export async function executeSearch(rawParams: Record<string, any>, { signal, re
264
67
  };
265
68
 
266
69
  try {
267
- // Step 1: Strict parameter validation BEFORE credentials and network
268
- const validated = validateSearchParams(rawParams);
269
- query = validated.query;
270
- const config = loadConfig({ managed: Boolean(resolveApiKey) });
271
- model = config.model;
272
-
273
- // Step 2: Credential resolution
274
- const effectiveAuthMode = validated.auth_mode || config.authMode;
275
- let token: string;
276
-
277
- if (resolveApiKey) {
278
- token = await resolveApiKey();
279
- if (!token) throw new HttpError('XAI_KEY_REQUIRED', 'Bind your xAI API key in Settings.', 409);
280
- credentialSource = 'api_key';
281
- billingMode = 'api_metered';
282
- } else if (effectiveAuthMode === 'api_key' || (effectiveAuthMode === 'auto' && config.apiKey)) {
283
- if (!config.apiKey) {
284
- throw new Error('Credential error: API key is required when auth_mode is "api_key", but neither XAI_API_KEY nor XAI_API_KEY_FILE was provided.');
70
+ const managed = Boolean(resolveApiKey);
71
+ const validated = validateSearchParams(rawParams, { managed });
72
+ query = validated.query;
73
+ const config = loadConfig({ managed });
74
+ model = config.model;
75
+
76
+ const effectiveAuthMode = validated.auth_mode || config.authMode;
77
+ let token: string;
78
+
79
+ if (resolveApiKey) {
80
+ token = await resolveApiKey();
81
+ if (!token) throw new HttpError('XAI_KEY_REQUIRED', 'Bind your xAI API key in Settings.', 409);
82
+ credentialSource = 'api_key';
83
+ billingMode = 'api_metered';
84
+ } else if (effectiveAuthMode === 'api_key' || (effectiveAuthMode === 'auto' && config.apiKey)) {
85
+ if (!config.apiKey) {
86
+ throw new Error('Credential error: API key is required when auth_mode is "api_key", but neither XAI_API_KEY nor XAI_API_KEY_FILE was provided.');
87
+ }
88
+ token = config.apiKey;
89
+ credentialSource = 'api_key';
90
+ billingMode = 'api_metered';
91
+ } else {
92
+ token = await getValidOAuthAccessToken(signal);
93
+ credentialSource = 'oauth';
94
+ billingMode = 'subscription_oauth';
285
95
  }
286
- token = config.apiKey;
287
- credentialSource = 'api_key';
288
- billingMode = 'api_metered';
289
- } else {
290
- token = await getValidOAuthAccessToken(signal);
291
- credentialSource = 'oauth';
292
- billingMode = 'subscription_oauth';
293
- }
294
-
295
- // Step 3: Construct request body
296
- const toolConfig: Record<string, any> = {
297
- type: 'x_search',
298
- };
299
- if (validated.allowed_x_handles) toolConfig.allowed_x_handles = validated.allowed_x_handles;
300
- if (validated.excluded_x_handles) toolConfig.excluded_x_handles = validated.excluded_x_handles;
301
- if (validated.from_date) toolConfig.from_date = validated.from_date;
302
- if (validated.to_date) toolConfig.to_date = validated.to_date;
303
- if (validated.enable_image_understanding !== undefined) toolConfig.enable_image_understanding = validated.enable_image_understanding;
304
- if (validated.enable_video_understanding !== undefined) toolConfig.enable_video_understanding = validated.enable_video_understanding;
305
96
 
306
- requestBody = {
307
- model: config.model,
308
- input: [
309
- {
310
- role: 'user',
311
- content: validated.query,
312
- },
313
- ],
314
- tools: [toolConfig],
315
- store: false,
316
- max_turns: config.maxTurns,
317
- };
318
-
319
- if (config.reasoningEffort) {
320
- requestBody.reasoning = {
321
- effort: config.reasoningEffort,
97
+ const toolConfig: Record<string, unknown> = {
98
+ type: 'x_search',
99
+ };
100
+ if (validated.allowed_x_handles) toolConfig.allowed_x_handles = validated.allowed_x_handles;
101
+ if (validated.excluded_x_handles) toolConfig.excluded_x_handles = validated.excluded_x_handles;
102
+ if (validated.from_date) toolConfig.from_date = validated.from_date;
103
+ if (validated.to_date) toolConfig.to_date = validated.to_date;
104
+ if (validated.enable_image_understanding !== undefined) toolConfig.enable_image_understanding = validated.enable_image_understanding;
105
+ if (validated.enable_video_understanding !== undefined) toolConfig.enable_video_understanding = validated.enable_video_understanding;
106
+
107
+ requestBody = {
108
+ model: config.model,
109
+ input: [
110
+ {
111
+ role: 'user',
112
+ content: validated.query,
113
+ },
114
+ ],
115
+ tools: [toolConfig],
116
+ store: false,
117
+ max_turns: config.maxTurns,
322
118
  };
323
- }
324
119
 
325
- // Step 4: Execute HTTP request with single OAuth 401 refresh retry
326
- let httpRes: any;
327
- try {
328
- httpRes = await sendHttpRequest({
120
+ if (config.reasoningEffort) {
121
+ requestBody.reasoning = {
122
+ effort: config.reasoningEffort,
123
+ };
124
+ }
125
+
126
+ const serializedRequest = JSON.stringify(requestBody);
127
+ const requestWithCredential = (credential: string, retries: number) => sendHttpRequest({
329
128
  url: XAI_RESPONSES_URL,
330
129
  method: 'POST',
331
130
  headers: {
332
- 'Authorization': `Bearer ${token}`,
131
+ Authorization: `Bearer ${credential}`,
333
132
  'Content-Type': 'application/json',
334
133
  },
335
- body: JSON.stringify(requestBody),
134
+ body: serializedRequest,
336
135
  signal,
337
136
  timeoutSeconds: config.timeoutSeconds,
338
- // Managed requests must not retry an old key after it has been unbound.
339
- retries: resolveApiKey ? 0 : config.retries,
137
+ retries,
340
138
  });
341
- } catch (err: any) {
342
- attempts.push(attemptFromError(err));
343
- // If OAuth returns HTTP 401, force-refresh token once and retry once
344
- if (credentialSource === 'oauth' && err instanceof HttpError && err.status === 401) {
139
+
140
+ let httpRes: SendHttpResponse;
141
+ try {
142
+ // Managed requests must not retry an old key after it has been unbound.
143
+ httpRes = await requestWithCredential(token, managed ? 0 : config.retries);
144
+ } catch (err) {
145
+ attempts.push(attemptFromError(err));
146
+ if (credentialSource !== 'oauth' || !(err instanceof HttpError) || err.status !== 401) throw err;
345
147
  const freshToken = await forceRefreshToken(token, signal);
346
148
  try {
347
- httpRes = await sendHttpRequest({
348
- url: XAI_RESPONSES_URL,
349
- method: 'POST',
350
- headers: {
351
- 'Authorization': `Bearer ${freshToken}`,
352
- 'Content-Type': 'application/json',
353
- },
354
- body: JSON.stringify(requestBody),
355
- signal,
356
- timeoutSeconds: config.timeoutSeconds,
357
- retries: 0,
358
- });
359
- } catch (retryErr: any) {
149
+ httpRes = await requestWithCredential(freshToken, 0);
150
+ } catch (retryErr) {
360
151
  attempts.push(attemptFromError(retryErr));
361
152
  if (retryErr instanceof HttpError && retryErr.status === 401) {
362
153
  throw oauthRequired('xAI rejected the Grok OAuth credential after refresh.', 401);
363
154
  }
364
155
  throw retryErr;
365
156
  }
366
- } else {
367
- throw err;
368
157
  }
369
- }
370
158
 
371
- const rawData = httpRes.data;
372
- if (!rawData || typeof rawData !== 'object') {
373
- attempts.push({
374
- http_status: httpRes.status ?? null,
375
- raw_response: rawData ?? null,
376
- error: {
377
- code: 'SEARCH_ERROR',
378
- message: 'Upstream xAI API returned empty or unparseable response data',
379
- status: httpRes.status ?? null,
380
- },
381
- });
382
- throw new Error('Upstream xAI API returned empty or unparseable response data');
383
- }
384
- attempts.push({ http_status: httpRes.status ?? null, raw_response: rawData, error: null });
385
-
386
- // Check for upstream error status
387
- if (rawData.status === 'failed' || rawData.error) {
388
- const errMsg = (!resolveApiKey && rawData.error?.message) || 'Upstream xAI response status is failed';
389
- const upstreamError = new HttpError('UPSTREAM_SERVER_ERROR', errMsg, httpRes.status);
390
- attempts[attempts.length - 1].error = errorInfo(upstreamError);
391
- throw upstreamError;
392
- }
393
-
394
- // Step 5: Extract answer, citations, inline citations, and tool execution details
395
- let answerText = '';
396
- if (typeof rawData.output_text === 'string' && rawData.output_text.trim()) {
397
- answerText = rawData.output_text.trim();
398
- }
399
-
400
- const collectedCitations: string[] = [];
401
- const inlineCitations: InlineCitation[] = [];
402
- const serverSideCalls: ServerSideCall[] = [];
403
-
404
- // Top-level sources or citations
405
- if (Array.isArray(rawData.citations)) {
406
- collectedCitations.push(...rawData.citations);
407
- }
408
- if (Array.isArray(rawData.sources)) {
409
- collectedCitations.push(...rawData.sources);
410
- }
411
-
412
- // Parse output items
413
- if (Array.isArray(rawData.output)) {
414
- for (const item of rawData.output) {
415
- const callId = item.call_id || item.id || '';
416
- const toolName = item.name || item.tool_name || '';
417
- const isXSearchCall = callId.startsWith('xs_') || X_SEARCH_INTERNAL_TOOLS.has(toolName);
418
- if (item.type === 'custom_tool_call' || isXSearchCall) {
419
- serverSideCalls.push({
420
- call_id: callId || null,
421
- name: toolName || null,
422
- arguments: item.arguments || item.input || null,
423
- });
424
- }
425
-
426
- const message = item.message || item;
427
- if (message.content) {
428
- if (typeof message.content === 'string' && !answerText) {
429
- answerText += (answerText ? '\n\n' : '') + message.content.trim();
430
- } else if (Array.isArray(message.content)) {
431
- for (const block of message.content) {
432
- if (!answerText) {
433
- const textPiece = block.output_text || block.text;
434
- if (typeof textPiece === 'string') {
435
- answerText += (answerText ? '\n\n' : '') + textPiece.trim();
436
- }
437
- }
438
-
439
- if (Array.isArray(block.annotations)) {
440
- for (const ann of block.annotations) {
441
- if (ann && (ann.type === 'url_citation' || ann.url)) {
442
- const urlStr = ann.url || ann.citation?.url;
443
- if (typeof urlStr === 'string' && (urlStr.startsWith('http://') || urlStr.startsWith('https://'))) {
444
- inlineCitations.push({
445
- url: urlStr,
446
- title: ann.title || ann.citation?.title || null,
447
- start_index: typeof ann.start_index === 'number' ? ann.start_index : null,
448
- end_index: typeof ann.end_index === 'number' ? ann.end_index : null,
449
- });
450
- collectedCitations.push(urlStr);
451
- }
452
- }
453
- }
454
- }
455
- }
456
- }
457
- }
159
+ const rawData: unknown = httpRes.data;
160
+ const attempt: CallLogAttempt = { http_status: httpRes.status, raw_response: rawData ?? null, error: null };
161
+ attempts.push(attempt);
162
+ if (!rawData || typeof rawData !== 'object' || Array.isArray(rawData)) {
163
+ const invalid = new HttpError('SEARCH_ERROR', 'Upstream xAI returned empty or unparseable response data.');
164
+ attempt.error = errorInfo(invalid);
165
+ throw invalid;
458
166
  }
459
- }
460
-
461
- const finalCitations = sanitizeUrls(collectedCitations);
462
- const hasCitations = finalCitations.length > 0 || inlineCitations.length > 0;
463
167
 
464
- const degraded = !hasCitations;
465
- const degradedReason = degraded ? 'No source citations returned by upstream x_search' : null;
168
+ const upstream = rawData as Record<string, unknown>;
169
+ if (upstream.status === 'failed' || upstream.error) {
170
+ const upstreamError = new HttpError('UPSTREAM_SERVER_ERROR', 'Upstream xAI reported a failed search.', httpRes.status);
171
+ attempt.error = errorInfo(upstreamError);
172
+ throw upstreamError;
173
+ }
466
174
 
467
- if (!answerText && !hasCitations) {
468
- throw new Error('Upstream returned no answer and no citations');
469
- }
175
+ const response = normalizeSearchResponse(upstream);
176
+ const hasCitations = response.citations.length > 0;
177
+ const degraded = !hasCitations;
178
+ const degradedReason = degraded ? 'No source citations returned by upstream x_search' : null;
470
179
 
471
- const searchExecution = serverSideCalls.length > 0 ? 'observed' : 'unreported';
180
+ if (!response.answer && !hasCitations) {
181
+ const empty = new HttpError('SEARCH_ERROR', 'Upstream xAI returned no answer or citations.');
182
+ attempt.error = errorInfo(empty);
183
+ throw empty;
184
+ }
472
185
 
473
- const warnings: string[] = [];
474
- if (credentialSource === 'oauth') {
475
- warnings.push('OAuth subscription search availability and quota are determined upstream by xAI; successful login does not guarantee search availability.');
476
- }
477
- if (degraded) {
478
- warnings.push('Result contains no source citations and cannot be treated as grounded search evidence.');
479
- }
186
+ const warnings: string[] = [];
187
+ if (response.response_status === 'incomplete') {
188
+ warnings.push('xAI returned an incomplete search response. Use the available citations and narrow the query if more coverage is needed.');
189
+ }
190
+ if (credentialSource === 'oauth') {
191
+ warnings.push('OAuth subscription search availability and quota are determined upstream by xAI; successful login does not guarantee search availability.');
192
+ }
193
+ if (degraded) {
194
+ warnings.push('Result contains no source citations and cannot be treated as grounded search evidence.');
195
+ }
480
196
 
481
- const result: XSearchResult = {
482
- success: true,
483
- provider: 'xai',
484
- tool: 'x_search',
485
- model: config.model,
486
- query: validated.query,
487
- credential_source: credentialSource,
488
- billing_mode: billingMode,
489
- answer: answerText,
490
- citations: finalCitations,
491
- inline_citations: inlineCitations,
492
- has_citations: hasCitations,
493
- degraded,
494
- degraded_reason: degradedReason,
495
- search_execution: searchExecution,
496
- server_side_calls: serverSideCalls,
497
- response_status: rawData.status || 'completed',
498
- incomplete_details: rawData.incomplete_details || null,
499
- usage: rawData.usage || null,
500
- warnings,
501
- log_file: null,
502
- };
503
- result.log_file = await persist('success', null);
504
- if (config.logEnabled && !result.log_file) {
505
- result.warnings.push('Call log could not be written.');
506
- }
507
- return result;
197
+ const result: XSearchResult = {
198
+ success: true,
199
+ provider: 'xai',
200
+ tool: 'x_search',
201
+ model: config.model,
202
+ query: validated.query,
203
+ credential_source: credentialSource,
204
+ billing_mode: billingMode,
205
+ ...response,
206
+ has_citations: hasCitations,
207
+ degraded,
208
+ degraded_reason: degradedReason,
209
+ warnings,
210
+ log_file: null,
211
+ };
212
+ result.log_file = await persist('success', null);
213
+ if (config.logEnabled && !result.log_file) {
214
+ result.warnings.push('Call log could not be written.');
215
+ }
216
+ return result;
508
217
  } catch (err: any) {
509
218
  const info = errorInfo(err);
510
219
  const logFile = await persist('error', info);