@scoheart/x-search-mcp 0.3.0 → 0.6.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/.env.example +7 -10
  2. package/README.md +29 -17
  3. package/THIRD_PARTY_NOTICES.md +4 -0
  4. package/TOOL.md +58 -77
  5. package/dist/evidence-licenses.txt +791 -0
  6. package/dist/evidence.html +170 -0
  7. package/dist/package.json +11 -3
  8. package/dist/src/auth.d.ts.map +1 -1
  9. package/dist/src/auth.js +67 -57
  10. package/dist/src/auth.js.map +1 -1
  11. package/dist/src/call-log.d.ts +5 -4
  12. package/dist/src/call-log.d.ts.map +1 -1
  13. package/dist/src/call-log.js +82 -54
  14. package/dist/src/call-log.js.map +1 -1
  15. package/dist/src/cli.d.ts.map +1 -1
  16. package/dist/src/cli.js +26 -19
  17. package/dist/src/cli.js.map +1 -1
  18. package/dist/src/config.d.ts.map +1 -1
  19. package/dist/src/config.js +12 -16
  20. package/dist/src/config.js.map +1 -1
  21. package/dist/src/device-login.d.ts +20 -0
  22. package/dist/src/device-login.d.ts.map +1 -0
  23. package/dist/src/device-login.js +110 -0
  24. package/dist/src/device-login.js.map +1 -0
  25. package/dist/src/events.d.ts +16 -0
  26. package/dist/src/events.d.ts.map +1 -0
  27. package/dist/src/events.js +128 -0
  28. package/dist/src/events.js.map +1 -0
  29. package/dist/src/evidence-app.d.ts +4 -0
  30. package/dist/src/evidence-app.d.ts.map +1 -0
  31. package/dist/src/evidence-app.js +17 -0
  32. package/dist/src/evidence-app.js.map +1 -0
  33. package/dist/src/http-server.d.ts +1 -0
  34. package/dist/src/http-server.d.ts.map +1 -1
  35. package/dist/src/http-server.js +6 -4
  36. package/dist/src/http-server.js.map +1 -1
  37. package/dist/src/http.d.ts +12 -15
  38. package/dist/src/http.d.ts.map +1 -1
  39. package/dist/src/http.js +78 -118
  40. package/dist/src/http.js.map +1 -1
  41. package/dist/src/index.d.ts +1 -0
  42. package/dist/src/index.d.ts.map +1 -1
  43. package/dist/src/index.js.map +1 -1
  44. package/dist/src/multi-user/service.d.ts.map +1 -1
  45. package/dist/src/multi-user/service.js +3 -2
  46. package/dist/src/multi-user/service.js.map +1 -1
  47. package/dist/src/search-input.d.ts +31 -0
  48. package/dist/src/search-input.d.ts.map +1 -0
  49. package/dist/src/search-input.js +102 -0
  50. package/dist/src/search-input.js.map +1 -0
  51. package/dist/src/search-response.d.ts +26 -0
  52. package/dist/src/search-response.d.ts.map +1 -0
  53. package/dist/src/search-response.js +128 -0
  54. package/dist/src/search-response.js.map +1 -0
  55. package/dist/src/search.d.ts +7 -20
  56. package/dist/src/search.d.ts.map +1 -1
  57. package/dist/src/search.js +129 -440
  58. package/dist/src/search.js.map +1 -1
  59. package/dist/src/server.d.ts +8 -9
  60. package/dist/src/server.d.ts.map +1 -1
  61. package/dist/src/server.js +110 -193
  62. package/dist/src/server.js.map +1 -1
  63. package/dist/src/tool-contract.d.ts +183 -0
  64. package/dist/src/tool-contract.d.ts.map +1 -0
  65. package/dist/src/tool-contract.js +88 -0
  66. package/dist/src/tool-contract.js.map +1 -0
  67. package/dist/src/types.d.ts +7 -37
  68. package/dist/src/types.d.ts.map +1 -1
  69. package/dist/src/watch-cli.d.ts +2 -0
  70. package/dist/src/watch-cli.d.ts.map +1 -0
  71. package/dist/src/watch-cli.js +41 -0
  72. package/dist/src/watch-cli.js.map +1 -0
  73. package/dist/src/watch-store.d.ts +41 -0
  74. package/dist/src/watch-store.d.ts.map +1 -0
  75. package/dist/src/watch-store.js +171 -0
  76. package/dist/src/watch-store.js.map +1 -0
  77. package/dist/ui/evidence.d.ts +2 -0
  78. package/dist/ui/evidence.d.ts.map +1 -0
  79. package/dist/ui/evidence.js +150 -0
  80. package/dist/ui/evidence.js.map +1 -0
  81. package/docs/events-and-apps.md +40 -0
  82. package/examples/codex.toml +6 -7
  83. package/examples/mcp.json +2 -6
  84. package/package.json +11 -3
  85. package/server.json +34 -0
  86. package/src/auth.ts +65 -57
  87. package/src/call-log.ts +83 -53
  88. package/src/cli.ts +26 -19
  89. package/src/config.ts +11 -13
  90. package/src/device-login.ts +120 -0
  91. package/src/events.ts +124 -0
  92. package/src/evidence-app.ts +19 -0
  93. package/src/http-server.ts +7 -4
  94. package/src/http.ts +83 -162
  95. package/src/index.ts +1 -0
  96. package/src/multi-user/service.ts +3 -2
  97. package/src/search-input.ts +109 -0
  98. package/src/search-response.ts +122 -0
  99. package/src/search.ts +131 -476
  100. package/src/server.ts +114 -207
  101. package/src/tool-contract.ts +96 -0
  102. package/src/types.ts +8 -40
  103. package/src/watch-cli.ts +35 -0
  104. package/src/watch-store.ts +182 -0
  105. package/tsconfig.json +2 -1
