dsh-querit 1.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.
@@ -0,0 +1,292 @@
1
+ import { WebError } from "@deepseek-ai/dsh-web";
2
+ import { DEFAULT_REQUEST_TIMEOUT_MS, QueritApiError, QueritClient, } from "./client.js";
3
+ /** Stable id both providers register under. */
4
+ export const QUERIT_PROVIDER_ID = "querit";
5
+ export const COUNTRY_VALUES = [
6
+ "argentina",
7
+ "australia",
8
+ "brazil",
9
+ "canada",
10
+ "colombia",
11
+ "france",
12
+ "germany",
13
+ "india",
14
+ "indonesia",
15
+ "japan",
16
+ "mexico",
17
+ "nigeria",
18
+ "philippines",
19
+ "south korea",
20
+ "spain",
21
+ "united kingdom",
22
+ "united states",
23
+ ];
24
+ export const LANGUAGE_VALUES = [
25
+ "english",
26
+ "japanese",
27
+ "korean",
28
+ "german",
29
+ "french",
30
+ "spanish",
31
+ "portuguese",
32
+ ];
33
+ /** `dN`/`wN`/`mN`/`yN` (N ≥ 1) or an inclusive `YYYY-MM-DDtoYYYY-MM-DD` range. */
34
+ export const TIME_RANGE_PATTERN = /^(?:[dwmy][1-9][0-9]*|\d{4}-\d{2}-\d{2}to\d{4}-\d{2}-\d{2})$/u;
35
+ /** Cap on one source's merged snippet + sentence excerpts, in chars. */
36
+ const SNIPPET_MAX_CHARS = 4_096;
37
+ export function isTimeRange(value) {
38
+ return typeof value === "string" && TIME_RANGE_PATTERN.test(value.trim());
39
+ }
40
+ /**
41
+ * Normalize a configured hostname list: lowercase, drop schemes/ports/paths,
42
+ * and keep at most 100 unique entries. Invalid entries are dropped.
43
+ */
44
+ export function normalizeDomains(values) {
45
+ const domains = new Set();
46
+ for (const entry of values ?? []) {
47
+ const host = normalizeHostname(entry);
48
+ if (host)
49
+ domains.add(host);
50
+ if (domains.size >= 100)
51
+ break;
52
+ }
53
+ return [...domains];
54
+ }
55
+ export function normalizeHostname(value) {
56
+ const trimmed = value.trim().toLowerCase();
57
+ if (!trimmed)
58
+ return undefined;
59
+ const candidate = trimmed.includes("://") ? trimmed : `https://${trimmed}`;
60
+ let url;
61
+ try {
62
+ url = new URL(candidate);
63
+ }
64
+ catch {
65
+ return undefined;
66
+ }
67
+ if (url.protocol !== "http:" && url.protocol !== "https:")
68
+ return undefined;
69
+ const host = url.hostname.toLowerCase();
70
+ if (!host || host.length > 253 || !host.includes("."))
71
+ return undefined;
72
+ return host;
73
+ }
74
+ function clampInteger(value, min, max) {
75
+ return Math.min(max, Math.max(min, Math.trunc(value)));
76
+ }
77
+ function mergeSnippet(result) {
78
+ const parts = [];
79
+ if (result.snippet.trim())
80
+ parts.push(result.snippet.trim());
81
+ for (const sentence of result.sentences) {
82
+ const trimmed = sentence.trim();
83
+ if (trimmed)
84
+ parts.push(`- ${trimmed}`);
85
+ }
86
+ const merged = parts.join("\n");
87
+ return merged.length <= SNIPPET_MAX_CHARS ? merged : `${merged.slice(0, SNIPPET_MAX_CHARS - 3)}...`;
88
+ }
89
+ export class QueritSearchProvider {
90
+ resolveOptions;
91
+ id = QUERIT_PROVIDER_ID;
92
+ /**
93
+ * @param resolveOptions - options for the NEXT operation, snapshotted once
94
+ * at each operation's entry so one search never mixes two settings sections.
95
+ */
96
+ constructor(resolveOptions) {
97
+ this.resolveOptions = resolveOptions;
98
+ }
99
+ available() {
100
+ const options = this.resolveOptions();
101
+ if (!URL.canParse(options.baseURL))
102
+ return false;
103
+ if ((options.apiKey?.length ?? 0) === 0 && options.resolveApiKey === undefined)
104
+ return false;
105
+ if (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1_000)
106
+ return false;
107
+ if (!Number.isInteger(options.count) || options.count < 1 || options.count > 20)
108
+ return false;
109
+ if (!Number.isInteger(options.chunksPerDoc) || options.chunksPerDoc < 1 || options.chunksPerDoc > 3)
110
+ return false;
111
+ if (options.timeRange !== undefined && !isTimeRange(options.timeRange))
112
+ return false;
113
+ return true;
114
+ }
115
+ async search(request, signal) {
116
+ throwIfAborted(signal);
117
+ const options = this.resolveOptions();
118
+ const client = await this.client(options, signal);
119
+ const filters = {};
120
+ if (options.includeDomains.length > 0 || options.excludeDomains.length > 0) {
121
+ filters.sites = {
122
+ ...(options.includeDomains.length > 0 ? { include: options.includeDomains } : {}),
123
+ ...(options.excludeDomains.length > 0 ? { exclude: options.excludeDomains } : {}),
124
+ };
125
+ }
126
+ if (options.timeRange)
127
+ filters.timeRange = { date: options.timeRange };
128
+ if (options.countries.length > 0)
129
+ filters.geo = { countries: { include: options.countries } };
130
+ if (options.languages.length > 0)
131
+ filters.languages = { include: options.languages };
132
+ const count = clampInteger(request.maxResults ?? options.count, 1, 20);
133
+ let response;
134
+ try {
135
+ response = await client.search({
136
+ query: request.query,
137
+ count,
138
+ chunksPerDoc: options.chunksPerDoc,
139
+ needContent: options.includeContent,
140
+ ...(Object.keys(filters).length === 0 ? {} : { filters }),
141
+ }, signal);
142
+ }
143
+ catch (error) {
144
+ if (signal?.aborted === true || isAbortError(error))
145
+ throw aborted(signal, error);
146
+ throw new WebError(`Querit search failed: ${errorMessage(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
147
+ }
148
+ const sources = response.results.map((result) => ({
149
+ url: result.url,
150
+ ...(result.title && result.title !== result.url ? { title: result.title } : {}),
151
+ ...(mergeSnippet(result) ? { snippet: mergeSnippet(result) } : {}),
152
+ ...(result.pageAge ? { publishedAt: result.pageAge } : {}),
153
+ }));
154
+ return { sources, truncated: false };
155
+ }
156
+ async client(options, signal) {
157
+ throwIfAborted(signal);
158
+ let apiKey = options.apiKey;
159
+ if (apiKey === undefined || apiKey.length === 0) {
160
+ let resolved;
161
+ try {
162
+ resolved = await abortable(options.resolveApiKey?.() ?? Promise.resolve(undefined), signal);
163
+ }
164
+ catch (error) {
165
+ if (signal?.aborted === true || isAbortError(error))
166
+ throw aborted(signal, error);
167
+ throw new WebError(`Querit credential resolution failed: ${errorMessage(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
168
+ }
169
+ apiKey = resolved;
170
+ }
171
+ if (apiKey === undefined || apiKey.length === 0) {
172
+ throw new WebError(`Querit has no API key for "${options.apiKeyEnv ?? "QUERIT_API_KEY"}". Configure it in priority order: export it in the launching environment, add it to the credentials store ($DSH_HOME/.credentials.yaml), or set a literal "apiKey" on the web-search-querit row. See the dsh-querit README for details.`, "WEB_PROVIDER_CREDENTIAL_MISSING");
173
+ }
174
+ return options.clientFactory?.({ apiKey, baseUrl: options.baseURL, timeoutMs: options.timeoutMs })
175
+ ?? new QueritClient({ apiKey, baseUrl: options.baseURL, timeoutMs: options.timeoutMs });
176
+ }
177
+ }
178
+ export class QueritFetchProvider {
179
+ resolveOptions;
180
+ id = QUERIT_PROVIDER_ID;
181
+ constructor(resolveOptions) {
182
+ this.resolveOptions = resolveOptions;
183
+ }
184
+ available() {
185
+ const options = this.resolveOptions();
186
+ if (!URL.canParse(options.baseURL))
187
+ return false;
188
+ if ((options.apiKey?.length ?? 0) === 0 && options.resolveApiKey === undefined)
189
+ return false;
190
+ if (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1_000)
191
+ return false;
192
+ if (!Number.isInteger(options.fetchCrawlTimeout) || options.fetchCrawlTimeout < 1 || options.fetchCrawlTimeout > 60)
193
+ return false;
194
+ if (!Number.isInteger(options.fetchMaxChars) || options.fetchMaxChars < 256)
195
+ return false;
196
+ return true;
197
+ }
198
+ async fetch(request, signal) {
199
+ throwIfAborted(signal);
200
+ const options = this.resolveOptions();
201
+ const client = await this.client(options, signal);
202
+ let response;
203
+ try {
204
+ response = await client.contents({
205
+ urls: [request.url],
206
+ format: options.fetchFormat,
207
+ crawlTimeout: options.fetchCrawlTimeout,
208
+ extrasMeta: false,
209
+ }, signal);
210
+ }
211
+ catch (error) {
212
+ if (signal?.aborted === true || isAbortError(error))
213
+ throw aborted(signal, error);
214
+ throw new WebError(`Querit fetch failed: ${errorMessage(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
215
+ }
216
+ const succeeded = response.statuses.some((status) => status.status === "success");
217
+ const result = response.results.find((item) => item.content.length > 0) ?? response.results[0];
218
+ if (succeeded && result !== undefined && result.content.length > 0) {
219
+ const truncated = result.content.length > options.fetchMaxChars;
220
+ const content = truncated ? `${result.content.slice(0, options.fetchMaxChars - 3)}...` : result.content;
221
+ return {
222
+ url: result.url,
223
+ statusCode: 200,
224
+ body: { kind: options.fetchFormat === "html" ? "html" : "text", content },
225
+ truncated,
226
+ };
227
+ }
228
+ const failed = response.statuses.find((status) => status.status !== undefined && status.status !== "success");
229
+ throw new WebError(failed ? `Querit could not retrieve the page: ${failed.status}` : "Querit returned no content for the requested URL.", "WEB_PROVIDER_ERROR");
230
+ }
231
+ async client(options, signal) {
232
+ throwIfAborted(signal);
233
+ let apiKey = options.apiKey;
234
+ if (apiKey === undefined || apiKey.length === 0) {
235
+ let resolved;
236
+ try {
237
+ resolved = await abortable(options.resolveApiKey?.() ?? Promise.resolve(undefined), signal);
238
+ }
239
+ catch (error) {
240
+ if (signal?.aborted === true || isAbortError(error))
241
+ throw aborted(signal, error);
242
+ throw new WebError(`Querit credential resolution failed: ${errorMessage(error)}`, "WEB_PROVIDER_ERROR", { cause: error });
243
+ }
244
+ apiKey = resolved;
245
+ }
246
+ if (apiKey === undefined || apiKey.length === 0) {
247
+ throw new WebError(`Querit has no API key for "${options.apiKeyEnv ?? "QUERIT_API_KEY"}". Configure it in priority order: export it in the launching environment, add it to the credentials store ($DSH_HOME/.credentials.yaml), or set a literal "apiKey" on the web-search-querit row. See the dsh-querit README for details.`, "WEB_PROVIDER_CREDENTIAL_MISSING");
248
+ }
249
+ return options.clientFactory?.({ apiKey, baseUrl: options.baseURL, timeoutMs: options.timeoutMs })
250
+ ?? new QueritClient({ apiKey, baseUrl: options.baseURL, timeoutMs: options.timeoutMs });
251
+ }
252
+ }
253
+ /**
254
+ * Race a same-process asynchronous preflight against caller cancellation. The
255
+ * attached settlement handlers keep observing an uncooperative operation after
256
+ * abort so a later rejection cannot become unhandled.
257
+ */
258
+ function abortable(operation, signal) {
259
+ if (signal === undefined)
260
+ return operation;
261
+ if (signal.aborted)
262
+ return Promise.reject(aborted(signal));
263
+ return new Promise((resolve, reject) => {
264
+ const onAbort = () => reject(aborted(signal));
265
+ signal.addEventListener("abort", onAbort, { once: true });
266
+ operation.then((value) => {
267
+ signal.removeEventListener("abort", onAbort);
268
+ resolve(value);
269
+ }, (error) => {
270
+ signal.removeEventListener("abort", onAbort);
271
+ reject(new Error(errorMessage(error), { cause: error }));
272
+ });
273
+ });
274
+ }
275
+ /** Throw the provider's stable cancellation error when the caller already aborted. */
276
+ function throwIfAborted(signal) {
277
+ if (signal?.aborted === true)
278
+ throw aborted(signal);
279
+ }
280
+ /** Build the provider's stable cancellation error while retaining the caller's reason. */
281
+ function aborted(signal, fallback) {
282
+ return new WebError("Querit request aborted", "WEB_ABORTED", { cause: signal?.aborted === true ? signal.reason : fallback });
283
+ }
284
+ /** True for a fetch/`AbortSignal` abort, surfaced as `WEB_ABORTED`. */
285
+ function isAbortError(error) {
286
+ return error instanceof DOMException && error.name === "AbortError";
287
+ }
288
+ function errorMessage(error) {
289
+ if (error instanceof QueritApiError)
290
+ return error.message;
291
+ return error instanceof Error ? error.message : String(error);
292
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Remove terminal escape/control sequences from untrusted remote text.
3
+ * Newlines and tabs are preserved so page content remains readable.
4
+ * Ported from pi-querit (MIT).
5
+ * @module dsh-querit/sanitize
6
+ */
7
+ export declare function sanitizeUntrustedText(value: string): string;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Remove terminal escape/control sequences from untrusted remote text.
3
+ * Newlines and tabs are preserved so page content remains readable.
4
+ * Ported from pi-querit (MIT).
5
+ * @module dsh-querit/sanitize
6
+ */
7
+ const ESC = 0x1b;
8
+ const BEL = 0x07;
9
+ const DELETE = 0x7f;
10
+ const CSI = 0x9b;
11
+ const ST = 0x9c;
12
+ const OSC = 0x9d;
13
+ const CONTROL_STRING_STARTS = new Set([0x90, 0x98, 0x9e, 0x9f]);
14
+ const ESC_CONTROL_STRING_STARTS = new Set([0x50, 0x58, 0x5e, 0x5f]);
15
+ const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu;
16
+ export function sanitizeUntrustedText(value) {
17
+ let output = "";
18
+ for (let index = 0; index < value.length;) {
19
+ const code = value.charCodeAt(index);
20
+ if (code === ESC) {
21
+ const next = value.charCodeAt(index + 1);
22
+ if (next === 0x5b) {
23
+ index = skipCsi(value, index + 2);
24
+ }
25
+ else if (next === 0x5d) {
26
+ index = skipOsc(value, index + 2);
27
+ }
28
+ else if (ESC_CONTROL_STRING_STARTS.has(next)) {
29
+ index = skipControlString(value, index + 2);
30
+ }
31
+ else {
32
+ index += Number.isNaN(next) ? 1 : 2;
33
+ }
34
+ continue;
35
+ }
36
+ if (code === CSI) {
37
+ index = skipCsi(value, index + 1);
38
+ continue;
39
+ }
40
+ if (code === OSC) {
41
+ index = skipOsc(value, index + 1);
42
+ continue;
43
+ }
44
+ if (CONTROL_STRING_STARTS.has(code)) {
45
+ index = skipControlString(value, index + 1);
46
+ continue;
47
+ }
48
+ if (code === 0x0a || code === 0x09) {
49
+ output += value[index];
50
+ index += 1;
51
+ continue;
52
+ }
53
+ if (code < 0x20 || (code >= 0x80 && code <= 0x9f) || code === DELETE) {
54
+ index += 1;
55
+ continue;
56
+ }
57
+ const codePoint = value.codePointAt(index);
58
+ if (codePoint === undefined)
59
+ break;
60
+ output += String.fromCodePoint(codePoint);
61
+ index += codePoint > 0xffff ? 2 : 1;
62
+ }
63
+ return output.replace(BIDI_CONTROLS, "");
64
+ }
65
+ function skipCsi(value, start) {
66
+ let index = start;
67
+ while (index < value.length) {
68
+ const code = value.charCodeAt(index);
69
+ index += 1;
70
+ if (code >= 0x40 && code <= 0x7e)
71
+ return index;
72
+ }
73
+ return index;
74
+ }
75
+ function skipOsc(value, start) {
76
+ let index = start;
77
+ while (index < value.length) {
78
+ const code = value.charCodeAt(index);
79
+ if (code === BEL || code === ST)
80
+ return index + 1;
81
+ if (code === ESC && value.charCodeAt(index + 1) === 0x5c)
82
+ return index + 2;
83
+ index += 1;
84
+ }
85
+ return index;
86
+ }
87
+ function skipControlString(value, start) {
88
+ let index = start;
89
+ while (index < value.length) {
90
+ const code = value.charCodeAt(index);
91
+ if (code === ST)
92
+ return index + 1;
93
+ if (code === ESC && value.charCodeAt(index + 1) === 0x5c)
94
+ return index + 2;
95
+ index += 1;
96
+ }
97
+ return index;
98
+ }
package/package.json ADDED
@@ -0,0 +1,97 @@
1
+ {
2
+ "name": "dsh-querit",
3
+ "description": "Querit-backed search and fetch providers for the DeepSeek Harness web capability seam (ctx.web)",
4
+ "version": "1.0.0",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "default": "./lib/index.js"
12
+ },
13
+ "./invariant": {
14
+ "types": "./lib/invariant.d.ts",
15
+ "default": "./lib/invariant.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "lib",
21
+ "README.md",
22
+ "README-zh.md",
23
+ "LICENSE"
24
+ ],
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/querit-ai/querit-plugins.git"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/querit-ai/querit-plugins/issues"
32
+ },
33
+ "keywords": [
34
+ "dsh-plugin",
35
+ "deepseek-harness",
36
+ "querit",
37
+ "web-search",
38
+ "web-fetch"
39
+ ],
40
+ "scripts": {
41
+ "check": "tsc -p tsconfig.check.json",
42
+ "build": "tsc -p tsconfig.json",
43
+ "test": "vitest run tests",
44
+ "pack:check": "npm pack --dry-run",
45
+ "prepack": "npm run check && npm test && npm run build"
46
+ },
47
+ "peerDependencies": {
48
+ "@deepseek-ai/cordis": "^4.0.1",
49
+ "@deepseek-ai/dsh-credentials": "^0.1.0-rc.6",
50
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
51
+ "@deepseek-ai/dsh-launch-environment": "^0.1.0-rc.6",
52
+ "@deepseek-ai/dsh-settings": "^0.1.0-rc.6",
53
+ "@deepseek-ai/dsh-tool-web": "^0.1.0-rc.6",
54
+ "@deepseek-ai/dsh-web": "^0.1.0-rc.6"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "@deepseek-ai/cordis": {
58
+ "optional": true
59
+ },
60
+ "@deepseek-ai/dsh-credentials": {
61
+ "optional": true
62
+ },
63
+ "@deepseek-ai/dsh-invariants": {
64
+ "optional": true
65
+ },
66
+ "@deepseek-ai/dsh-launch-environment": {
67
+ "optional": true
68
+ },
69
+ "@deepseek-ai/dsh-settings": {
70
+ "optional": true
71
+ },
72
+ "@deepseek-ai/dsh-tool-web": {
73
+ "optional": true
74
+ },
75
+ "@deepseek-ai/dsh-web": {
76
+ "optional": true
77
+ }
78
+ },
79
+ "dependencies": {
80
+ "@deepseek-ai/schemastery": "^3.18.1"
81
+ },
82
+ "devDependencies": {
83
+ "@deepseek-ai/cordis": "^4.0.1",
84
+ "@deepseek-ai/dsh-credentials": "^0.1.0-rc.6",
85
+ "@deepseek-ai/dsh-invariants": "^0.1.0-rc.6",
86
+ "@deepseek-ai/dsh-launch-environment": "^0.1.0-rc.6",
87
+ "@deepseek-ai/dsh-settings": "^0.1.0-rc.6",
88
+ "@deepseek-ai/dsh-tool-web": "^0.1.0-rc.6",
89
+ "@deepseek-ai/dsh-web": "^0.1.0-rc.6",
90
+ "@types/node": "^22.0.0",
91
+ "typescript": "^5.9.0",
92
+ "vitest": "^4.0.0"
93
+ },
94
+ "engines": {
95
+ "node": ">=22.19.0"
96
+ }
97
+ }