@scoheart/x-search-mcp 0.4.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 +28 -16
  3. package/THIRD_PARTY_NOTICES.md +4 -0
  4. package/TOOL.md +57 -78
  5. package/dist/evidence-licenses.txt +791 -0
  6. package/dist/evidence.html +170 -0
  7. package/dist/package.json +10 -3
  8. package/dist/src/auth.d.ts.map +1 -1
  9. package/dist/src/auth.js +6 -11
  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 +38 -29
  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 +15 -41
  22. package/dist/src/device-login.d.ts.map +1 -1
  23. package/dist/src/device-login.js +101 -63
  24. package/dist/src/device-login.js.map +1 -1
  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 +2 -1
  46. package/dist/src/multi-user/service.js.map +1 -1
  47. package/dist/src/search-input.d.ts +5 -17
  48. package/dist/src/search-input.d.ts.map +1 -1
  49. package/dist/src/search-input.js +5 -8
  50. package/dist/src/search-input.js.map +1 -1
  51. package/dist/src/search-response.d.ts +25 -5
  52. package/dist/src/search-response.d.ts.map +1 -1
  53. package/dist/src/search-response.js +97 -94
  54. package/dist/src/search-response.js.map +1 -1
  55. package/dist/src/search.d.ts +6 -3
  56. package/dist/src/search.d.ts.map +1 -1
  57. package/dist/src/search.js +131 -184
  58. package/dist/src/search.js.map +1 -1
  59. package/dist/src/server.d.ts +7 -10
  60. package/dist/src/server.d.ts.map +1 -1
  61. package/dist/src/server.js +109 -95
  62. package/dist/src/server.js.map +1 -1
  63. package/dist/src/tool-contract.d.ts +159 -126
  64. package/dist/src/tool-contract.d.ts.map +1 -1
  65. package/dist/src/tool-contract.js +78 -73
  66. package/dist/src/tool-contract.js.map +1 -1
  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 +10 -3
  85. package/server.json +34 -0
  86. package/src/auth.ts +6 -11
  87. package/src/call-log.ts +39 -30
  88. package/src/cli.ts +26 -19
  89. package/src/config.ts +11 -13
  90. package/src/device-login.ts +107 -71
  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 +2 -1
  97. package/src/search-input.ts +5 -9
  98. package/src/search-response.ts +90 -95
  99. package/src/search.ts +126 -180
  100. package/src/server.ts +115 -104
  101. package/src/tool-contract.ts +82 -76
  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/http.ts CHANGED
@@ -1,197 +1,118 @@
1
- import { request, EnvHttpProxyAgent } from 'undici';
1
+ import { request, EnvHttpProxyAgent, type Dispatcher } from 'undici';
2
2
  import { version } from './version.js';
3
3
 
4
- // Global HTTP proxy agent reading standard environment variables: HTTP_PROXY, HTTPS_PROXY, NO_PROXY
5
4
  const proxyAgent = new EnvHttpProxyAgent();
5
+ const maxAuthResponseBytes = 64 * 1024;
6
6
 
