@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.
- package/README.md +3 -3
- package/TOOL.md +8 -6
- package/dist/package.json +2 -1
- package/dist/src/auth.d.ts.map +1 -1
- package/dist/src/auth.js +61 -46
- package/dist/src/auth.js.map +1 -1
- package/dist/src/call-log.d.ts.map +1 -1
- package/dist/src/call-log.js +52 -33
- package/dist/src/call-log.js.map +1 -1
- package/dist/src/device-login.d.ts +46 -0
- package/dist/src/device-login.d.ts.map +1 -0
- package/dist/src/device-login.js +72 -0
- package/dist/src/device-login.js.map +1 -0
- package/dist/src/multi-user/service.js +2 -2
- package/dist/src/multi-user/service.js.map +1 -1
- package/dist/src/search-input.d.ts +43 -0
- package/dist/src/search-input.d.ts.map +1 -0
- package/dist/src/search-input.js +105 -0
- package/dist/src/search-input.js.map +1 -0
- package/dist/src/search-response.d.ts +6 -0
- package/dist/src/search-response.d.ts.map +1 -0
- package/dist/src/search-response.js +125 -0
- package/dist/src/search-response.js.map +1 -0
- package/dist/src/search.d.ts +3 -19
- package/dist/src/search.d.ts.map +1 -1
- package/dist/src/search.js +54 -312
- package/dist/src/search.js.map +1 -1
- package/dist/src/server.d.ts +2 -0
- package/dist/src/server.d.ts.map +1 -1
- package/dist/src/server.js +61 -158
- package/dist/src/server.js.map +1 -1
- package/dist/src/tool-contract.d.ts +150 -0
- package/dist/src/tool-contract.d.ts.map +1 -0
- package/dist/src/tool-contract.js +83 -0
- package/dist/src/tool-contract.js.map +1 -0
- package/examples/codex.toml +1 -1
- package/examples/mcp.json +1 -1
- package/package.json +2 -1
- package/src/auth.ts +59 -46
- package/src/call-log.ts +52 -31
- package/src/device-login.ts +84 -0
- package/src/multi-user/service.ts +2 -2
- package/src/search-input.ts +113 -0
- package/src/search-response.ts +127 -0
- package/src/search.ts +127 -418
- package/src/server.ts +66 -170
- 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
|
|
6
|
-
|
|
7
|
-
|
|
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
|
-
|
|
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,
|
|
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
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
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
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
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
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
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
|
-
|
|
131
|
+
Authorization: `Bearer ${credential}`,
|
|
333
132
|
'Content-Type': 'application/json',
|
|
334
133
|
},
|
|
335
|
-
body:
|
|
134
|
+
body: serializedRequest,
|
|
336
135
|
signal,
|
|
337
136
|
timeoutSeconds: config.timeoutSeconds,
|
|
338
|
-
|
|
339
|
-
retries: resolveApiKey ? 0 : config.retries,
|
|
137
|
+
retries,
|
|
340
138
|
});
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
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
|
|
348
|
-
|
|
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
|
-
|
|
372
|
-
|
|
373
|
-
attempts.push(
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
error
|
|
377
|
-
|
|
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
|
-
|
|
465
|
-
|
|
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
|
-
|
|
468
|
-
|
|
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
|
-
|
|
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
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
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
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
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);
|