pi-querit 1.1.1 → 1.2.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/src/client.ts CHANGED
@@ -1,22 +1,56 @@
1
- import { sanitizeTerminalText } from "./sanitize.js";
1
+ import { sanitizeErrorMessage, sanitizeTerminalText } from "./sanitize.js";
2
2
 
3
3
  const SEARCH_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
4
4
  const CONTENTS_RESPONSE_MAX_BYTES = 10 * 1024 * 1024;
5
5
  const ERROR_RESPONSE_MAX_BYTES = 8 * 1024;
6
6
  const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
7
-
8
- export const QUERIT_API_BASE_URL = "https://api.querit.ai";
7
+ /** Querit documents these as the only statuses worth retrying; never 400, 401, 403, or 404. */
8
+ const RETRYABLE_STATUSES = new Set([429, 500, 503]);
9
+
10
+ const QUERIT_API_BASE_URL = "https://api.querit.ai";
11
+ /** Largest `count` the API accepts. */
12
+ export const QUERIT_COUNT_LIMIT = 100;
13
+ /** Inclusive bounds of `highlights.maxCharacters`. */
14
+ export const QUERIT_HIGHLIGHT_MIN_CHARACTERS = 100;
15
+ export const QUERIT_HIGHLIGHT_MAX_CHARACTERS = 8_000;
16
+ /** Largest `contentMaxChars` the API accepts. */
17
+ export const QUERIT_CONTENT_MAX_CHARS_LIMIT = 1_000_000;
18
+ /** The values `filters.vertical` and `rank.preference` accept. */
19
+ export const VERTICAL_VALUES = ["code", "finance"] as const;
20
+ export const RANK_VALUES = ["relevance", "freshness"] as const;
21
+
22
+ export type QueritVertical = (typeof VERTICAL_VALUES)[number];
23
+ export type QueritRankPreference = (typeof RANK_VALUES)[number];
24
+ type QueritResourceTag = "qa" | "github";
25
+
26
+ interface QueritHighlights {
27
+ /** Guides the extraction; Querit falls back to the top-level query when omitted. */
28
+ query?: string;
29
+ maxCharacters?: number;
30
+ }
9
31
 
10
32
  export interface QueritSearchRequest {
11
33
  query: string;
12
- count: number;
34
+ /** Omit to let Querit apply its server default. */
35
+ count?: number;
36
+ /** Deprecated by Querit in favor of `highlights`. Send only when a user explicitly configured it. */
13
37
  chunksPerDoc?: number;
38
+ highlights?: boolean | QueritHighlights;
14
39
  needContent?: boolean;
40
+ /** Body-text limit per result; only meaningful together with `needContent: true`. */
41
+ contentMaxChars?: number;
42
+ /** Enterprise only; ignored by Querit on other plans. */
43
+ needMarkdown?: boolean;
44
+ /** Returns 400 when combined with `filters.vertical: "code"`. */
45
+ rank?: { preference: QueritRankPreference };
15
46
  filters?: {
16
47
  sites?: { include?: string[]; exclude?: string[] };
17
48
  timeRange?: { date: string };
18
49
  geo?: { countries: { include: string[] } };
19
50
  languages?: { include: string[] };
51
+ vertical?: QueritVertical;
52
+ /** Sub-tags of a vertical. Only `qa` and `github`, on the code vertical, are documented. */
53
+ resourceTags?: { include?: QueritResourceTag[] };
20
54
  };
21
55
  }
22
56
 
@@ -25,16 +59,32 @@ export interface QueritContentsRequest {
25
59
  format: "text" | "markdown" | "html";
26
60
  crawlTimeout: number;
27
61
  extrasMeta: boolean;
62
+ /** Content limit per URL. Omit for the full available content. */
63
+ contentMaxChars?: number;
64
+ highlights?: QueritHighlights;
65
+ }
66
+
67
+ interface QueritCost {
68
+ /** Querit always reports "USD". */
69
+ currency: string;
70
+ /** Charge in dollars with up to six decimal places; 0 is a reported zero charge. */
71
+ total: number;
28
72
  }
29
73
 
