@scoheart/x-search-mcp 0.2.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 (105) hide show
  1. package/README.md +59 -75
  2. package/TOOL.md +28 -17
  3. package/dist/package.json +8 -1
  4. package/dist/src/auth.d.ts +14 -5
  5. package/dist/src/auth.d.ts.map +1 -1
  6. package/dist/src/auth.js +180 -118
  7. package/dist/src/auth.js.map +1 -1
  8. package/dist/src/call-log.d.ts.map +1 -1
  9. package/dist/src/call-log.js +52 -33
  10. package/dist/src/call-log.js.map +1 -1
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +9 -4
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/config.d.ts +3 -1
  15. package/dist/src/config.d.ts.map +1 -1
  16. package/dist/src/config.js +4 -4
  17. package/dist/src/config.js.map +1 -1
  18. package/dist/src/device-login.d.ts +46 -0
  19. package/dist/src/device-login.d.ts.map +1 -0
  20. package/dist/src/device-login.js +72 -0
  21. package/dist/src/device-login.js.map +1 -0
  22. package/dist/src/http-config.d.ts +9 -0
  23. package/dist/src/http-config.d.ts.map +1 -1
  24. package/dist/src/http-config.js +10 -5
  25. package/dist/src/http-config.js.map +1 -1
  26. package/dist/src/http-server.d.ts +10 -2
  27. package/dist/src/http-server.d.ts.map +1 -1
  28. package/dist/src/http-server.js +46 -15
  29. package/dist/src/http-server.js.map +1 -1
  30. package/dist/src/index.d.ts +3 -0
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +3 -0
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/multi-user/bindings.d.ts +21 -0
  35. package/dist/src/multi-user/bindings.d.ts.map +1 -0
  36. package/dist/src/multi-user/bindings.js +129 -0
  37. package/dist/src/multi-user/bindings.js.map +1 -0
  38. package/dist/src/multi-user/cli.d.ts +23 -0
  39. package/dist/src/multi-user/cli.d.ts.map +1 -0
  40. package/dist/src/multi-user/cli.js +82 -0
  41. package/dist/src/multi-user/cli.js.map +1 -0
  42. package/dist/src/multi-user/identity.d.ts +17 -0
  43. package/dist/src/multi-user/identity.d.ts.map +1 -0
  44. package/dist/src/multi-user/identity.js +78 -0
  45. package/dist/src/multi-user/identity.js.map +1 -0
  46. package/dist/src/multi-user/keys.d.ts +17 -0
  47. package/dist/src/multi-user/keys.d.ts.map +1 -0
  48. package/dist/src/multi-user/keys.js +54 -0
  49. package/dist/src/multi-user/keys.js.map +1 -0
  50. package/dist/src/multi-user/kms.d.ts +10 -0
  51. package/dist/src/multi-user/kms.d.ts.map +1 -0
  52. package/dist/src/multi-user/kms.js +83 -0
  53. package/dist/src/multi-user/kms.js.map +1 -0
  54. package/dist/src/multi-user/service.d.ts +13 -0
  55. package/dist/src/multi-user/service.d.ts.map +1 -0
  56. package/dist/src/multi-user/service.js +92 -0
  57. package/dist/src/multi-user/service.js.map +1 -0
  58. package/dist/src/multi-user/settings.d.ts +9 -0
  59. package/dist/src/multi-user/settings.d.ts.map +1 -0
  60. package/dist/src/multi-user/settings.js +323 -0
  61. package/dist/src/multi-user/settings.js.map +1 -0
  62. package/dist/src/search-input.d.ts +43 -0
  63. package/dist/src/search-input.d.ts.map +1 -0
  64. package/dist/src/search-input.js +105 -0
  65. package/dist/src/search-input.js.map +1 -0
  66. package/dist/src/search-response.d.ts +6 -0
  67. package/dist/src/search-response.d.ts.map +1 -0
  68. package/dist/src/search-response.js +125 -0
  69. package/dist/src/search-response.js.map +1 -0
  70. package/dist/src/search.d.ts +5 -20
  71. package/dist/src/search.d.ts.map +1 -1
  72. package/dist/src/search.js +67 -332
  73. package/dist/src/search.js.map +1 -1
  74. package/dist/src/server.d.ts +9 -1
  75. package/dist/src/server.d.ts.map +1 -1
  76. package/dist/src/server.js +88 -81
  77. package/dist/src/server.js.map +1 -1
  78. package/dist/src/tool-contract.d.ts +150 -0
  79. package/dist/src/tool-contract.d.ts.map +1 -0
  80. package/dist/src/tool-contract.js +83 -0
  81. package/dist/src/tool-contract.js.map +1 -0
  82. package/docs/multi-user.md +108 -0
  83. package/examples/codex.toml +1 -1
  84. package/examples/mcp.json +1 -1
  85. package/package.json +8 -1
  86. package/src/auth.ts +178 -125
  87. package/src/call-log.ts +52 -31
  88. package/src/cli.ts +9 -4
  89. package/src/config.ts +4 -4
  90. package/src/device-login.ts +84 -0
  91. package/src/http-config.ts +11 -5
  92. package/src/http-server.ts +55 -18
  93. package/src/index.ts +3 -0
  94. package/src/multi-user/bindings.ts +135 -0
  95. package/src/multi-user/cli.ts +78 -0
  96. package/src/multi-user/identity.ts +83 -0
  97. package/src/multi-user/keys.ts +66 -0
  98. package/src/multi-user/kms.ts +87 -0
  99. package/src/multi-user/service.ts +92 -0
  100. package/src/multi-user/settings.ts +329 -0
  101. package/src/search-input.ts +113 -0
  102. package/src/search-response.ts +127 -0
  103. package/src/search.ts +130 -426
  104. package/src/server.ts +97 -82
  105. package/src/tool-contract.ts +90 -0