7
7
  export class HttpError extends Error {
8
- code: string;
9
- status: number | null;
10
- data?: any;
11
-
12
- constructor(code: string, message: string, status: number | null = null, data?: any) {
8
+ constructor(
9
+ readonly code: string,
10
+ message: string,
11
+ readonly status: number | null = null,
12
+ readonly data?: any,
13
+ readonly retryAfterMs?: number,
14
+ ) {
13
15
  super(message);
14
16
  this.name = 'HttpError';
15
- this.code = code;
16
- this.status = status;
17
- this.data = data;
18
17
  }
19
18
  }
20
19
 
21
- /**
22
- * Maps HTTP status code to sanitized local error.
23
- * Prevents leaking any credentials that might be echoed in raw upstream response bodies.
24
- */
25
- export function createSanitizedHttpError(status: number, data?: any): HttpError {
26
- if (status === 401) {
27
- return new HttpError('UPSTREAM_AUTH_ERROR', 'Authentication failed with upstream xAI API (HTTP 401)', 401, data);
28
- }
29
- if (status === 403) {
30
- return new HttpError(
31
- 'UPSTREAM_FORBIDDEN',
32
- 'Access forbidden (HTTP 403). The account may lack required API balance or X Search subscription entitlements.',
33
- 403,
34
- data
35
- );
36
- }
37
- if (status === 404) {
38
- return new HttpError('UPSTREAM_NOT_FOUND', 'Requested resource not found on upstream xAI API (HTTP 404)', 404, data);
39
- }
40
- if (status === 429) {
41
- return new HttpError('UPSTREAM_RATE_LIMITED', 'Upstream xAI rate limit exceeded (HTTP 429)', 429, data);
42
- }
43
- if (status >= 500 && status < 600) {
44
- return new HttpError(
45
- 'UPSTREAM_SERVER_ERROR',
46
- `Upstream xAI service encountered a server error (HTTP ${status})`,
47
- status,
48
- data
49
- );
50
- }
51
- return new HttpError('UPSTREAM_HTTP_ERROR', `Upstream xAI returned HTTP error ${status}`, status, data);
20
+ export function abortError(signal: AbortSignal): HttpError {
21
+ return signal.reason instanceof HttpError
22
+ ? signal.reason
23
+ : new HttpError('CANCELLED', 'The request was cancelled.');
52
24
  }
53
25
 
54
- function sleep(ms: number, signal?: AbortSignal): Promise<void> {
55
- return new Promise((resolve, reject) => {
56
- if (signal?.aborted) {
57
- return reject(new HttpError('cancelled', 'Request was cancelled by client'));
58
- }
59
- const timer = setTimeout(() => {
60
- signal?.removeEventListener('abort', onAbort);
61
- resolve();
62
- }, ms);
63
-
64
- function onAbort() {
65
- clearTimeout(timer);
66
- reject(new HttpError('cancelled', 'Request was cancelled by client'));
67
- }
26
+ function parseRetryAfter(value: string | string[] | undefined): number | undefined {
27
+ if (typeof value !== 'string') return undefined;
28
+ const header = value.trim();
29
+ if (/^\d+$/.test(header)) {
30
+ const ms = Number(header) * 1000;
31
+ return Number.isSafeInteger(ms) ? ms : undefined;
32
+ }
33
+ const date = /^[A-Za-z]{3}, /.test(header) ? Date.parse(header) : NaN;
34
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
35
+ }
68
36
 
69
- signal?.addEventListener('abort', onAbort, { once: true });
70
- });
37
+ function httpStatusError(status: number, data: unknown, retryAfterMs?: number): HttpError {
38
+ switch (status) {
39
+ case 401: return new HttpError('UPSTREAM_AUTH_ERROR', 'xAI rejected the credential (HTTP 401).', status, data);
40
+ case 403: return new HttpError('UPSTREAM_FORBIDDEN', 'xAI denied access. Check API balance or X Search subscription entitlement.', status, data);
41
+ case 429: return new HttpError('UPSTREAM_RATE_LIMITED', 'xAI rate-limited this request.', status, data, retryAfterMs);
42
+ default:
43
+ return new HttpError(status >= 500 ? 'UPSTREAM_SERVER_ERROR' : 'UPSTREAM_HTTP_ERROR',
44
+ `xAI returned HTTP ${status}.`, status, data);
45
+ }
71
46
  }
72
47
 
73
48
  export interface SendHttpOptions {
74
49
  url: string;
75
- method?: string;
50
+ method?: Dispatcher.HttpMethod;
76
51
  headers?: Record<string, string>;
77
52
  body?: string | Buffer | null;
78
53
  signal?: AbortSignal;
79
- timeoutSeconds?: number;
80
- retries?: number;
81
- isRefresh?: boolean;
54
+ timeoutMs?: number;
55
+ maxResponseBytes?: number;
82
56
  }
83
57
 
84
58
  export interface SendHttpResponse {
85
59
  status: number;
86
- headers: Record<string, any>;
87
60
  data: any;
88
61
  }
89
62
 
90
- export async function sendHttpRequest({
91
- url,
92
- method = 'GET',
93
- headers = {},
94
- body = null,
95
- signal,
96
- timeoutSeconds = 180,
97
- retries = 2,
98
- isRefresh = false,
99
- }: SendHttpOptions): Promise<SendHttpResponse> {
100
- const maxRetries = isRefresh ? 0 : retries;
101
- let attempt = 0;
102
-
103
- while (true) {
104
- if (signal?.aborted) {
105
- throw new HttpError('cancelled', 'Request was cancelled by client');
63
+ async function readBody(response: Dispatcher.ResponseData, limit: number): Promise<string> {
64
+ const chunks: Buffer[] = [];
65
+ let bytes = 0;
66
+ try {
67
+ const contentLength = response.headers['content-length'];
68
+ if (Number(contentLength) > limit) {
69
+ throw new HttpError('UPSTREAM_RESPONSE_TOO_LARGE', 'xAI response exceeded the byte limit.', response.statusCode);
106
70
  }
107
-
108
- const timeoutController = new AbortController();
109
- const timeoutId = setTimeout(() => {
110
- timeoutController.abort(new Error('TIMEOUT'));
111
- }, timeoutSeconds * 1000);
112
-
113
- const abortHandler = () => {
114
- timeoutController.abort(new Error('CANCELLED'));
115
- };
116
- signal?.addEventListener('abort', abortHandler, { once: true });
117
-
118
- let response: any;
119
- let responseText = '';
120
- let timedOut = false;
121
- let cancelled = false;
122
-
123
- try {
124
- response = await request(url, {
125
- method: method as any,
126
- headers: {
127
- 'User-Agent': `x-search-mcp/${version}`,
128
- ...headers,
129
- },
130
- body: body as any,
131
- dispatcher: proxyAgent,
132
- signal: timeoutController.signal,
133
- });
134
- // Keep the deadline and client cancellation attached through body consumption.
135
- responseText = await response.body.text();
136
- } catch (err: any) {
137
- if (signal?.aborted || err?.message === 'CANCELLED') {
138
- cancelled = true;
139
- } else if (timeoutController.signal.aborted || err?.name === 'AbortError' || err?.message === 'TIMEOUT') {
140
- timedOut = true;
71
+ for await (const chunk of response.body) {
72
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
73
+ bytes += buffer.length;
74
+ if (bytes > limit) {
75
+ throw new HttpError('UPSTREAM_RESPONSE_TOO_LARGE', 'xAI response exceeded the byte limit.', response.statusCode);
141
76
  }
142
-
143
- clearTimeout(timeoutId);
144
- signal?.removeEventListener('abort', abortHandler);
145
-
146
- if (cancelled) {
147
- throw new HttpError('cancelled', 'Request was cancelled by client');
148
- }
149
-
150
- const isNetworkOrTimeout = timedOut || !err.status;
151
- if (isNetworkOrTimeout && attempt < maxRetries) {
152
- attempt++;
153
- const backoffMs = Math.min(1500 * attempt, 5000);
154
- await sleep(backoffMs, signal);
155
- continue;
156
- }
157
-
158
- if (timedOut) {
159
- throw new HttpError('TIMEOUT', `Request timed out after ${timeoutSeconds} seconds`);
160
- }
161
- throw new HttpError('NETWORK_ERROR', `Network connection error: ${err.message}`);
162
- } finally {
163
- clearTimeout(timeoutId);
164
- signal?.removeEventListener('abort', abortHandler);
165
- }
166
-
167
- const status = response.statusCode;
168
-
169
- // Retry on 5xx errors if remaining retries
170
- if (status >= 500 && status < 600 && attempt < maxRetries) {
171
- attempt++;
172
- const backoffMs = Math.min(1500 * attempt, 5000);
173
- await sleep(backoffMs, signal);
174
- continue;
77
+ chunks.push(buffer);
175
78
  }
79
+ return Buffer.concat(chunks, bytes).toString('utf8');
80
+ } finally {
81
+ response.body.destroy();
82
+ }
83
+ }
176
84
 
177
- let parsedData: any = null;
178
- const contentType = response.headers['content-type'] || '';
179
- if (typeof contentType === 'string' && (contentType.includes('application/json') || responseText.trim().startsWith('{'))) {
180
- try {
181
- parsedData = JSON.parse(responseText);
182
- } catch {
183
- // Fallback to text
184
- }
85
+ /** Send a single HTTP request, consuming at most the configured number of bytes. */
86
+ export async function sendHttpRequest({
87
+ url, method = 'GET', headers = {}, body = null, signal, timeoutMs, maxResponseBytes = maxAuthResponseBytes,
88
+ }: SendHttpOptions): Promise<SendHttpResponse> {
89
+ const timeout = timeoutMs === undefined ? undefined : new AbortController();
90
+ const timer = timeout && setTimeout(
91
+ () => timeout.abort(new HttpError('TIMEOUT', 'The xAI HTTP exchange timed out.')), timeoutMs,
92
+ );
93
+ const requestSignal = signal && timeout ? AbortSignal.any([signal, timeout.signal]) : signal ?? timeout?.signal;
94
+ try {
95
+ if (requestSignal?.aborted) throw abortError(requestSignal);
96
+ const response = await request(url, {
97
+ method, headers: { 'User-Agent': `x-search-mcp/${version}`, ...headers }, body,
98
+ dispatcher: proxyAgent, signal: requestSignal,
99
+ });
100
+ const text = await readBody(response, maxResponseBytes);
101
+ const contentType = response.headers['content-type'];
102
+ let data: unknown = text;
103
+ if (String(contentType ?? '').includes('application/json') || text.trimStart().startsWith('{')) {
104
+ try { data = JSON.parse(text); } catch { /* Keep the bounded body for opt-in diagnostics. */ }
185
105
  }
186
-
187
- if (status >= 400) {
188
- throw createSanitizedHttpError(status, parsedData ?? responseText);
106
+ const status = response.statusCode;
107
+ if (status < 200 || status >= 300) {
108
+ throw httpStatusError(status, data, parseRetryAfter(response.headers['retry-after']));
189
109
  }
190
-
191
- return {
192
- status,
193
- headers: response.headers,
194
- data: parsedData ?? responseText,
195
- };
110
+ return { status, data };
111
+ } catch (error) {
112
+ if (requestSignal?.aborted) throw abortError(requestSignal);
113
+ if (error instanceof HttpError) throw error;
114
+ throw new HttpError('NETWORK_ERROR', 'The connection to xAI ended before a complete response was received.');
115
+ } finally {
116
+ clearTimeout(timer);
196
117
  }
197
118
  }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './types.js';
2
+ export type { SearchSource, XSearchResult } from './tool-contract.js';
2
3
  export * from './config.js';
3
4
  export * from './http.js';
4
5
  export * from './auth.js';
@@ -43,7 +43,7 @@ export async function startMultiUserHttp(options: MultiUserOptions, store: Bindi
43
43
 
44
44
  return startHttp(context => {
45
45
  const user = principalFrom(context.authInfo);
46
- return createManagedSearchServer(async (params, request) => {
46
+ return createManagedSearchServer(async (params, request, trackCleanup) => {
47
47
  if (!user) throw new HttpError('MCP_AUTH_REQUIRED', 'Sign in to this MCP server.', 401);
48
48
  const now = Date.now();
49
49
  const rate = rates.get(user.subject) ?? { starts: [], active: 0 };
@@ -57,6 +57,7 @@ export async function startMultiUserHttp(options: MultiUserOptions, store: Bindi
57
57
  try {
58
58
  return await executeSearch(params, {
59
59
  signal: request.mcpReq.signal,
60
+ trackCleanup,
60
61
  resolveApiKey: async () => {
61
62
  let key: string | null;
62
63
  try { key = await store.get(user); }
@@ -6,7 +6,7 @@ const queryLimit = 16_000;
6
6
  const handleLimit = 10;
7
7
  export const authModeSchema = z.enum(['auto', 'api_key', 'oauth']);
8
8
 
9
- export const managedSearchInputSchema = z.strictObject({
9
+ export const searchInputSchema = z.strictObject({
10
10
  query: z.string().describe('Search query, maximum 16000 characters after trimming'),
11
11
  allowed_x_handles: z.array(z.string()).max(handleLimit).optional()
12
12
  .describe('Only search these X handles, max 10. Mutually exclusive with excluded_x_handles.'),
@@ -16,10 +16,7 @@ export const managedSearchInputSchema = z.strictObject({
16
16
  to_date: z.string().optional().describe('Exclusive end date in YYYY-MM-DD, later than from_date'),
17
17
  enable_image_understanding: z.boolean().optional().describe('Analyze images in matching posts'),
18
18
  enable_video_understanding: z.boolean().optional().describe('Analyze videos in matching posts'),
19
- });
20
-
21
- export const personalSearchInputSchema = managedSearchInputSchema.extend({
22
- auth_mode: authModeSchema.optional().describe('Override the configured credential selection mode'),
19
+ detail: z.enum(['concise', 'detailed']).optional().describe('Concise by default. Use detailed for a longer answer and more evidence.'),
23
20
  });
24
21
 
25
22
  function invalidInput(message: string): HttpError {
@@ -67,9 +64,8 @@ export function validateAndNormalizeHandles(handles: unknown[], fieldName: strin
67
64
  }
68
65
 
69
66
  /** Apply the same search rules before credentials are looked up or xAI is called. */
70
- export function validateSearchParams(rawParams: unknown, { managed = false } = {}): XSearchInput {
71
- const shape = managed ? managedSearchInputSchema : personalSearchInputSchema;
72
- const parsed = shape.safeParse(rawParams);
67
+ export function validateSearchParams(rawParams: unknown): XSearchInput {
68
+ const parsed = searchInputSchema.safeParse(rawParams);
73
69
  if (!parsed.success) {
74
70
  const detail = parsed.error.issues.map(issue =>
75
71
  issue.path.length ? `${issue.path.join('.')}: ${issue.message}` : issue.message).join('; ');
@@ -108,6 +104,6 @@ export function validateSearchParams(rawParams: unknown, { managed = false } = {
108
104
  to_date: to,
109
105
  enable_image_understanding: params.enable_image_understanding,
110
106
  enable_video_understanding: params.enable_video_understanding,
111
- auth_mode: params.auth_mode,
107
+ detail: params.detail ?? 'concise',
112
108
  };
113
109
  }
@@ -1,18 +1,15 @@
1
- import type { InlineCitation, ServerSideCall, XSearchResult } from './types.js';
1
+ import type { SearchSource, XSearchResult } from './tool-contract.js';
2
+ import type { SearchDetail } from './types.js';
2
3
 
3
- const xSearchToolNames = new Set([
4
- 'x_search',
5
- 'x_keyword_search',
6
- 'x_semantic_search',
7
- 'x_user_search',
8
- 'x_thread_fetch',
9
- ]);
10
-
11
- type SearchResponse = Pick<XSearchResult, 'answer' | 'citations' | 'inline_citations' | 'search_execution'
12
- | 'server_side_calls' | 'response_status' | 'incomplete_details' | 'usage'>;
4
+ const xSearchTools = new Set(['x_search', 'x_keyword_search', 'x_semantic_search', 'x_user_search', 'x_thread_fetch']);
5
+ const xHosts = new Set(['x.com', 'www.x.com', 'mobile.x.com', 'twitter.com', 'www.twitter.com', 'mobile.twitter.com']);
6
+ const limits = {
7
+ concise: { answerBytes: 3000, sources: 8 },
8
+ detailed: { answerBytes: 16000, sources: 24 },
9
+ };
13
10
 
14
11
  function record(value: unknown): Record<string, unknown> | undefined {
15
- return value !== null && typeof value === 'object' && !Array.isArray(value)
12
+ return value && typeof value === 'object' && !Array.isArray(value)
16
13
  ? value as Record<string, unknown> : undefined;
17
14
  }
18
15
 
@@ -20,108 +17,106 @@ function text(value: unknown): string {
20
17
  return typeof value === 'string' ? value.trim() : '';
21
18
  }
22
19
 
23
- function citationUrl(value: unknown): string | undefined {
24
- const candidate = text(value);
25
- if (!/^https?:\/\//i.test(candidate) || /[\x00-\x1f\x7f]/.test(candidate)) return undefined;
26
- try {
27
- const url = new URL(candidate);
28
- return url.username || url.password ? undefined : candidate;
29
- } catch {
30
- return undefined;
31
- }
32
- }
33
-
34
- function citationOffset(value: unknown): number | null {
20
+ function count(value: unknown): number | null {
35
21
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
36
22
  }
37
23
 
38
- function inlineCitation(value: unknown): InlineCitation | undefined {
39
- const annotation = record(value);
40
- if (!annotation || (annotation.type !== 'url_citation' && !annotation.url)) return undefined;
41
- const nested = record(annotation.citation);
42
- const url = citationUrl(annotation.url) ?? citationUrl(nested?.url);
43
- if (!url) return undefined;
44
- return {
45
- url,
46
- title: text(annotation.title) || text(nested?.title) || null,
47
- start_index: citationOffset(annotation.start_index),
48
- end_index: citationOffset(annotation.end_index),
49
- };
24
+ function normalizeSource(value: unknown): SearchSource | undefined {
25
+ const candidate = text(value);
26
+ if (candidate.length > 1024 || !/^https?:\/\//i.test(candidate) || /[\x00-\x1f\x7f]/.test(candidate)) return;
27
+ let url: URL;
28
+ try { url = new URL(candidate); } catch { return; }
29
+ if (url.username || url.password) return;
30
+ if (!url.port && xHosts.has(url.hostname)) {
31
+ const match = /^\/([A-Za-z0-9_]{1,15})\/status\/(\d{1,20})(?:\/(?:photo|video)\/\d+)?\/?$/.exec(url.pathname);
32
+ const id = match?.[2] ?? /^\/i\/web\/status\/(\d{1,20})\/?$/.exec(url.pathname)?.[1];
33
+ if (id) {
34
+ const handle = match?.[1].toLowerCase() === 'i' ? undefined : match?.[1];
35
+ return { kind: 'x_post', url: `https://x.com/${handle ?? 'i'}/status/${id}`, post_id: id, ...(handle ? { handle } : {}) };
36
+ }
37
+ }
38
+ url.hash = '';
39
+ if (url.href.length <= 1024) return { kind: 'web', url: url.href };
50
40
  }
51
41
 
52
- function hasXSearchUsage(usage: unknown): boolean {
53
- const details = record(record(usage)?.server_side_tool_usage_details);
54
- return [details?.x_posts_fetched, details?.x_users_fetched].some(
55
- count => typeof count === 'number' && Number.isSafeInteger(count) && count > 0,
56
- );
42
+ function boundedAnswer(answer: string, limit: number): string {
43
+ const bytes = Buffer.from(answer);
44
+ if (bytes.length <= limit) return answer;
45
+ let end = limit;
46
+ while ((bytes[end] & 0xc0) === 0x80) end--;
47
+ return bytes.subarray(0, end).toString('utf8').trimEnd();
57
48
  }
58
49
 
59
- /** Normalize xAI's visible answer, citations and evidence independently of transport and credentials. */
60
- export function normalizeSearchResponse(raw: Record<string, unknown>): SearchResponse {
50
+ /** Project upstream data into bounded answer, checked source links and usage counts. */
51
+ export function normalizeSearchResponse(raw: Record<string, unknown>, detail: SearchDetail) {
61
52
  const canonicalAnswer = text(raw.output_text);
62
- const answerPieces: string[] = [];
63
- const citations = new Set<string>();
64
- const inlineCitations: InlineCitation[] = [];
65
- const serverSideCalls: ServerSideCall[] = [];
66
- let xSearchObserved = hasXSearchUsage(raw.usage);
53
+ const parts: string[] = [];
54
+ const sources = new Map<string, SearchSource>();
55
+ const calls = new Set<string>();
56
+ let callsWithoutId = 0;
67
57
 
68
- for (const sources of [raw.citations, raw.sources]) {
69
- if (!Array.isArray(sources)) continue;
70
- for (const source of sources) {
71
- const url = citationUrl(source);
72
- if (url) citations.add(url);
73
- }
58
+ function addSource(value: unknown, cited = false): void {
59
+ const source = normalizeSource(value);
60
+ if (!source) return;
61
+ const key = source.kind === 'x_post' ? `post:${source.post_id}` : source.url;
62
+ const existing = sources.get(key);
63
+ const preferred = existing?.kind === 'x_post' && existing.handle ? existing : source;
64
+ sources.set(key, { ...preferred, ...(existing?.cited_in_answer || cited ? { cited_in_answer: true as const } : {}) });
65
+ }
66
+
67
+ for (const list of [raw.citations, raw.sources]) {
68
+ if (!Array.isArray(list)) continue;
69
+ for (const entry of list) addSource(record(entry)?.url ?? entry);
74
70
  }
75
71
 
76
- for (const value of Array.isArray(raw.output) ? raw.output : []) {
77
- const item = record(value);
72
+ for (const entry of Array.isArray(raw.output) ? raw.output : []) {
73
+ const item = record(entry);
78
74
  if (!item) continue;
79
75
  const name = text(item.name) || text(item.tool_name);
80
- const callId = text(item.call_id) || text(item.id);
81
- const isXSearch = xSearchToolNames.has(name) || callId.startsWith('xs_');
82
- if (isXSearch) xSearchObserved = true;
83
- if ((isXSearch || item.type === 'custom_tool_call') && (name || callId)) {
84
- serverSideCalls.push({
85
- call_id: callId || null,
86
- name: name || null,
87
- arguments: item.arguments ?? item.input ?? null,
88
- });
89
- }
90
-
91
- if (item.type !== 'message' && item.type !== undefined) continue;
92
- const message = record(item.message) ?? item;
93
- const role = message.role ?? item.role;
94
- if (role !== undefined && role !== 'assistant') continue;
95
- if (typeof message.content === 'string') {
96
- const piece = text(message.content);
97
- if (piece && !canonicalAnswer) answerPieces.push(piece);
98
- continue;
76
+ const id = text(item.call_id) || text(item.id);
77
+ if (xSearchTools.has(name) || id.startsWith('xs_')) {
78
+ if (id) calls.add(id);
79
+ else callsWithoutId++;
99
80
  }
100
- if (!Array.isArray(message.content)) continue;
101
- for (const blockValue of message.content) {
102
- const block = record(blockValue);
103
- if (!block || (block.type !== undefined && block.type !== 'output_text' && block.type !== 'text')) continue;
104
- const piece = text(block.output_text) || text(block.text);
105
- if (piece && !canonicalAnswer) answerPieces.push(piece);
81
+ if (item.type !== 'message' || item.role !== 'assistant' || !Array.isArray(item.content)) continue;
82
+ for (const entry of item.content) {
83
+ const block = record(entry);
84
+ if (block?.type !== 'output_text' || typeof block.text !== 'string') continue;
85
+ if (block.text.trim()) parts.push(block.text.trim());
106
86
  if (!Array.isArray(block.annotations)) continue;
107
- for (const annotation of block.annotations) {
108
- const citation = inlineCitation(annotation);
109
- if (citation) {
110
- inlineCitations.push(citation);
111
- citations.add(citation.url);
112
- }
87
+ for (const value of block.annotations) {
88
+ const annotation = record(value);
89
+ if (annotation?.type !== 'url_citation') continue;
90
+ const start = count(annotation.start_index);
91
+ const end = count(annotation.end_index);
92
+ addSource(annotation.url ?? record(annotation.citation)?.url,
93
+ start !== null && end !== null && start < end && end <= block.text.length);
113
94
  }
114
95
  }
115
96
  }
116
97
 
98
+ const fullAnswer = canonicalAnswer || parts.join('\n\n');
99
+ const limit = limits[detail];
100
+ const answer = boundedAnswer(fullAnswer, limit.answerBytes);
101
+ const ranked = [...sources.values()].sort((a, b) =>
102
+ Number(b.kind === 'x_post') - Number(a.kind === 'x_post')
103
+ || Number(Boolean(b.cited_in_answer)) - Number(Boolean(a.cited_in_answer)));
104
+ const usage = record(raw.usage);
105
+ const tools = record(usage?.server_side_tool_usage_details);
106
+ const status: XSearchResult['status'] = raw.status === 'incomplete' ? 'partial'
107
+ : ranked.some(source => source.kind === 'x_post') ? 'complete' : 'unverified';
108
+
117
109
  return {
118
- answer: canonicalAnswer || answerPieces.join('\n\n'),
119
- citations: [...citations],
120
- inline_citations: inlineCitations,
121
- search_execution: xSearchObserved ? 'observed' : 'unreported',
122
- server_side_calls: serverSideCalls,
123
- response_status: text(raw.status) || 'completed',
124
- incomplete_details: raw.incomplete_details ?? null,
125
- usage: raw.usage ?? null,
110
+ status,
111
+ answer,
112
+ sources: ranked.slice(0, limit.sources),
113
+ truncated: answer !== fullAnswer || ranked.length > limit.sources,
114
+ usage: {
115
+ x_search_calls: (calls.size + callsWithoutId) || null,
116
+ x_posts_fetched: count(tools?.x_posts_fetched),
117
+ x_users_fetched: count(tools?.x_users_fetched),
118
+ input_tokens: count(usage?.input_tokens),
119
+ output_tokens: count(usage?.output_tokens),
120
+ },
126
121
  };
127
122
  }