30
- export interface QueritSearchResult {
74
+ interface QueritSearchResult {
31
75
  title: string;
32
76
  url: string;
33
77
  snippet: string;
34
78
  pageAge?: string;
35
79
  siteName?: string;
36
80
  siteIcon?: string;
81
+ /** Body text, present only when `needContent: true` was requested and is available. */
37
82
  sentences: string[];
83
+ /** Query-focused fragments, present only when `highlights` was requested and is available. */
84
+ highlights: string[];
85
+ /** Markdown versions. Omitted unless `needMarkdown: true` was requested on an Enterprise plan. */
86
+ snippetMarkdown?: string[];
87
+ contentMarkdown?: string;
38
88
  }
39
89
 
40
90
  export interface QueritSearchResponse {
@@ -42,11 +92,13 @@ export interface QueritSearchResponse {
42
92
  errorMessage?: string;
43
93
  searchId?: string;
44
94
  took?: string;
95
+ /** Absent means unavailable, never "free". */
96
+ cost?: QueritCost;
45
97
  query: string;
46
98
  results: QueritSearchResult[];
47
99
  }
48
100
 
49
- export interface QueritContentMetadata {
101
+ interface QueritContentMetadata {
50
102
  title?: string;
51
103
  url?: string;
52
104
  publishTime?: string;
@@ -54,14 +106,15 @@ export interface QueritContentMetadata {
54
106
  siteIcon?: string;
55
107
  }
56
108
 
57
- export interface QueritContentResult {
109
+ interface QueritContentResult {
58
110
  id?: string;
59
111
  url: string;
60
112
  content: string;
113
+ highlights: string[];
61
114
  metadata?: QueritContentMetadata;
62
115
  }
63
116
 
64
- export interface QueritContentStatus {
117
+ interface QueritContentStatus {
65
118
  id?: string;
66
119
  status?: string;
67
120
  }
@@ -70,16 +123,31 @@ export interface QueritContentsResponse {
70
123
  errorCode?: string;
71
124
  errorMessage?: string;
72
125
  searchId?: string;
126
+ searchTime?: number;
127
+ /** Absent means unavailable, never "free". */
128
+ cost?: QueritCost;
73
129
  results: QueritContentResult[];
74
130
  statuses: QueritContentStatus[];
75
- searchTime?: number;
76
131
  }
77
132
 
78
- export interface QueritClientOptions {
133
+ export interface QueritRetryOptions {
134
+ /** Retries after the first attempt. `0` disables retries. */
135
+ maxRetries: number;
136
+ baseDelayMs: number;
137
+ /**
138
+ * Ceiling for backoff waits and for an honored `Retry-After`. A `Retry-After` that
139
+ * exceeds it is not waited out: the tool call fails instead of blocking the agent.
140
+ */
141
+ maxDelayMs: number;
142
+ }
143
+
144
+ interface QueritClientOptions {
79
145
  apiKey: string;
80
146
  fetchImpl?: typeof fetch;
81
147
  baseUrl?: string;
148
+ /** Deadline for the whole operation, retries and backoff waits included. */
82
149
  timeoutMs?: number;
150
+ retry?: Partial<QueritRetryOptions>;
83
151
  }
84
152
 
85
153
  interface ParsedResponse {
@@ -87,15 +155,34 @@ interface ParsedResponse {
87
155
  searchId?: string;
88
156
  }
89
157
 
158
+ /** The signals one operation runs under. */
159
+ interface Operation {
160
+ /** What the request and the backoff waits listen to: the caller's signal and the deadline together. */
161
+ signal: AbortSignal;
162
+ callerSignal?: AbortSignal;
163
+ deadline: AbortSignal;
164
+ }
165
+
166
+ const DEFAULT_RETRY: QueritRetryOptions = { maxRetries: 2, baseDelayMs: 500, maxDelayMs: 5_000 };
167
+
90
168
  export class QueritApiError extends Error {
91
169
  readonly status?: number;
92
170
  readonly searchId?: string;
93
-
94
- constructor(message: string, options: { status?: number; searchId?: string; cause?: unknown } = {}) {
171
+ /** Wait the server asked for through `Retry-After`, when it sent one. */
172
+ readonly retryAfterMs?: number;
173
+ /** Requests sent before giving up, including the first. */
174
+ readonly attempts: number;
175
+
176
+ constructor(
177
+ message: string,
178
+ options: { status?: number; searchId?: string; retryAfterMs?: number; attempts?: number; cause?: unknown } = {},
179
+ ) {
95
180
  super(message, options.cause === undefined ? undefined : { cause: options.cause });
96
181
  this.name = "QueritApiError";
97
182
  this.status = options.status;
98
183
  this.searchId = options.searchId;
184
+ this.retryAfterMs = options.retryAfterMs;
185
+ this.attempts = options.attempts ?? 1;
99
186
  }
100
187
  }
101
188
 
@@ -104,6 +191,7 @@ export class QueritClient {
104
191
  private readonly fetchImpl: typeof fetch;
105
192
  private readonly baseUrl: string;
106
193
  private readonly timeoutMs: number;
194
+ private readonly retry: QueritRetryOptions;
107
195
 
108
196
  constructor(options: QueritClientOptions) {
109
197
  const apiKey = options.apiKey.trim();
@@ -115,6 +203,7 @@ export class QueritClient {
115
203
  this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
116
204
  this.baseUrl = (options.baseUrl ?? QUERIT_API_BASE_URL).replace(/\/+$/, "");
117
205
  this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
206
+ this.retry = { ...DEFAULT_RETRY, ...options.retry };
118
207
  }
119
208
 
120
209
  async search(request: QueritSearchRequest, signal?: AbortSignal): Promise<QueritSearchResponse> {
@@ -127,14 +216,61 @@ export class QueritClient {
127
216
  return normalizeContentsResponse(response.body, response.searchId);
128
217
  }
129
218
 
219
+ /**
220
+ * Posts the request, retrying the statuses Querit calls transient with bounded
221
+ * exponential backoff and jitter. One deadline covers every attempt and wait.
222
+ */
130
223
  private async postJson(
131
224
  path: string,
132
225
  requestBody: QueritSearchRequest | QueritContentsRequest,
133
226
  responseLimit: number,
134
227
  callerSignal?: AbortSignal,
135
228
  ): Promise<ParsedResponse> {
136
- const timeoutSignal = AbortSignal.timeout(this.timeoutMs);
137
- const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
229
+ const deadline = AbortSignal.timeout(this.timeoutMs);
230
+ const operation: Operation = {
231
+ deadline,
232
+ callerSignal,
233
+ signal: callerSignal ? AbortSignal.any([callerSignal, deadline]) : deadline,
234
+ };
235
+
236
+ for (let attempt = 0; ; attempt++) {
237
+ let failure: QueritApiError;
238
+ try {
239
+ return await this.attempt(path, requestBody, responseLimit, operation);
240
+ } catch (error) {
241
+ failure = error instanceof QueritApiError
242
+ ? error
243
+ : new QueritApiError(sanitizeErrorMessage(error), { cause: error });
244
+ }
245
+
246
+ // Cancellations and timeouts are reported as-is: they are not transient server states.
247
+ const retryable = RETRYABLE_STATUSES.has(failure.status ?? 0);
248
+ if (!retryable || attempt >= this.retry.maxRetries) throw withAttempts(failure, attempt + 1);
249
+
250
+ const waitMs = retryDelayMs(failure.retryAfterMs, attempt, this.retry);
251
+ if (waitMs === undefined) {
252
+ // Honor an over-long Retry-After by not retrying sooner.
253
+ throw withAttempts(new QueritApiError(
254
+ `${failure.message} Querit asked to retry after ${Math.ceil((failure.retryAfterMs ?? 0) / 1_000)}s, `
255
+ + `longer than the ${this.retry.maxDelayMs} ms this client waits; not retried.`,
256
+ { status: failure.status, searchId: failure.searchId, retryAfterMs: failure.retryAfterMs, cause: failure },
257
+ ), attempt + 1);
258
+ }
259
+
260
+ try {
261
+ await sleep(waitMs, operation.signal);
262
+ } catch (cancelled) {
263
+ throw interrupted(cancelled, operation, this.timeoutMs, sanitizeErrorMessage(cancelled));
264
+ }
265
+ }
266
+ }
267
+
268
+ private async attempt(
269
+ path: string,
270
+ requestBody: QueritSearchRequest | QueritContentsRequest,
271
+ responseLimit: number,
272
+ operation: Operation,
273
+ ): Promise<ParsedResponse> {
138
274
  let response: Response;
139
275
 
140
276
  try {
@@ -146,16 +282,10 @@ export class QueritClient {
146
282
  "Content-Type": "application/json",
147
283
  },
148
284
  body: JSON.stringify(requestBody),
149
- signal,
285
+ signal: operation.signal,
150
286
  });
151
287
  } catch (error) {
152
- if (callerSignal?.aborted) {
153
- throw new QueritApiError("Querit request was cancelled.", { cause: error });
154
- }
155
- if (timeoutSignal.aborted) {
156
- throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, { cause: error });
157
- }
158
- throw new QueritApiError(`Querit request failed: ${errorMessage(error)}`, { cause: error });
288
+ throw interrupted(error, operation, this.timeoutMs, `Querit request failed: ${sanitizeErrorMessage(error)}`);
159
289
  }
160
290
 
161
291
  const bodyLimit = response.ok ? responseLimit : ERROR_RESPONSE_MAX_BYTES;
@@ -163,19 +293,13 @@ export class QueritClient {
163
293
  try {
164
294
  text = await readResponseText(response, bodyLimit);
165
295
  } catch (error) {
166
- if (callerSignal?.aborted) {
167
- throw new QueritApiError("Querit request was cancelled.", { status: response.status, cause: error });
168
- }
169
- if (timeoutSignal.aborted) {
170
- throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, {
171
- status: response.status,
172
- cause: error,
173
- });
174
- }
175
- throw new QueritApiError(`Could not read the Querit response: ${errorMessage(error)}`, {
176
- status: response.status,
177
- cause: error,
178
- });
296
+ throw interrupted(
297
+ error,
298
+ operation,
299
+ this.timeoutMs,
300
+ `Could not read the Querit response: ${sanitizeErrorMessage(error)}`,
301
+ response.status,
302
+ );
179
303
  }
180
304
 
181
305
  const searchId = extractSearchId(text);
@@ -185,9 +309,12 @@ export class QueritClient {
185
309
  } catch (error) {
186
310
  const excerpt = redactSecret(text.slice(0, 500), this.apiKey);
187
311
  if (!response.ok) {
188
- throw new QueritApiError(
312
+ throw this.apiError(
189
313
  `Querit API request failed with HTTP ${response.status}${excerpt ? `: ${excerpt}` : "."}`,
190
- { status: response.status, searchId, cause: error },
314
+ response,
315
+ response.status,
316
+ searchId,
317
+ error,
191
318
  );
192
319
  }
193
320
  throw new QueritApiError(
@@ -206,16 +333,112 @@ export class QueritClient {
206
333
  const apiErrorCode = optionalString(payload.error_code);
207
334
  const apiErrorMessage = optionalString(payload.error_msg);
208
335
  const numericErrorCode = apiErrorCode === undefined ? undefined : Number(apiErrorCode);
336
+ // Querit asks clients to check error_code even on an HTTP 200.
209
337
  if (!response.ok || (Number.isFinite(numericErrorCode) && numericErrorCode !== 200)) {
210
- const message = redactSecret(
211
- apiErrorMessage ?? `Querit API request failed with HTTP ${response.status}.`,
212
- this.apiKey,
338
+ // error_code is the request's own verdict; the HTTP status stands in when the body has none.
339
+ const status = response.ok ? (numericErrorCode ?? response.status) : response.status;
340
+ throw this.apiError(
341
+ redactSecret(apiErrorMessage ?? `Querit API request failed with HTTP ${response.status}.`, this.apiKey),
342
+ response,
343
+ status,
344
+ searchId,
213
345
  );
214
- throw new QueritApiError(message, { status: response.status, searchId });
215
346
  }
216
347
 
217
348
  return { body: payload, searchId };
218
349
  }
350
+
351
+ /**
352
+ * Marks an API failure with its status and Retry-After so postJson can decide whether to
353
+ * retry, and puts search_id in the message: support needs it to trace the request.
354
+ */
355
+ private apiError(
356
+ message: string,
357
+ response: Response,
358
+ status: number,
359
+ searchId: string | undefined,
360
+ cause?: unknown,
361
+ ): QueritApiError {
362
+ const traced = searchId ? `${message} [search_id: ${searchId}]` : message;
363
+ return new QueritApiError(traced, {
364
+ status,
365
+ searchId,
366
+ retryAfterMs: parseRetryAfter(response.headers.get("retry-after")),
367
+ cause,
368
+ });
369
+ }
370
+ }
371
+
372
+ /** Says how many requests a final failure took, when the first one was retried. */
373
+ function withAttempts(failure: QueritApiError, attempts: number): QueritApiError {
374
+ if (attempts <= 1) return failure;
375
+ return new QueritApiError(`Querit request failed after ${attempts} attempts: ${failure.message}`, {
376
+ status: failure.status,
377
+ searchId: failure.searchId,
378
+ retryAfterMs: failure.retryAfterMs,
379
+ attempts,
380
+ cause: failure,
381
+ });
382
+ }
383
+
384
+ /**
385
+ * Says when the caller cancelled or the deadline passed — neither is a transient
386
+ * server state, so neither is retried — and otherwise reports `failure`.
387
+ * `status` is the HTTP status, when a response had already arrived.
388
+ */
389
+ function interrupted(
390
+ error: unknown,
391
+ operation: Operation,
392
+ timeoutMs: number,
393
+ failure: string,
394
+ status?: number,
395
+ ): QueritApiError {
396
+ if (operation.callerSignal?.aborted) {
397
+ return new QueritApiError("Querit request was cancelled.", { status, cause: error });
398
+ }
399
+ if (operation.deadline.aborted) {
400
+ return new QueritApiError(`Querit request timed out after ${timeoutMs} ms.`, { status, cause: error });
401
+ }
402
+ return new QueritApiError(failure, { status, cause: error });
403
+ }
404
+
405
+ function retryDelayMs(retryAfterMs: number | undefined, attempt: number, retry: QueritRetryOptions): number | undefined {
406
+ if (retryAfterMs !== undefined) {
407
+ return retryAfterMs <= retry.maxDelayMs ? retryAfterMs : undefined;
408
+ }
409
+ // Equal jitter: half the ceiling plus a random half, so waits back off without clustering.
410
+ const ceiling = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** attempt);
411
+ return Math.round(ceiling / 2 + Math.random() * (ceiling / 2));
412
+ }
413
+
414
+ /** Parses `Retry-After` in both forms the HTTP spec allows: delay-seconds or an HTTP-date. */
415
+ export function parseRetryAfter(value: string | null, now = Date.now()): number | undefined {
416
+ if (value === null) return undefined;
417
+ const trimmed = value.trim();
418
+ if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
419
+ return Math.max(0, Math.ceil(Number(trimmed) * 1_000));
420
+ }
421
+ const date = Date.parse(trimmed);
422
+ if (!Number.isFinite(date)) return undefined;
423
+ return Math.max(0, date - now);
424
+ }
425
+
426
+ function sleep(ms: number, signal: AbortSignal): Promise<void> {
427
+ return new Promise((resolve, reject) => {
428
+ if (signal.aborted) {
429
+ reject(signal.reason);
430
+ return;
431
+ }
432
+ const onAbort = () => {
433
+ clearTimeout(timer);
434
+ reject(signal.reason);
435
+ };
436
+ const timer = setTimeout(() => {
437
+ signal.removeEventListener("abort", onAbort);
438
+ resolve();
439
+ }, ms);
440
+ signal.addEventListener("abort", onAbort, { once: true });
441
+ });
219
442
  }
220
443
 
221
444
  async function readResponseText(response: Response, maxBytes: number): Promise<string> {
@@ -268,6 +491,7 @@ function normalizeSearchResponse(
268
491
  for (const rawItem of resultsContainer.result) {
269
492
  if (!isRecord(rawItem)) continue;
270
493
  const url = normalizeHttpUrl(rawItem.url);
494
+ // Every result field is optional; a result without a usable URL cannot be cited.
271
495
  if (!url || deduplicated.has(url)) continue;
272
496
 
273
497
  deduplicated.set(url, {
@@ -277,9 +501,10 @@ function normalizeSearchResponse(
277
501
  pageAge: optionalString(rawItem.page_age),
278
502
  siteName: optionalString(rawItem.site_name),
279
503
  siteIcon: optionalString(rawItem.site_icon),
280
- sentences: Array.isArray(rawItem.sentence)
281
- ? rawItem.sentence.filter((value): value is string => typeof value === "string")
282
- : [],
504
+ sentences: stringList(rawItem.sentence),
505
+ highlights: stringList(rawItem.highlights),
506
+ snippetMarkdown: optionalStringList(rawItem.snippet_markdown),
507
+ contentMarkdown: optionalString(rawItem.content_markdown),
283
508
  });
284
509
  }
285
510
 
@@ -289,6 +514,7 @@ function normalizeSearchResponse(
289
514
  errorMessage: optionalString(payload.error_msg),
290
515
  searchId,
291
516
  took: optionalString(payload.took),
517
+ cost: normalizeCost(payload.cost),
292
518
  query: queryContext ? optionalString(queryContext.query) ?? requestedQuery : requestedQuery,
293
519
  results: [...deduplicated.values()],
294
520
  };
@@ -323,6 +549,7 @@ function normalizeContentsResponse(
323
549
  id: optionalString(rawResult.id),
324
550
  url,
325
551
  content: optionalString(rawResult.content) ?? "",
552
+ highlights: stringList(rawResult.highlights),
326
553
  metadata,
327
554
  });
328
555
  }
@@ -338,12 +565,26 @@ function normalizeContentsResponse(
338
565
  errorCode: optionalString(payload.error_code),
339
566
  errorMessage: optionalString(payload.error_msg),
340
567
  searchId,
568
+ searchTime: optionalNumber(payload.searchTime),
569
+ cost: normalizeCost(payload.cost),
341
570
  results: [...deduplicated.values()],
342
571
  statuses,
343
- searchTime: optionalNumber(payload.searchTime),
344
572
  };
345
573
  }
346
574
 
575
+ /** Reads `cost`, keeping Querit's "absent means unavailable" distinct from a reported zero. */
576
+ function normalizeCost(value: unknown): QueritCost | undefined {
577
+ if (!isRecord(value) || typeof value.currency !== "string") return undefined;
578
+ const total = optionalNumber(value.total);
579
+ if (total === undefined || total < 0) return undefined;
580
+ return { currency: value.currency, total };
581
+ }
582
+
583
+ /** Renders a cost at the API's six-decimal precision so small charges stay visible. */
584
+ export function formatCost(cost: QueritCost): string {
585
+ return `${cost.currency} ${cost.total.toFixed(6)}`;
586
+ }
587
+
347
588
  function extractSearchId(text: string): string | undefined {
348
589
  const match = /"search_id"\s*:\s*(?:"([^"]+)"|(-?\d+))/.exec(text);
349
590
  const value = match?.[1] ?? match?.[2];
@@ -376,10 +617,16 @@ function optionalNumber(value: unknown): number | undefined {
376
617
  return typeof value === "number" && Number.isFinite(value) ? value : undefined;
377
618
  }
378
619
 
379
- function isRecord(value: unknown): value is Record<string, unknown> {
380
- return typeof value === "object" && value !== null && !Array.isArray(value);
620
+ /** Reads an optional string array, dropping anything that is not a string. */
621
+ function stringList(value: unknown): string[] {
622
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
381
623
  }
382
624
 
383
- function errorMessage(error: unknown): string {
384
- return sanitizeTerminalText(error instanceof Error ? error.message : String(error));
625
+ /** Like stringList, but keeps "the API omitted this field" distinct from an empty list. */
626
+ function optionalStringList(value: unknown): string[] | undefined {
627
+ return Array.isArray(value) ? stringList(value) : undefined;
628
+ }
629
+
630
+ function isRecord(value: unknown): value is Record<string, unknown> {
631
+ return typeof value === "object" && value !== null && !Array.isArray(value);
385
632
  }
package/src/config.ts CHANGED
@@ -1,8 +1,15 @@
1
1
  import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
2
  import { dirname, join } from "node:path";
3
3
  import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
4
+ import {
5
+ QUERIT_CONTENT_MAX_CHARS_LIMIT,
6
+ QUERIT_COUNT_LIMIT,
7
+ RANK_VALUES,
8
+ type QueritRankPreference,
9
+ } from "./client.js";
10
+ import { sanitizeErrorMessage } from "./sanitize.js";
4
11
 
5
- export const QUERIT_CONFIG_FILE = "querit-search.json";
12
+ const QUERIT_CONFIG_FILE = "querit-search.json";
6
13
 
7
14
  export const COUNTRY_VALUES = [
8
15
  "argentina",
@@ -32,12 +39,14 @@ export const LANGUAGE_VALUES = [
32
39
  "french",
33
40
  "spanish",
34
41
  "portuguese",
42
+ "russian",
35
43
  ] as const;
36
44
 
37
45
  export type QueritCountry = (typeof COUNTRY_VALUES)[number];
38
46
  export type QueritLanguage = (typeof LANGUAGE_VALUES)[number];
39
47
 
40
48
  export interface QueritSearchDefaults {
49
+ /** Omit to let Querit apply its server default. */
41
50
  count?: number;
42
51
  includeDomains?: string[];
43
52
  excludeDomains?: string[];
@@ -45,7 +54,16 @@ export interface QueritSearchDefaults {
45
54
  countries?: QueritCountry[];
46
55
  languages?: QueritLanguage[];
47
56
  includeContent?: boolean;
57
+ /** Body-text budget per result, in Unicode code points. Only applies with `includeContent`. */
58
+ contentMaxChars?: number;
59
+ /** Ask for query-focused fragments instead of, or in addition to, whole body text. */
60
+ highlights?: boolean;
61
+ /** Enterprise plans only; Querit ignores it elsewhere. */
62
+ needMarkdown?: boolean;
63
+ /** Deprecated by Querit. Kept so existing configurations keep working; prefer `highlights`. */
48
64
  chunksPerDoc?: number;
65
+ /** A nudge on top of the default ranking. Dropped for code-vertical searches, which reject it. */
66
+ rank?: QueritRankPreference;
49
67
  }
50
68
 
51
69
  export interface QueritConfig {
@@ -57,7 +75,7 @@ export interface QueritConfigSettings {
57
75
  search?: QueritSearchDefaults;
58
76
  }
59
77
 
60
- export interface ApiKeyResolutionOptions {
78
+ interface ApiKeyResolutionOptions {
61
79
  configPath?: string;
62
80
  env?: NodeJS.ProcessEnv;
63
81
  }
@@ -72,7 +90,7 @@ export async function loadQueritConfig(configPath = getQueritConfigPath()): Prom
72
90
  text = await readFile(configPath, "utf8");
73
91
  } catch (error) {
74
92
  if (isNodeError(error) && error.code === "ENOENT") return undefined;
75
- throw new Error(`Could not read Querit configuration at ${configPath}: ${errorMessage(error)}`, {
93
+ throw new Error(`Could not read Querit configuration at ${configPath}: ${sanitizeErrorMessage(error)}`, {
76
94
  cause: error,
77
95
  });
78
96
  }
@@ -135,13 +153,21 @@ export async function saveQueritConfig(
135
153
  });
136
154
  }
137
155
 
138
- export function parseSearchDefaults(value: unknown): QueritSearchDefaults | undefined {
156
+ function parseSearchDefaults(value: unknown): QueritSearchDefaults | undefined {
139
157
  if (!isRecord(value)) return undefined;
140
158
  const defaults: QueritSearchDefaults = {};
141
159
 
142
- if (isIntegerInRange(value.count, 1, 20)) defaults.count = value.count;
160
+ if (isIntegerInRange(value.count, 1, QUERIT_COUNT_LIMIT)) defaults.count = value.count;
143
161
  if (isIntegerInRange(value.chunksPerDoc, 1, 3)) defaults.chunksPerDoc = value.chunksPerDoc;
144
162
  if (typeof value.includeContent === "boolean") defaults.includeContent = value.includeContent;
163
+ if (isIntegerInRange(value.contentMaxChars, 1, QUERIT_CONTENT_MAX_CHARS_LIMIT)) {
164
+ defaults.contentMaxChars = value.contentMaxChars;
165
+ }
166
+ if (typeof value.highlights === "boolean") defaults.highlights = value.highlights;
167
+ if (typeof value.needMarkdown === "boolean") defaults.needMarkdown = value.needMarkdown;
168
+ if (typeof value.rank === "string" && (RANK_VALUES as readonly string[]).includes(value.rank)) {
169
+ defaults.rank = value.rank as QueritRankPreference;
170
+ }
145
171
  if (typeof value.timeRange === "string" && value.timeRange.trim()) {
146
172
  defaults.timeRange = value.timeRange.trim().slice(0, 64);
147
173
  }
@@ -194,7 +220,3 @@ function isRecord(value: unknown): value is Record<string, unknown> {
194
220
  function isNodeError(error: unknown): error is NodeJS.ErrnoException {
195
221
  return error instanceof Error && "code" in error;
196
222
  }
197
-
198
- function errorMessage(error: unknown): string {
199
- return error instanceof Error ? error.message : String(error);
200
- }