package/src/search.ts CHANGED
@@ -1,217 +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
- import { getValidOAuthAccessToken, forceRefreshToken } from './auth.js';
5
- import type {
6
- XSearchInput,
7
- XSearchResult,
8
- InlineCitation,
9
- ServerSideCall,
10
- AuthMode,
11
- CallLogAttempt,
12
- } from './types.js';
4
+ import { getValidOAuthAccessToken, forceRefreshToken, oauthRequired } from './auth.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
- }
36
-
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
- }
9
+ export { validateCalendarDate, validateAndNormalizeHandles, validateSearchParams } from './search-input.js';
128
10
 
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;
15
+ resolveApiKey?: () => Promise<string>;
210
16
  }
211
17
 
212
- /**
213
- * Execute x_search call against xAI responses API.
214
- */
215
18
  function errorInfo(err: any): { code: string; message: string; status: number | null } {
216
19
  return {
217
20
  code: err?.code || 'SEARCH_ERROR',
@@ -228,17 +31,19 @@ function attemptFromError(err: any): CallLogAttempt {
228
31
  };
229
32
  }
230
33
 
231
- export async function executeSearch(rawParams: Record<string, any>, { signal }: ExecuteSearchOptions = {}): Promise<XSearchResult> {
34
+ /** Execute x_search against the xAI Responses API. */
35
+ export async function executeSearch(rawParams: Record<string, any>, { signal, resolveApiKey }: ExecuteSearchOptions = {}): Promise<XSearchResult> {
232
36
  const startedAt = new Date().toISOString();
233
37
  const startedMs = Date.now();
234
38
  const attempts: CallLogAttempt[] = [];
235
- let requestBody: Record<string, any> | null = null;
39
+ let requestBody: Record<string, unknown> | null = null;
236
40
  let credentialSource: 'api_key' | 'oauth' | null = null;
237
41
  let billingMode: 'api_metered' | 'subscription_oauth' | null = null;
238
42
  let model = '';
239
43
  let query = typeof rawParams?.query === 'string' ? rawParams.query : '';
240
44
 
241
45
  const persist = async (outcome: 'success' | 'error', error: { code: string; message: string; status: number | null } | null) => {
46
+ if (resolveApiKey) return null;
242
47
  try {
243
48
  const logFile = await writeCallLog({
244
49
  started_at: startedAt,
@@ -262,254 +67,153 @@ export async function executeSearch(rawParams: Record<string, any>, { signal }:
262
67
  };
263
68
 
264
69
  try {
265
- // Step 1: Strict parameter validation BEFORE credentials and network
266
- const validated = validateSearchParams(rawParams);
267
- query = validated.query;
268
- const config = loadConfig();
269
- model = config.model;
270
-
271
- // Step 2: Credential resolution
272
- const effectiveAuthMode = validated.auth_mode || config.authMode;
273
- let token: string;
274
-
275
- if (effectiveAuthMode === 'api_key') {
276
- if (!config.apiKey) {
277
- 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.');
278
- }
279
- token = config.apiKey;
280
- credentialSource = 'api_key';
281
- billingMode = 'api_metered';
282
- } else if (effectiveAuthMode === 'oauth') {
283
- token = await getValidOAuthAccessToken(signal);
284
- credentialSource = 'oauth';
285
- billingMode = 'subscription_oauth';
286
- } else {
287
- // Mode 'auto'
288
- if (config.apiKey) {
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
+ }
289
88
  token = config.apiKey;
290
89
  credentialSource = 'api_key';
291
90
  billingMode = 'api_metered';
292
91
  } else {
293
- try {
294
- token = await getValidOAuthAccessToken(signal);
295
- credentialSource = 'oauth';
296
- billingMode = 'subscription_oauth';
297
- } catch (error) {
298
- if (error instanceof HttpError && error.code === 'cancelled') throw error;
299
- throw new Error('Credential error: No valid credentials found. Provide XAI_API_KEY or authenticate via "x-search-mcp auth login".');
300
- }
92
+ token = await getValidOAuthAccessToken(signal);
93
+ credentialSource = 'oauth';
94
+ billingMode = 'subscription_oauth';
301
95
  }
302
- }
303
96
 
304
- // Step 3: Construct request body
305
- const toolConfig: Record<string, any> = {
306
- type: 'x_search',
307
- };
308
- if (validated.allowed_x_handles) toolConfig.allowed_x_handles = validated.allowed_x_handles;
309
- if (validated.excluded_x_handles) toolConfig.excluded_x_handles = validated.excluded_x_handles;
310
- if (validated.from_date) toolConfig.from_date = validated.from_date;
311
- if (validated.to_date) toolConfig.to_date = validated.to_date;
312
- if (validated.enable_image_understanding !== undefined) toolConfig.enable_image_understanding = validated.enable_image_understanding;
313
- if (validated.enable_video_understanding !== undefined) toolConfig.enable_video_understanding = validated.enable_video_understanding;
314
-
315
- requestBody = {
316
- model: config.model,
317
- input: [
318
- {
319
- role: 'user',
320
- content: validated.query,
321
- },
322
- ],
323
- tools: [toolConfig],
324
- store: false,
325
- max_turns: config.maxTurns,
326
- };
327
-
328
- if (config.reasoningEffort) {
329
- requestBody.reasoning = {
330
- 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,
331
118
  };
332
- }
333
119
 
334
- // Step 4: Execute HTTP request with single OAuth 401 refresh retry
335
- let httpRes: any;
336
- try {
337
- 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({
338
128
  url: XAI_RESPONSES_URL,
339
129
  method: 'POST',
340
130
  headers: {
341
- 'Authorization': `Bearer ${token}`,
131
+ Authorization: `Bearer ${credential}`,
342
132
  'Content-Type': 'application/json',
343
133
  },
344
- body: JSON.stringify(requestBody),
134
+ body: serializedRequest,
345
135
  signal,
346
136
  timeoutSeconds: config.timeoutSeconds,
347
- retries: config.retries,
137
+ retries,
348
138
  });
349
- } catch (err: any) {
350
- attempts.push(attemptFromError(err));
351
- // If OAuth returns HTTP 401, force-refresh token once and retry once
352
- 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;
353
147
  const freshToken = await forceRefreshToken(token, signal);
354
148
  try {
355
- httpRes = await sendHttpRequest({
356
- url: XAI_RESPONSES_URL,
357
- method: 'POST',
358
- headers: {
359
- 'Authorization': `Bearer ${freshToken}`,
360
- 'Content-Type': 'application/json',
361
- },
362
- body: JSON.stringify(requestBody),
363
- signal,
364
- timeoutSeconds: config.timeoutSeconds,
365
- retries: 0,
366
- });
367
- } catch (retryErr: any) {
149
+ httpRes = await requestWithCredential(freshToken, 0);
150
+ } catch (retryErr) {
368
151
  attempts.push(attemptFromError(retryErr));
152
+ if (retryErr instanceof HttpError && retryErr.status === 401) {
153
+ throw oauthRequired('xAI rejected the Grok OAuth credential after refresh.', 401);
154
+ }
369
155
  throw retryErr;
370
156
  }
371
- } else {
372
- throw err;
373
157
  }
374
- }
375
-
376
- const rawData = httpRes.data;
377
- if (!rawData || typeof rawData !== 'object') {
378
- attempts.push({
379
- http_status: httpRes.status ?? null,
380
- raw_response: rawData ?? null,
381
- error: {
382
- code: 'SEARCH_ERROR',
383
- message: 'Upstream xAI API returned empty or unparseable response data',
384
- status: httpRes.status ?? null,
385
- },
386
- });
387
- throw new Error('Upstream xAI API returned empty or unparseable response data');
388
- }
389
- attempts.push({ http_status: httpRes.status ?? null, raw_response: rawData, error: null });
390
-
391
- // Check for upstream error status
392
- if (rawData.status === 'failed' || rawData.error) {
393
- const errMsg = rawData.error?.message || 'Upstream xAI response status is failed';
394
- const upstreamError = new HttpError('UPSTREAM_SERVER_ERROR', errMsg, httpRes.status);
395
- attempts[attempts.length - 1].error = errorInfo(upstreamError);
396
- throw upstreamError;
397
- }
398
158
 
399
- // Step 5: Extract answer, citations, inline citations, and tool execution details
400
- let answerText = '';
401
- if (typeof rawData.output_text === 'string' && rawData.output_text.trim()) {
402
- answerText = rawData.output_text.trim();
403
- }
404
-
405
- const collectedCitations: string[] = [];
406
- const inlineCitations: InlineCitation[] = [];
407
- const serverSideCalls: ServerSideCall[] = [];
408
-
409
- // Top-level sources or citations
410
- if (Array.isArray(rawData.citations)) {
411
- collectedCitations.push(...rawData.citations);
412
- }
413
- if (Array.isArray(rawData.sources)) {
414
- collectedCitations.push(...rawData.sources);
415
- }
416
-
417
- // Parse output items
418
- if (Array.isArray(rawData.output)) {
419
- for (const item of rawData.output) {
420
- const callId = item.call_id || item.id || '';
421
- const toolName = item.name || item.tool_name || '';
422
- const isXSearchCall = callId.startsWith('xs_') || X_SEARCH_INTERNAL_TOOLS.has(toolName);
423
- if (item.type === 'custom_tool_call' || isXSearchCall) {
424
- serverSideCalls.push({
425
- call_id: callId || null,
426
- name: toolName || null,
427
- arguments: item.arguments || item.input || null,
428
- });
429
- }
430
-
431
- const message = item.message || item;
432
- if (message.content) {
433
- if (typeof message.content === 'string' && !answerText) {
434
- answerText += (answerText ? '\n\n' : '') + message.content.trim();
435
- } else if (Array.isArray(message.content)) {
436
- for (const block of message.content) {
437
- if (!answerText) {
438
- const textPiece = block.output_text || block.text;
439
- if (typeof textPiece === 'string') {
440
- answerText += (answerText ? '\n\n' : '') + textPiece.trim();
441
- }
442
- }
443
-
444
- if (Array.isArray(block.annotations)) {
445
- for (const ann of block.annotations) {
446
- if (ann && (ann.type === 'url_citation' || ann.url)) {
447
- const urlStr = ann.url || ann.citation?.url;
448
- if (typeof urlStr === 'string' && (urlStr.startsWith('http://') || urlStr.startsWith('https://'))) {
449
- inlineCitations.push({
450
- url: urlStr,
451
- title: ann.title || ann.citation?.title || null,
452
- start_index: typeof ann.start_index === 'number' ? ann.start_index : null,
453
- end_index: typeof ann.end_index === 'number' ? ann.end_index : null,
454
- });
455
- collectedCitations.push(urlStr);
456
- }
457
- }
458
- }
459
- }
460
- }
461
- }
462
- }
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;
463
166
  }
464
- }
465
-
466
- const finalCitations = sanitizeUrls(collectedCitations);
467
- const hasCitations = finalCitations.length > 0 || inlineCitations.length > 0;
468
167
 
469
- const degraded = !hasCitations;
470
- 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
+ }
471
174
 
472
- if (!answerText && !hasCitations) {
473
- throw new Error('Upstream returned no answer and no citations');
474
- }
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;
475
179
 
476
- 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
+ }
477
185
 
478
- const warnings: string[] = [];
479
- if (credentialSource === 'oauth') {
480
- warnings.push('OAuth subscription search availability and quota are determined upstream by xAI; successful login does not guarantee search availability.');
481
- }
482
- if (degraded) {
483
- warnings.push('Result contains no source citations and cannot be treated as grounded search evidence.');
484
- }
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
+ }
485
196
 
486
- const result: XSearchResult = {
487
- success: true,
488
- provider: 'xai',
489
- tool: 'x_search',
490
- model: config.model,
491
- query: validated.query,
492
- credential_source: credentialSource,
493
- billing_mode: billingMode,
494
- answer: answerText,
495
- citations: finalCitations,
496
- inline_citations: inlineCitations,
497
- has_citations: hasCitations,
498
- degraded,
499
- degraded_reason: degradedReason,
500
- search_execution: searchExecution,
501
- server_side_calls: serverSideCalls,
502
- response_status: rawData.status || 'completed',
503
- incomplete_details: rawData.incomplete_details || null,
504
- usage: rawData.usage || null,
505
- warnings,
506
- log_file: null,
507
- };
508
- result.log_file = await persist('success', null);
509
- if (config.logEnabled && !result.log_file) {
510
- result.warnings.push('Call log could not be written.');
511
- }
512
- 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;
513
217
  } catch (err: any) {
514
218
  const info = errorInfo(err);
515
219
  const logFile = await persist('error', info);