opencode-querit 1.0.2 → 3.0.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 +81 -46
- package/lib/client.d.ts +102 -7
- package/lib/client.js +234 -51
- package/lib/config.d.ts +37 -37
- package/lib/config.js +61 -62
- package/lib/format.d.ts +3 -5
- package/lib/format.js +25 -32
- package/lib/index.d.ts +75 -10
- package/lib/index.js +218 -143
- package/lib/sanitize.d.ts +2 -0
- package/lib/sanitize.js +4 -0
- package/package.json +12 -4
package/lib/client.js
CHANGED
|
@@ -2,24 +2,79 @@
|
|
|
2
2
|
* Credential-safe client for the public Querit API
|
|
3
3
|
* (`POST https://api.querit.ai/v1/search` and `/v1/contents`).
|
|
4
4
|
* Structure follows the client shipped by pi-querit / dsh-querit (MIT):
|
|
5
|
-
* response-size limits, deduplication, URL normalization,
|
|
6
|
-
* redaction from every error
|
|
5
|
+
* response-size limits, deduplication, URL normalization, bounded retries for
|
|
6
|
+
* the statuses Querit calls transient, and API-key redaction from every error
|
|
7
|
+
* surface.
|
|
7
8
|
* @module opencode-querit/client
|
|
8
9
|
*/
|
|
9
|
-
import { sanitizeUntrustedText } from "./sanitize.js";
|
|
10
|
-
export const QUERIT_API_BASE_URL = "https://api.querit.ai";
|
|
11
|
-
export const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
|
|
10
|
+
import { sanitizeErrorMessage, sanitizeUntrustedText } from "./sanitize.js";
|
|
12
11
|
const SEARCH_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
13
12
|
const CONTENTS_RESPONSE_MAX_BYTES = 10 * 1024 * 1024;
|
|
14
13
|
const ERROR_RESPONSE_MAX_BYTES = 8 * 1024;
|
|
14
|
+
/** Querit documents these as the only statuses worth retrying; never 400, 401, 403, or 404. */
|
|
15
|
+
const RETRYABLE_STATUSES = new Set([429, 500, 503]);
|
|
16
|
+
export const QUERIT_API_BASE_URL = "https://api.querit.ai";
|
|
17
|
+
export const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
|
|
18
|
+
/** Largest `count` the API accepts. */
|
|
19
|
+
export const QUERIT_COUNT_LIMIT = 100;
|
|
20
|
+
/** Inclusive bounds of `highlights.maxCharacters`. */
|
|
21
|
+
export const QUERIT_HIGHLIGHT_MIN_CHARACTERS = 100;
|
|
22
|
+
export const QUERIT_HIGHLIGHT_MAX_CHARACTERS = 8_000;
|
|
23
|
+
/** Largest `contentMaxChars` the API accepts. */
|
|
24
|
+
export const QUERIT_CONTENT_MAX_CHARS_LIMIT = 1_000_000;
|
|
25
|
+
/** Most URLs one /v1/contents request accepts. */
|
|
26
|
+
export const QUERIT_URLS_LIMIT = 10;
|
|
27
|
+
/** Inclusive bounds of `crawlTimeout`, in seconds. */
|
|
28
|
+
export const QUERIT_CRAWL_TIMEOUT_MIN_SECONDS = 1;
|
|
29
|
+
export const QUERIT_CRAWL_TIMEOUT_MAX_SECONDS = 60;
|
|
30
|
+
export const FETCH_FORMAT_VALUES = ["text", "markdown", "html"];
|
|
31
|
+
export const VERTICAL_VALUES = ["code", "finance"];
|
|
32
|
+
export const RANK_VALUES = ["relevance", "freshness"];
|
|
33
|
+
export const RESOURCE_TAG_VALUES = ["qa", "github"];
|
|
34
|
+
export const COUNTRY_VALUES = [
|
|
35
|
+
"argentina",
|
|
36
|
+
"australia",
|
|
37
|
+
"brazil",
|
|
38
|
+
"canada",
|
|
39
|
+
"colombia",
|
|
40
|
+
"france",
|
|
41
|
+
"germany",
|
|
42
|
+
"india",
|
|
43
|
+
"indonesia",
|
|
44
|
+
"japan",
|
|
45
|
+
"mexico",
|
|
46
|
+
"nigeria",
|
|
47
|
+
"philippines",
|
|
48
|
+
"south korea",
|
|
49
|
+
"spain",
|
|
50
|
+
"united kingdom",
|
|
51
|
+
"united states",
|
|
52
|
+
];
|
|
53
|
+
export const LANGUAGE_VALUES = [
|
|
54
|
+
"english",
|
|
55
|
+
"japanese",
|
|
56
|
+
"korean",
|
|
57
|
+
"german",
|
|
58
|
+
"french",
|
|
59
|
+
"spanish",
|
|
60
|
+
"portuguese",
|
|
61
|
+
"russian",
|
|
62
|
+
];
|
|
63
|
+
const DEFAULT_RETRY = { maxRetries: 2, baseDelayMs: 500, maxDelayMs: 5_000 };
|
|
15
64
|
export class QueritApiError extends Error {
|
|
16
65
|
status;
|
|
17
66
|
searchId;
|
|
67
|
+
/** Wait the server asked for through `Retry-After`, when it sent one. */
|
|
68
|
+
retryAfterMs;
|
|
69
|
+
/** Requests sent before giving up, including the first. */
|
|
70
|
+
attempts;
|
|
18
71
|
constructor(message, options = {}) {
|
|
19
72
|
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
20
73
|
this.name = "QueritApiError";
|
|
21
74
|
this.status = options.status;
|
|
22
75
|
this.searchId = options.searchId;
|
|
76
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
77
|
+
this.attempts = options.attempts ?? 1;
|
|
23
78
|
}
|
|
24
79
|
}
|
|
25
80
|
export class QueritClient {
|
|
@@ -27,6 +82,7 @@ export class QueritClient {
|
|
|
27
82
|
fetchImpl;
|
|
28
83
|
baseUrl;
|
|
29
84
|
timeoutMs;
|
|
85
|
+
retry;
|
|
30
86
|
constructor(options) {
|
|
31
87
|
const apiKey = options.apiKey.trim();
|
|
32
88
|
if (!apiKey) {
|
|
@@ -36,6 +92,7 @@ export class QueritClient {
|
|
|
36
92
|
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
37
93
|
this.baseUrl = (options.baseUrl ?? QUERIT_API_BASE_URL).replace(/\/+$/, "");
|
|
38
94
|
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
95
|
+
this.retry = { ...DEFAULT_RETRY, ...options.retry };
|
|
39
96
|
}
|
|
40
97
|
async search(request, signal) {
|
|
41
98
|
const response = await this.postJson("/v1/search", request, SEARCH_RESPONSE_MAX_BYTES, signal);
|
|
@@ -45,9 +102,45 @@ export class QueritClient {
|
|
|
45
102
|
const response = await this.postJson("/v1/contents", request, CONTENTS_RESPONSE_MAX_BYTES, signal);
|
|
46
103
|
return normalizeContentsResponse(response.body, response.searchId);
|
|
47
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* Posts the request, retrying the statuses Querit calls transient with bounded
|
|
107
|
+
* exponential backoff and jitter. One deadline covers every attempt and wait.
|
|
108
|
+
*/
|
|
48
109
|
async postJson(path, requestBody, responseLimit, callerSignal) {
|
|
49
|
-
const
|
|
50
|
-
const signal = callerSignal ? AbortSignal.any([callerSignal,
|
|
110
|
+
const deadline = AbortSignal.timeout(this.timeoutMs);
|
|
111
|
+
const signal = callerSignal ? AbortSignal.any([callerSignal, deadline]) : deadline;
|
|
112
|
+
const operation = { signal, callerSignal, deadline, timeoutMs: this.timeoutMs };
|
|
113
|
+
for (let attempt = 0;; attempt++) {
|
|
114
|
+
let failure;
|
|
115
|
+
try {
|
|
116
|
+
return await this.attempt(path, requestBody, responseLimit, operation);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
failure = error instanceof QueritApiError
|
|
120
|
+
? error
|
|
121
|
+
: new QueritApiError(sanitizeErrorMessage(error), { cause: error });
|
|
122
|
+
}
|
|
123
|
+
// A cancelled or timed-out operation is reported as such: it is not a transient server state.
|
|
124
|
+
if (signal.aborted)
|
|
125
|
+
throw interrupted(failure, operation, () => failure, failure.status);
|
|
126
|
+
if (!RETRYABLE_STATUSES.has(failure.status ?? 0) || attempt >= this.retry.maxRetries) {
|
|
127
|
+
throw withAttempts(failure, attempt + 1);
|
|
128
|
+
}
|
|
129
|
+
const waitMs = retryDelayMs(failure.retryAfterMs, attempt, this.retry);
|
|
130
|
+
if (waitMs === undefined) {
|
|
131
|
+
// Honor an over-long Retry-After by not retrying sooner.
|
|
132
|
+
throw withAttempts(new QueritApiError(`${failure.message} Querit asked to retry after ${Math.ceil((failure.retryAfterMs ?? 0) / 1_000)}s, `
|
|
133
|
+
+ `longer than the ${this.retry.maxDelayMs} ms this client waits; not retried.`, { status: failure.status, searchId: failure.searchId, retryAfterMs: failure.retryAfterMs, cause: failure }), attempt + 1);
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
await sleep(waitMs, signal);
|
|
137
|
+
}
|
|
138
|
+
catch (cancelled) {
|
|
139
|
+
throw interrupted(cancelled, operation, (cause) => new QueritApiError(sanitizeErrorMessage(cause), { cause }));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
async attempt(path, requestBody, responseLimit, operation) {
|
|
51
144
|
let response;
|
|
52
145
|
try {
|
|
53
146
|
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
@@ -58,17 +151,11 @@ export class QueritClient {
|
|
|
58
151
|
"Content-Type": "application/json",
|
|
59
152
|
},
|
|
60
153
|
body: JSON.stringify(requestBody),
|
|
61
|
-
signal,
|
|
154
|
+
signal: operation.signal,
|
|
62
155
|
});
|
|
63
156
|
}
|
|
64
157
|
catch (error) {
|
|
65
|
-
|
|
66
|
-
throw new QueritApiError("Querit request was cancelled.", { cause: error });
|
|
67
|
-
}
|
|
68
|
-
if (timeoutSignal.aborted) {
|
|
69
|
-
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, { cause: error });
|
|
70
|
-
}
|
|
71
|
-
throw new QueritApiError(`Querit request failed: ${errorMessage(error)}`, { cause: error });
|
|
158
|
+
throw interrupted(error, operation, transportFailure("Querit request failed"));
|
|
72
159
|
}
|
|
73
160
|
const bodyLimit = response.ok ? responseLimit : ERROR_RESPONSE_MAX_BYTES;
|
|
74
161
|
let text;
|
|
@@ -76,19 +163,7 @@ export class QueritClient {
|
|
|
76
163
|
text = await readResponseText(response, bodyLimit);
|
|
77
164
|
}
|
|
78
165
|
catch (error) {
|
|
79
|
-
|
|
80
|
-
throw new QueritApiError("Querit request was cancelled.", { status: response.status, cause: error });
|
|
81
|
-
}
|
|
82
|
-
if (timeoutSignal.aborted) {
|
|
83
|
-
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, {
|
|
84
|
-
status: response.status,
|
|
85
|
-
cause: error,
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
throw new QueritApiError(`Could not read the Querit response: ${errorMessage(error)}`, {
|
|
89
|
-
status: response.status,
|
|
90
|
-
cause: error,
|
|
91
|
-
});
|
|
166
|
+
throw interrupted(error, operation, transportFailure("Could not read the Querit response"), response.status);
|
|
92
167
|
}
|
|
93
168
|
const searchId = extractSearchId(text);
|
|
94
169
|
let payload;
|
|
@@ -97,27 +172,104 @@ export class QueritClient {
|
|
|
97
172
|
}
|
|
98
173
|
catch (error) {
|
|
99
174
|
const excerpt = redactSecret(text.slice(0, 500), this.apiKey);
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
throw new QueritApiError(`Querit returned invalid JSON${excerpt ? `: ${excerpt}` : "."}`, { status: response.status, searchId, cause: error });
|
|
175
|
+
throw apiError(!response.ok
|
|
176
|
+
? `Querit API request failed with HTTP ${response.status}${excerpt ? `: ${excerpt}` : "."}`
|
|
177
|
+
: `Querit returned invalid JSON${excerpt ? `: ${excerpt}` : "."}`, response, response.status, searchId, error);
|
|
104
178
|
}
|
|
105
179
|
if (!isRecord(payload)) {
|
|
106
|
-
throw
|
|
107
|
-
status: response.status,
|
|
108
|
-
searchId,
|
|
109
|
-
});
|
|
180
|
+
throw apiError("Querit returned an invalid response object.", response, response.status, searchId);
|
|
110
181
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const
|
|
114
|
-
if (
|
|
115
|
-
|
|
116
|
-
throw new QueritApiError(message, { status: response.status, searchId });
|
|
182
|
+
// Querit asks clients to check error_code even on an HTTP 200: it is the verdict, and on
|
|
183
|
+
// a 200 it is the only thing that names the failure.
|
|
184
|
+
const status = response.ok ? (numericCode(payload.error_code) ?? response.status) : response.status;
|
|
185
|
+
if (status !== 200) {
|
|
186
|
+
throw apiError(redactSecret(optionalString(payload.error_msg) || `Querit API request failed with HTTP ${response.status}.`, this.apiKey), response, status, searchId);
|
|
117
187
|
}
|
|
118
188
|
return { body: payload, searchId };
|
|
119
189
|
}
|
|
120
190
|
}
|
|
191
|
+
/**
|
|
192
|
+
* Marks an API failure with the status that decides retries and the `Retry-After`
|
|
193
|
+
* the server sent.
|
|
194
|
+
*/
|
|
195
|
+
function apiError(message, response, status, searchId, cause) {
|
|
196
|
+
return new QueritApiError(withSearchId(message, searchId), {
|
|
197
|
+
status,
|
|
198
|
+
searchId,
|
|
199
|
+
retryAfterMs: parseRetryAfter(response.headers.get("retry-after")),
|
|
200
|
+
cause,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
/** Puts `search_id` in a failure message: support traces a request with it. */
|
|
204
|
+
function withSearchId(message, searchId) {
|
|
205
|
+
return searchId ? `${message} [search_id: ${searchId}]` : message;
|
|
206
|
+
}
|
|
207
|
+
/** Says how many requests a final failure took, when the first one was retried. */
|
|
208
|
+
function withAttempts(failure, attempts) {
|
|
209
|
+
if (attempts <= 1)
|
|
210
|
+
return failure;
|
|
211
|
+
return new QueritApiError(`Querit request failed after ${attempts} attempts: ${failure.message}`, {
|
|
212
|
+
status: failure.status,
|
|
213
|
+
searchId: failure.searchId,
|
|
214
|
+
retryAfterMs: failure.retryAfterMs,
|
|
215
|
+
attempts,
|
|
216
|
+
cause: failure,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Maps a rejected transport step to the failure the caller sees. A cancellation or
|
|
221
|
+
* timeout is reported as such; anything else becomes whatever `failure` builds.
|
|
222
|
+
*/
|
|
223
|
+
function interrupted(error, operation, failure, status) {
|
|
224
|
+
if (operation.callerSignal?.aborted) {
|
|
225
|
+
return new QueritApiError("Querit request was cancelled.", { status, cause: error });
|
|
226
|
+
}
|
|
227
|
+
if (operation.deadline.aborted) {
|
|
228
|
+
return new QueritApiError(`Querit request timed out after ${operation.timeoutMs} ms.`, { status, cause: error });
|
|
229
|
+
}
|
|
230
|
+
return failure(error);
|
|
231
|
+
}
|
|
232
|
+
function transportFailure(reason, status) {
|
|
233
|
+
return (cause) => new QueritApiError(`${reason}: ${sanitizeErrorMessage(cause)}`, { status, cause });
|
|
234
|
+
}
|
|
235
|
+
function retryDelayMs(retryAfterMs, attempt, retry) {
|
|
236
|
+
if (retryAfterMs !== undefined) {
|
|
237
|
+
return retryAfterMs <= retry.maxDelayMs ? retryAfterMs : undefined;
|
|
238
|
+
}
|
|
239
|
+
// Equal jitter: half the ceiling plus a random half, so waits back off without clustering.
|
|
240
|
+
const ceiling = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** attempt);
|
|
241
|
+
return Math.round(ceiling / 2 + Math.random() * (ceiling / 2));
|
|
242
|
+
}
|
|
243
|
+
/** Parses `Retry-After` in both forms the HTTP spec allows: delay-seconds or an HTTP-date. */
|
|
244
|
+
export function parseRetryAfter(value, now = Date.now()) {
|
|
245
|
+
if (value === null)
|
|
246
|
+
return undefined;
|
|
247
|
+
const trimmed = value.trim();
|
|
248
|
+
if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
|
|
249
|
+
return Math.max(0, Math.ceil(Number(trimmed) * 1_000));
|
|
250
|
+
}
|
|
251
|
+
const date = Date.parse(trimmed);
|
|
252
|
+
if (!Number.isFinite(date))
|
|
253
|
+
return undefined;
|
|
254
|
+
return Math.max(0, date - now);
|
|
255
|
+
}
|
|
256
|
+
function sleep(ms, signal) {
|
|
257
|
+
return new Promise((resolve, reject) => {
|
|
258
|
+
if (signal.aborted) {
|
|
259
|
+
reject(signal.reason);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
const onAbort = () => {
|
|
263
|
+
clearTimeout(timer);
|
|
264
|
+
reject(signal.reason);
|
|
265
|
+
};
|
|
266
|
+
const timer = setTimeout(() => {
|
|
267
|
+
signal.removeEventListener("abort", onAbort);
|
|
268
|
+
resolve();
|
|
269
|
+
}, ms);
|
|
270
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
271
|
+
});
|
|
272
|
+
}
|
|
121
273
|
async function readResponseText(response, maxBytes) {
|
|
122
274
|
const contentLength = response.headers.get("content-length");
|
|
123
275
|
if (contentLength !== null) {
|
|
@@ -155,13 +307,14 @@ async function readResponseText(response, maxBytes) {
|
|
|
155
307
|
function normalizeSearchResponse(payload, searchId, requestedQuery) {
|
|
156
308
|
const resultsContainer = payload.results;
|
|
157
309
|
if (!isRecord(resultsContainer) || !Array.isArray(resultsContainer.result)) {
|
|
158
|
-
throw new QueritApiError("Querit search response is missing results.result.", { searchId });
|
|
310
|
+
throw new QueritApiError(withSearchId("Querit search response is missing results.result.", searchId), { searchId });
|
|
159
311
|
}
|
|
160
312
|
const deduplicated = new Map();
|
|
161
313
|
for (const rawItem of resultsContainer.result) {
|
|
162
314
|
if (!isRecord(rawItem))
|
|
163
315
|
continue;
|
|
164
316
|
const url = normalizeHttpUrl(rawItem.url);
|
|
317
|
+
// Every result field is optional; a result without a usable URL cannot be cited.
|
|
165
318
|
if (!url || deduplicated.has(url))
|
|
166
319
|
continue;
|
|
167
320
|
deduplicated.set(url, {
|
|
@@ -171,22 +324,24 @@ function normalizeSearchResponse(payload, searchId, requestedQuery) {
|
|
|
171
324
|
pageAge: optionalString(rawItem.page_age),
|
|
172
325
|
siteName: optionalString(rawItem.site_name),
|
|
173
326
|
siteIcon: optionalString(rawItem.site_icon),
|
|
174
|
-
sentences:
|
|
175
|
-
|
|
176
|
-
|
|
327
|
+
sentences: stringList(rawItem.sentence),
|
|
328
|
+
highlights: stringList(rawItem.highlights),
|
|
329
|
+
snippetMarkdown: optionalStringList(rawItem.snippet_markdown),
|
|
330
|
+
contentMarkdown: optionalString(rawItem.content_markdown),
|
|
177
331
|
});
|
|
178
332
|
}
|
|
179
333
|
const queryContext = isRecord(payload.query_context) ? payload.query_context : undefined;
|
|
180
334
|
return {
|
|
181
335
|
searchId,
|
|
182
336
|
took: optionalString(payload.took),
|
|
337
|
+
cost: normalizeCost(payload.cost),
|
|
183
338
|
query: queryContext ? optionalString(queryContext.query) ?? requestedQuery : requestedQuery,
|
|
184
339
|
results: [...deduplicated.values()],
|
|
185
340
|
};
|
|
186
341
|
}
|
|
187
342
|
function normalizeContentsResponse(payload, searchId) {
|
|
188
343
|
if (!Array.isArray(payload.results) || !Array.isArray(payload.statuses)) {
|
|
189
|
-
throw new QueritApiError("Querit contents response is missing results or statuses.", { searchId });
|
|
344
|
+
throw new QueritApiError(withSearchId("Querit contents response is missing results or statuses.", searchId), { searchId });
|
|
190
345
|
}
|
|
191
346
|
const deduplicated = new Map();
|
|
192
347
|
for (const rawResult of payload.results) {
|
|
@@ -209,6 +364,7 @@ function normalizeContentsResponse(payload, searchId) {
|
|
|
209
364
|
id: optionalString(rawResult.id),
|
|
210
365
|
url,
|
|
211
366
|
content: optionalString(rawResult.content) ?? "",
|
|
367
|
+
highlights: stringList(rawResult.highlights),
|
|
212
368
|
metadata,
|
|
213
369
|
});
|
|
214
370
|
}
|
|
@@ -220,11 +376,25 @@ function normalizeContentsResponse(payload, searchId) {
|
|
|
220
376
|
}));
|
|
221
377
|
return {
|
|
222
378
|
searchId,
|
|
379
|
+
cost: normalizeCost(payload.cost),
|
|
380
|
+
searchTime: optionalNumber(payload.searchTime),
|
|
223
381
|
results: [...deduplicated.values()],
|
|
224
382
|
statuses,
|
|
225
|
-
searchTime: optionalNumber(payload.searchTime),
|
|
226
383
|
};
|
|
227
384
|
}
|
|
385
|
+
/** Reads `cost`, keeping Querit's "absent means unavailable" distinct from a reported zero. */
|
|
386
|
+
function normalizeCost(value) {
|
|
387
|
+
if (!isRecord(value) || typeof value.currency !== "string")
|
|
388
|
+
return undefined;
|
|
389
|
+
const total = optionalNumber(value.total);
|
|
390
|
+
if (total === undefined || total < 0)
|
|
391
|
+
return undefined;
|
|
392
|
+
return { currency: value.currency, total };
|
|
393
|
+
}
|
|
394
|
+
/** Renders a cost at the API's six-decimal precision so small charges stay visible. */
|
|
395
|
+
export function formatCost(cost) {
|
|
396
|
+
return `${sanitizeUntrustedText(cost.currency).replace(/\s+/g, " ").trim()} ${cost.total.toFixed(6)}`;
|
|
397
|
+
}
|
|
228
398
|
function extractSearchId(text) {
|
|
229
399
|
const match = /"search_id"\s*:\s*(?:"([^"]+)"|(-?\d+))/.exec(text);
|
|
230
400
|
const value = match?.[1] ?? match?.[2];
|
|
@@ -257,9 +427,22 @@ function optionalString(value) {
|
|
|
257
427
|
function optionalNumber(value) {
|
|
258
428
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
259
429
|
}
|
|
430
|
+
/** Reads `error_code`: an integer, which a looser server may send as a numeric string. */
|
|
431
|
+
function numericCode(value) {
|
|
432
|
+
if (typeof value === "number")
|
|
433
|
+
return Number.isFinite(value) ? value : undefined;
|
|
434
|
+
if (typeof value === "string" && /^-?\d+$/u.test(value.trim()))
|
|
435
|
+
return Number(value);
|
|
436
|
+
return undefined;
|
|
437
|
+
}
|
|
438
|
+
/** Reads an optional string array, dropping anything that is not a string. */
|
|
439
|
+
function stringList(value) {
|
|
440
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
441
|
+
}
|
|
442
|
+
/** Like stringList, but keeps "the API omitted this field" distinct from an empty list. */
|
|
443
|
+
function optionalStringList(value) {
|
|
444
|
+
return Array.isArray(value) ? stringList(value) : undefined;
|
|
445
|
+
}
|
|
260
446
|
function isRecord(value) {
|
|
261
447
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
262
448
|
}
|
|
263
|
-
function errorMessage(error) {
|
|
264
|
-
return sanitizeUntrustedText(error instanceof Error ? error.message : String(error));
|
|
265
|
-
}
|
package/lib/config.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Plugin option resolution for opencode-querit. Raw options come from the
|
|
3
|
-
* `
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* `options` object of the plugin's entry in `opencode.json(c)`; every value is
|
|
4
|
+
* validated, normalized, and defaulted here so the tools only ever see a fully
|
|
5
|
+
* resolved `QueritConfig`.
|
|
6
6
|
*
|
|
7
7
|
* API-key resolution happens per tool call in priority order: the
|
|
8
8
|
* environment variable named by `apiKeyEnv` (default `QUERIT_API_KEY`), then
|
|
@@ -10,21 +10,10 @@
|
|
|
10
10
|
* overrides plugin config everywhere.
|
|
11
11
|
* @module opencode-querit/config
|
|
12
12
|
*/
|
|
13
|
-
|
|
14
|
-
export declare const LANGUAGE_VALUES: readonly ["english", "japanese", "korean", "german", "french", "spanish", "portuguese"];
|
|
15
|
-
/** `dN`/`wN`/`mN`/`yN` (N ≥ 1) or an inclusive `YYYY-MM-DDtoYYYY-MM-DD` range. */
|
|
16
|
-
export declare const TIME_RANGE_PATTERN: RegExp;
|
|
13
|
+
import { type QueritCountry, type QueritFetchFormat, type QueritLanguage, type QueritRankPreference, type QueritResourceTag, type QueritVertical } from "./client.js";
|
|
17
14
|
export declare const DEFAULT_API_KEY_ENV = "QUERIT_API_KEY";
|
|
18
15
|
export declare const BASE_URL_ENV = "QUERIT_BASE_URL";
|
|
19
|
-
|
|
20
|
-
export declare const DEFAULT_TIMEOUT_MS = 70000;
|
|
21
|
-
export declare const DEFAULT_CHUNKS_PER_DOC = 1;
|
|
22
|
-
export declare const DEFAULT_FETCH_FORMAT = "markdown";
|
|
23
|
-
export declare const DEFAULT_FETCH_CRAWL_TIMEOUT = 10;
|
|
24
|
-
export declare const DEFAULT_FETCH_MAX_CHARS = 8000;
|
|
25
|
-
export declare const DEFAULT_MAX_OUTPUT_CHARS = 200000;
|
|
26
|
-
export type FetchFormat = "text" | "markdown" | "html";
|
|
27
|
-
/** Raw options accepted from the `opencode.json` plugin tuple. */
|
|
16
|
+
/** Raw options accepted from the plugin's `options` object. */
|
|
28
17
|
export interface OpenCodeQueritOptions {
|
|
29
18
|
/** Literal Querit API key; prefer `apiKeyEnv` so no secret enters opencode.json. */
|
|
30
19
|
apiKey?: string;
|
|
@@ -32,26 +21,38 @@ export interface OpenCodeQueritOptions {
|
|
|
32
21
|
apiKeyEnv?: string;
|
|
33
22
|
/** Querit API base URL; `/v1/search` and `/v1/contents` are appended. */
|
|
34
23
|
baseURL?: string;
|
|
35
|
-
/** Per-request timeout in ms (default: 70000). */
|
|
24
|
+
/** Per-request timeout in ms (default: 70000), retries and backoff waits included. */
|
|
36
25
|
timeoutMs?: number;
|
|
37
|
-
/**
|
|
26
|
+
/** Result count per search, 1–100. Unset: Querit's server default decides. */
|
|
38
27
|
count?: number;
|
|
39
28
|
/** Relative (`d7`, `w2`, `m3`, `y1`) or `YYYY-MM-DDtoYYYY-MM-DD` date range. */
|
|
40
29
|
timeRange?: string;
|
|
41
|
-
/** Country
|
|
42
|
-
countries?:
|
|
30
|
+
/** Country filter; values from the Querit country list. */
|
|
31
|
+
countries?: QueritCountry[];
|
|
43
32
|
/** Language filter; values from the Querit language list. */
|
|
44
|
-
languages?:
|
|
33
|
+
languages?: QueritLanguage[];
|
|
45
34
|
/** Whitelist hostnames (only these domains return results). */
|
|
46
35
|
includeDomains?: string[];
|
|
47
36
|
/** Blacklist hostnames (these domains never return results). */
|
|
48
37
|
excludeDomains?: string[];
|
|
49
|
-
/**
|
|
38
|
+
/** Vertical search: `code` or `finance`. Unset: universal search. */
|
|
39
|
+
vertical?: QueritVertical;
|
|
40
|
+
/** Sub-tags of the `code` vertical to keep (`qa`, `github`). Requires `vertical: "code"`. */
|
|
41
|
+
resourceTags?: QueritResourceTag[];
|
|
42
|
+
/** Ranking preference, a boost on top of Querit's default ranking. Dropped for the `code` vertical. */
|
|
43
|
+
rank?: QueritRankPreference;
|
|
44
|
+
/** Request query-focused fragments (`highlights`) of each result. */
|
|
45
|
+
highlights?: boolean;
|
|
46
|
+
/** Request sentence-level content excerpts (`needContent`); excerpts are appended to each result's content. */
|
|
50
47
|
includeContent?: boolean;
|
|
51
|
-
/**
|
|
48
|
+
/** Server-side limit on the body text of each result, in Unicode code points (1–1000000). Only read with `includeContent`. */
|
|
49
|
+
contentMaxChars?: number;
|
|
50
|
+
/** Request Markdown versions of each result's snippet and body (`needMarkdown`); Enterprise plans only. */
|
|
51
|
+
needMarkdown?: boolean;
|
|
52
|
+
/** Summary chunks per result, 1–3. Deprecated by Querit in favor of `highlights`; sent only when set. */
|
|
52
53
|
chunksPerDoc?: number;
|
|
53
54
|
/** Format requested from `/v1/contents` for fetch calls (default: markdown). */
|
|
54
|
-
fetchFormat?:
|
|
55
|
+
fetchFormat?: QueritFetchFormat;
|
|
55
56
|
/** Per-page crawl timeout in seconds, 1–60 (default: 10). */
|
|
56
57
|
fetchCrawlTimeout?: number;
|
|
57
58
|
/** Cap applied to one fetched page's decoded body, in chars (default: 8000). */
|
|
@@ -65,30 +66,29 @@ export interface QueritConfig {
|
|
|
65
66
|
apiKeyEnv: string;
|
|
66
67
|
baseURL: string;
|
|
67
68
|
timeoutMs: number;
|
|
68
|
-
count
|
|
69
|
+
count?: number;
|
|
69
70
|
timeRange?: string;
|
|
70
|
-
countries:
|
|
71
|
-
languages:
|
|
71
|
+
countries: QueritCountry[];
|
|
72
|
+
languages: QueritLanguage[];
|
|
72
73
|
includeDomains: string[];
|
|
73
74
|
excludeDomains: string[];
|
|
75
|
+
vertical?: QueritVertical;
|
|
76
|
+
resourceTags: QueritResourceTag[];
|
|
77
|
+
rank?: QueritRankPreference;
|
|
78
|
+
highlights: boolean;
|
|
74
79
|
includeContent: boolean;
|
|
75
|
-
|
|
76
|
-
|
|
80
|
+
contentMaxChars?: number;
|
|
81
|
+
needMarkdown: boolean;
|
|
82
|
+
chunksPerDoc?: number;
|
|
83
|
+
fetchFormat: QueritFetchFormat;
|
|
77
84
|
fetchCrawlTimeout: number;
|
|
78
85
|
fetchMaxChars: number;
|
|
79
86
|
maxOutputChars: number;
|
|
80
87
|
}
|
|
81
|
-
export declare function isTimeRange(value: unknown): value is string;
|
|
82
|
-
/**
|
|
83
|
-
* Normalize a configured hostname list: lowercase, drop schemes/ports/paths,
|
|
84
|
-
* and keep at most 100 unique entries. Invalid entries are dropped.
|
|
85
|
-
*/
|
|
86
|
-
export declare function normalizeDomains(values: readonly string[] | undefined): string[];
|
|
87
|
-
export declare function normalizeHostname(value: string): string | undefined;
|
|
88
88
|
/**
|
|
89
89
|
* Resolve raw plugin options (plus environment fallbacks) into a fully
|
|
90
90
|
* defaulted `QueritConfig`. Throws a descriptive error on any invalid value
|
|
91
|
-
* so a misconfigured `opencode.json` fails the
|
|
91
|
+
* so a misconfigured `opencode.json` fails the plugin load loudly instead of
|
|
92
92
|
* silently changing behavior.
|
|
93
93
|
*/
|
|
94
94
|
export declare function resolveConfig(options?: OpenCodeQueritOptions, env?: NodeJS.ProcessEnv): QueritConfig;
|