package/src/search.ts CHANGED
@@ -1,514 +1,169 @@
1
- import { sendHttpRequest, HttpError } from './http.js';
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { abortError, HttpError, sendHttpRequest } from './http.js';
2
3
  import { loadConfig } from './config.js';
3
4
  import { writeCallLog } from './call-log.js';
4
5
  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';
6
+ import { validateSearchParams } from './search-input.js';
7
+ import { normalizeSearchResponse } from './search-response.js';
8
+ import type { XSearchResult } from './tool-contract.js';
9
+ import type { AuthMode, CallLogAttempt, CallLogEntry } from './types.js';
13
10
 
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
- ]);
11
+ export { validateCalendarDate, validateAndNormalizeHandles, validateSearchParams } from './search-input.js';
25
12
 
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
- }
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
- }
13
+ const endpoint = 'https://api.x.ai/v1/responses';
207
14
 
208
15
  export interface ExecuteSearchOptions {
209
16
  signal?: AbortSignal;
17
+ authMode?: AuthMode;
210
18
  resolveApiKey?: () => Promise<string>;
19
+ trackCleanup?: (task: Promise<unknown>) => void;
211
20
  }
212
21
 
213
- /**
214
- * Execute x_search call against xAI responses API.
215
- */
216
- function errorInfo(err: any): { code: string; message: string; status: number | null } {
217
- return {
218
- code: err?.code || 'SEARCH_ERROR',
219
- message: err?.message || 'Search execution failed',
220
- status: err?.status ?? null,
221
- };
22
+ function logError(error: unknown): NonNullable<CallLogEntry['error']> {
23
+ return error instanceof HttpError
24
+ ? { code: error.code, message: error.message, status: error.status }
25
+ : { code: 'SEARCH_ERROR', message: 'The search could not be completed.', status: null };
222
26
  }
223
27
 
224
- function attemptFromError(err: any): CallLogAttempt {
225
- return {
226
- http_status: err?.status ?? null,
227
- raw_response: err instanceof HttpError ? err.data ?? null : null,
228
- error: errorInfo(err),
229
- };
28
+ function untilAborted<T>(task: Promise<T>, signal: AbortSignal): Promise<T> {
29
+ return new Promise((resolve, reject) => {
30
+ const abort = () => reject(abortError(signal));
31
+ signal.addEventListener('abort', abort, { once: true });
32
+ task.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
33
+ if (signal.aborted) abort();
34
+ });
230
35
  }
231
36
 
232
- export async function executeSearch(rawParams: Record<string, any>, { signal, resolveApiKey }: ExecuteSearchOptions = {}): Promise<XSearchResult> {
37
+ /** One time budget covers key lookup, any credential refresh, rate limiting and response reads. */
38
+ export async function executeSearch(rawParams: unknown, options: ExecuteSearchOptions = {}): Promise<XSearchResult> {
39
+ const started = performance.now();
40
+ const params = validateSearchParams(rawParams);
41
+ const managed = Boolean(options.resolveApiKey);
42
+ const config = loadConfig({ managed });
233
43
  const startedAt = new Date().toISOString();
234
- const startedMs = Date.now();
235
- const attempts: CallLogAttempt[] = [];
236
- let requestBody: Record<string, any> | null = null;
237
- let credentialSource: 'api_key' | 'oauth' | null = null;
238
- let billingMode: 'api_metered' | 'subscription_oauth' | null = null;
239
- let model = '';
240
- let query = typeof rawParams?.query === 'string' ? rawParams.query : '';
44
+ const deadline = started + config.deadlineMs;
45
+ const budget = new AbortController();
46
+ const deadlineError = new HttpError('SEARCH_DEADLINE_EXCEEDED', 'The search exceeded its total time budget.');
47
+ const timer = setTimeout(() => budget.abort(deadlineError), Math.max(0, deadline - performance.now()));
48
+ const signal = options.signal ? AbortSignal.any([options.signal, budget.signal]) : budget.signal;
241
49
 
242
- const persist = async (outcome: 'success' | 'error', error: { code: string; message: string; status: number | null } | null) => {
243
- if (resolveApiKey) return null;
244
- try {
245
- const logFile = await writeCallLog({
246
- started_at: startedAt,
247
- elapsed_ms: Date.now() - startedMs,
248
- endpoint: XAI_RESPONSES_URL,
249
- model,
250
- query,
251
- credential_source: credentialSource,
252
- billing_mode: billingMode,
253
- request: requestBody,
254
- attempts,
255
- outcome,
256
- error,
257
- });
258
- if (logFile) console.error(`x-search-mcp call_log=${logFile}`);
259
- return logFile;
260
- } catch (err: any) {
261
- console.error(`x-search-mcp call_log_error=${err?.message || 'failed to write call log'}`);
262
- return null;
263
- }
264
- };
265
-
266
- 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.');
285
- }
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';
50
+ function checkBudget() {
51
+ if (!signal.aborted && performance.now() >= deadline) budget.abort(deadlineError);
52
+ if (signal.aborted) throw abortError(signal);
293
53
  }
294
54
 
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
-
306
- requestBody = {
55
+ const { query, detail, ...filters } = params;
56
+ const body = {
307
57
  model: config.model,
308
- input: [
309
- {
310
- role: 'user',
311
- content: validated.query,
312
- },
313
- ],
314
- tools: [toolConfig],
58
+ input: [{ role: 'user', content: query }],
59
+ tools: [{ type: 'x_search', ...filters }],
315
60
  store: false,
316
61
  max_turns: config.maxTurns,
62
+ ...(config.reasoningEffort ? { reasoning: { effort: config.reasoningEffort } } : {}),
317
63
  };
64
+ const serialized = JSON.stringify(body);
65
+ const attempts: CallLogAttempt[] = [];
66
+ const mode = options.authMode ?? config.authMode;
67
+ const usesOAuth = !managed && (mode === 'oauth' || (mode === 'auto' && !config.apiKey));
68
+ const credentialSource = usesOAuth ? 'oauth' : 'api_key';
69
+ let failure: CallLogEntry['error'] = null;
70
+ let xSearchCalls: number | null = null;
318
71
 
319
- if (config.reasoningEffort) {
320
- requestBody.reasoning = {
321
- effort: config.reasoningEffort,
322
- };
72
+ function waitForCredential(task: Promise<string>): Promise<string> {
73
+ // A submitted refresh can rotate the token. Let it persist under the lock
74
+ // while freeing the search caller on timeout or disconnection.
75
+ options.trackCleanup?.(task);
76
+ return untilAborted(task, signal);
323
77
  }
324
78
 
325
- // Step 4: Execute HTTP request with single OAuth 401 refresh retry
326
- let httpRes: any;
327
- try {
328
- httpRes = await sendHttpRequest({
329
- url: XAI_RESPONSES_URL,
330
- method: 'POST',
331
- headers: {
332
- 'Authorization': `Bearer ${token}`,
333
- 'Content-Type': 'application/json',
334
- },
335
- body: JSON.stringify(requestBody),
336
- signal,
337
- timeoutSeconds: config.timeoutSeconds,
338
- // Managed requests must not retry an old key after it has been unbound.
339
- retries: resolveApiKey ? 0 : config.retries,
340
- });
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) {
345
- const freshToken = await forceRefreshToken(token, signal);
346
- 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) {
360
- attempts.push(attemptFromError(retryErr));
361
- if (retryErr instanceof HttpError && retryErr.status === 401) {
362
- throw oauthRequired('xAI rejected the Grok OAuth credential after refresh.', 401);
363
- }
364
- throw retryErr;
365
- }
366
- } else {
367
- throw err;
79
+ async function post(credential: string) {
80
+ checkBudget();
81
+ try {
82
+ const response = await sendHttpRequest({
83
+ url: endpoint, method: 'POST', body: serialized, signal, maxResponseBytes: config.maxResponseBytes,
84
+ headers: { Authorization: `Bearer ${credential}`, 'Content-Type': 'application/json' },
85
+ });
86
+ attempts.push({ http_status: response.status, raw_response: config.logMode === 'debug' ? response.data : null, error: null });
87
+ return response;
88
+ } catch (error) {
89
+ const info = logError(error);
90
+ attempts.push({
91
+ http_status: info.status,
92
+ raw_response: config.logMode === 'debug' && error instanceof HttpError ? error.data ?? null : null,
93
+ error: info,
94
+ });
95
+ throw error;
368
96
  }
369
97
  }
370
98
 
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
- }
99
+ try {
100
+ checkBudget();
101
+ const credential = options.resolveApiKey ? await waitForCredential(options.resolveApiKey())
102
+ : usesOAuth ? await waitForCredential(getValidOAuthAccessToken(signal))
103
+ : config.apiKey;
104
+ if (!credential) {
105
+ throw managed ? new HttpError('XAI_KEY_REQUIRED', 'Bind an xAI API key in Settings.', 409)
106
+ : new HttpError('API_KEY_REQUIRED', 'Configure XAI_API_KEY or XAI_API_KEY_FILE.');
107
+ }
438
108
 
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
- }
109
+ let response;
110
+ try {
111
+ response = await post(credential);
112
+ } catch (error) {
113
+ if (!(error instanceof HttpError)) throw error;
114
+ if (usesOAuth && error.status === 401) {
115
+ const fresh = await waitForCredential(forceRefreshToken(credential, signal));
116
+ try { response = await post(fresh); } catch (retryError) {
117
+ if (retryError instanceof HttpError && retryError.status === 401) {
118
+ throw oauthRequired('xAI rejected the Grok OAuth credential after refresh.', 401);
455
119
  }
120
+ throw retryError;
456
121
  }
122
+ } else if (!managed && error.status === 429 && error.retryAfterMs !== undefined
123
+ && error.retryAfterMs < deadline - performance.now()) {
124
+ if (error.retryAfterMs > 0) await delay(error.retryAfterMs, undefined, { signal });
125
+ response = await post(credential);
126
+ } else {
127
+ throw error;
457
128
  }
458
129
  }
459
- }
460
-
461
- const finalCitations = sanitizeUrls(collectedCitations);
462
- const hasCitations = finalCitations.length > 0 || inlineCitations.length > 0;
463
-
464
- const degraded = !hasCitations;
465
- const degradedReason = degraded ? 'No source citations returned by upstream x_search' : null;
466
130
 
467
- if (!answerText && !hasCitations) {
468
- throw new Error('Upstream returned no answer and no citations');
469
- }
470
-
471
- const searchExecution = serverSideCalls.length > 0 ? 'observed' : 'unreported';
472
-
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
- }
131
+ const data = response.data as unknown;
132
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
133
+ throw new HttpError('INVALID_UPSTREAM_RESPONSE', 'xAI did not return a search response object.', response.status);
134
+ }
135
+ const upstream = data as Record<string, unknown>;
136
+ if (upstream.status === 'failed' || upstream.error) {
137
+ throw new HttpError('UPSTREAM_SERVER_ERROR', 'xAI reported a failed search.', response.status);
138
+ }
480
139
 
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;
508
- } catch (err: any) {
509
- const info = errorInfo(err);
510
- const logFile = await persist('error', info);
511
- if (err && typeof err === 'object') err.logFile = logFile;
512
- throw err;
140
+ const normalized = normalizeSearchResponse(upstream, detail ?? 'concise');
141
+ if (!normalized.answer && !normalized.sources.length) {
142
+ throw new HttpError('EMPTY_SEARCH_RESPONSE', 'xAI returned no answer or sources.', response.status);
143
+ }
144
+ checkBudget();
145
+ xSearchCalls = normalized.usage.x_search_calls;
146
+ return {
147
+ ...normalized,
148
+ model: config.model,
149
+ usage: { ...normalized.usage, requests: attempts.length },
150
+ elapsed_ms: Math.round(performance.now() - started),
151
+ };
152
+ } catch (error) {
153
+ const cause = signal.aborted ? abortError(signal) : error;
154
+ failure = logError(cause);
155
+ throw cause;
156
+ } finally {
157
+ clearTimeout(timer);
158
+ if (config.logMode !== 'off') {
159
+ const log = writeCallLog({
160
+ started_at: startedAt,
161
+ elapsed_ms: Math.round(performance.now() - started),
162
+ endpoint, model: config.model, query, credential_source: credentialSource,
163
+ billing_mode: usesOAuth ? 'subscription_oauth' : 'api_metered',
164
+ request: body, attempts, outcome: failure ? 'error' : 'success', error: failure, x_search_calls: xSearchCalls,
165
+ }).catch(() => null);
166
+ options.trackCleanup?.(log);
167
+ }
513
168
  }
514
169
  }