@hexiaowu/dsh-web-search-zai 0.0.0-stage → 0.1.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/lib/search.js ADDED
@@ -0,0 +1,321 @@
1
+ /**
2
+ * The two Z.ai search backends and their `auto` orchestration.
3
+ *
4
+ * - `plan`: one Anthropic-compatible Messages call with the server-side
5
+ * `web_search_20250305` tool. It spends the GLM coding-plan quota and can
6
+ * answer slowly because the provider model is thinking.
7
+ * - `api`: the metered native `/web_search` endpoint. It returns structured
8
+ * results quickly but is billed per call.
9
+ *
10
+ * Both throw `WebError` with the seam's vocabulary
11
+ * (`WEB_PROVIDER_ERROR` / `WEB_ABORTED`); this module never retries, because
12
+ * the Host tool layer already owns cancellation and the retry budget.
13
+ *
14
+ * @module dsh-web-search-zai/search
15
+ */
16
+ import { WebError } from '@deepseek-ai/dsh-web';
17
+ import { parseApiResponse, parsePlanResponse } from './parse.js';
18
+ import { isNonBlankString, previewText } from './util.js';
19
+
20
+ /** Accepted `mode` values. Anything else behaves as `auto`. */
21
+ export const SEARCH_MODES = Object.freeze(['auto', 'plan', 'api']);
22
+
23
+ /** Upper bound on the native API channel, which should answer in seconds. */
24
+ const API_TIMEOUT_CAP_MS = 15000;
25
+
26
+ /** Anthropic server-tool descriptor the plan channel requests. */
27
+ const PLAN_SEARCH_TOOL_TYPE = 'web_search_20250305';
28
+
29
+ /** Attribution header sent on every request. Bump with the package version. */
30
+ const USER_AGENT = 'dsh-web-search-zai/0.1.0';
31
+
32
+ /** Keep an upstream HTML error page from flooding the model-facing message. */
33
+ const MAX_ERROR_BODY_CHARS = 600;
34
+
35
+ /** Instruction that keeps the plan channel from answering out of memory. */
36
+ const PLAN_INSTRUCTION = 'Use the web_search tool to search the web for the query below, then stop. '
37
+ + 'Do not answer from memory, do not add commentary.';
38
+
39
+ /**
40
+ * Run one search through the configured channel(s).
41
+ *
42
+ * @param {object} input - the call input.
43
+ * @param {string} input.query - one query; the Host fans multiple tool queries out to parallel calls.
44
+ * @param {object} input.options - the settings snapshot for this operation.
45
+ * @param {string} input.apiKey - the resolved API key.
46
+ * @param {AbortSignal} [input.signal] - the Host tool call's cancellation signal.
47
+ * @param {typeof fetch} [input.fetchImpl] - injectable transport for tests.
48
+ * @returns {Promise<{ sources: object[], truncated: boolean }>} the normalized search result.
49
+ * @throws {WebError} with `WEB_PROVIDER_ERROR` or `WEB_ABORTED`.
50
+ */
51
+ export async function runSearch({ query, options, apiKey, signal, fetchImpl = fetch }) {
52
+ if (!isNonBlankString(query)) {
53
+ throw new WebError('Z.ai web search requires a non-empty query.', 'WEB_PROVIDER_ERROR');
54
+ }
55
+ if (!isNonBlankString(apiKey)) {
56
+ throw new WebError(
57
+ `Z.ai web search has no API key for "${options.apiKeyEnv ?? 'ZAI_CODING_CN_API_KEY'}".`,
58
+ 'WEB_PROVIDER_CREDENTIAL_MISSING',
59
+ );
60
+ }
61
+
62
+ const mode = normalizeMode(options.mode);
63
+ if (mode === 'plan') return searchViaPlan({ query, options, apiKey, signal, fetchImpl });
64
+ if (mode === 'api') return searchViaApi({ query, options, apiKey, signal, fetchImpl });
65
+ return searchWithFallback({ query, options, apiKey, signal, fetchImpl });
66
+ }
67
+
68
+ /**
69
+ * Search through the plan channel only.
70
+ *
71
+ * @param {object} input - the call input (see {@link runSearch}).
72
+ * @returns {Promise<{ sources: object[], truncated: boolean }>}
73
+ */
74
+ export async function searchViaPlan({ query, options, apiKey, signal, fetchImpl = fetch }) {
75
+ const endpoint = joinEndpoint(options.planBaseURL, 'messages');
76
+ return dispatchJson({
77
+ fetchImpl,
78
+ endpoint,
79
+ label: 'Z.ai plan web search',
80
+ headers: {
81
+ 'x-api-key': apiKey,
82
+ authorization: `Bearer ${apiKey}`,
83
+ 'anthropic-version': options.apiVersion,
84
+ 'content-type': 'application/json',
85
+ accept: 'application/json',
86
+ 'user-agent': USER_AGENT,
87
+ },
88
+ body: {
89
+ model: options.model,
90
+ max_tokens: options.maxTokens,
91
+ messages: [{
92
+ role: 'user',
93
+ content: [{ type: 'text', text: `${PLAN_INSTRUCTION}\n\nQuery: ${query}` }],
94
+ }],
95
+ tools: [{ type: PLAN_SEARCH_TOOL_TYPE, name: 'web_search', max_uses: options.maxUses }],
96
+ },
97
+ validate: parsePlanResponse,
98
+ callerSignal: signal,
99
+ timeoutMs: options.timeoutMs,
100
+ });
101
+ }
102
+
103
+ /**
104
+ * Search through the metered native API only.
105
+ *
106
+ * @param {object} input - the call input (see {@link runSearch}).
107
+ * @returns {Promise<{ sources: object[], truncated: boolean }>}
108
+ */
109
+ export async function searchViaApi({ query, options, apiKey, signal, fetchImpl = fetch }) {
110
+ const endpoint = joinEndpoint(options.apiBaseURL, 'web_search');
111
+ return dispatchJson({
112
+ fetchImpl,
113
+ endpoint,
114
+ label: 'Z.ai native web search',
115
+ headers: {
116
+ authorization: `Bearer ${apiKey}`,
117
+ 'content-type': 'application/json',
118
+ accept: 'application/json',
119
+ 'user-agent': USER_AGENT,
120
+ },
121
+ body: {
122
+ search_engine: options.searchEngine,
123
+ search_query: query,
124
+ count: options.count,
125
+ },
126
+ validate: parseApiResponse,
127
+ callerSignal: signal,
128
+ timeoutMs: Math.min(options.timeoutMs, API_TIMEOUT_CAP_MS),
129
+ });
130
+ }
131
+
132
+ /** Try the plan channel, then fall back to the native API on any non-abort failure. */
133
+ async function searchWithFallback({ query, options, apiKey, signal, fetchImpl }) {
134
+ let planError;
135
+ try {
136
+ return await searchViaPlan({ query, options, apiKey, signal, fetchImpl });
137
+ } catch (error) {
138
+ if (isAborted(error, signal)) throw error;
139
+ planError = error;
140
+ }
141
+
142
+ let apiError;
143
+ try {
144
+ return await searchViaApi({ query, options, apiKey, signal, fetchImpl });
145
+ } catch (error) {
146
+ if (isAborted(error, signal)) throw error;
147
+ apiError = error;
148
+ }
149
+
150
+ throw new WebError(
151
+ 'Z.ai web search failed on both channels.\n'
152
+ + `- plan channel: ${errorMessage(planError)}\n`
153
+ + `- api channel: ${errorMessage(apiError)}\n\n`
154
+ + 'The plan channel spends GLM coding-plan quota on one model call and uses planBaseURL; '
155
+ + 'the api channel is the metered native search API and uses apiBaseURL. '
156
+ + 'Fix the endpoint, key, quota, or network problem named above, or set mode to "plan" or "api" '
157
+ + 'in the web-search-zai plugin settings to use a single channel.',
158
+ 'WEB_PROVIDER_ERROR',
159
+ { cause: apiError },
160
+ );
161
+ }
162
+
163
+ /** POST a JSON body and hand the decoded JSON to a channel parser. */
164
+ async function dispatchJson({
165
+ fetchImpl, endpoint, label, headers, body, validate, callerSignal, timeoutMs,
166
+ }) {
167
+ throwIfAborted(callerSignal, label);
168
+
169
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
170
+ const signal = callerSignal === undefined ? timeoutSignal : AbortSignal.any([callerSignal, timeoutSignal]);
171
+
172
+ let response;
173
+ try {
174
+ response = await fetchImpl(endpoint, {
175
+ method: 'POST',
176
+ redirect: 'error',
177
+ headers,
178
+ body: JSON.stringify(body),
179
+ signal,
180
+ });
181
+ } catch (error) {
182
+ throw transportFailure(error, { label, endpoint, callerSignal, timeoutSignal, timeoutMs });
183
+ }
184
+
185
+ let text;
186
+ try {
187
+ text = await response.text();
188
+ } catch (error) {
189
+ throw transportFailure(error, { label, endpoint, callerSignal, timeoutSignal, timeoutMs });
190
+ }
191
+
192
+ if (!response.ok) throw upstreamFailure(response, text, label, endpoint);
193
+
194
+ let json;
195
+ try {
196
+ json = text.trim().length === 0 ? {} : JSON.parse(text);
197
+ } catch {
198
+ throw new WebError(
199
+ `${label} returned a non-JSON response (HTTP ${response.status}): ${previewText(text, MAX_ERROR_BODY_CHARS)}\n\n`
200
+ + `The request used endpoint ${endpoint}.`,
201
+ 'WEB_PROVIDER_ERROR',
202
+ );
203
+ }
204
+
205
+ try {
206
+ return validate(json);
207
+ } catch (error) {
208
+ if (error instanceof WebError) throw error;
209
+ if (error?.code === 'WEB_PROVIDER_ERROR') {
210
+ throw new WebError(
211
+ `${error.message}\n\nThe request used endpoint ${endpoint}.`,
212
+ 'WEB_PROVIDER_ERROR',
213
+ { cause: error },
214
+ );
215
+ }
216
+ throw new WebError(
217
+ `${label} returned a response this provider could not use: ${errorMessage(error)}\n\n`
218
+ + `The request used endpoint ${endpoint}.`,
219
+ 'WEB_PROVIDER_ERROR',
220
+ { cause: error },
221
+ );
222
+ }
223
+ }
224
+
225
+ /** Map a transport rejection to a timeout, cancellation, or provider error. */
226
+ function transportFailure(error, { label, endpoint, callerSignal, timeoutSignal, timeoutMs }) {
227
+ if (callerSignal?.aborted === true) {
228
+ return new WebError(`${label} aborted`, 'WEB_ABORTED', { cause: callerSignal.reason ?? error });
229
+ }
230
+ if (timeoutSignal?.aborted === true || error?.name === 'TimeoutError') {
231
+ return new WebError(
232
+ `${label} timed out after ${timeoutMs}ms (endpoint ${endpoint}). `
233
+ + 'The Z.ai endpoint did not answer in time; raise timeoutMs in the web-search-zai settings '
234
+ + 'if this is normal for the plan channel.',
235
+ 'WEB_PROVIDER_ERROR',
236
+ { cause: error },
237
+ );
238
+ }
239
+ return new WebError(
240
+ `${label} request failed: ${errorMessage(error)}\n\n`
241
+ + `The request used endpoint ${endpoint}. Check the network, the endpoint setting, the API key, `
242
+ + 'and the Z.ai plan or account balance.',
243
+ 'WEB_PROVIDER_ERROR',
244
+ { cause: error },
245
+ );
246
+ }
247
+
248
+ /** Build the provider error for a non-2xx response, preserving the upstream detail. */
249
+ function upstreamFailure(response, text, label, endpoint) {
250
+ const { detail, code } = upstreamInfo(text);
251
+ const status = `HTTP ${response.status}${isNonBlankString(response.statusText) ? ` ${response.statusText}` : ''}`;
252
+ const hint = code === '1113'
253
+ ? 'the account balance or resource package (code 1113: recharge or activate the GLM plan / web-search resource package)'
254
+ : code === '1000'
255
+ ? 'the API key status or model access (code 1000: the key or model was rejected; check the account plan and regenerate the key if needed)'
256
+ : label.includes('plan') ? 'the Z.ai plan quota' : 'the Z.ai account balance';
257
+ return new WebError(
258
+ `${label} failed (${status}): ${detail === undefined ? 'no response body' : detail}\n\n`
259
+ + `The request used endpoint ${endpoint}. Check the endpoint, ${hint}, and the API key permissions.`,
260
+ 'WEB_PROVIDER_ERROR',
261
+ );
262
+ }
263
+
264
+ /** Pull the most specific message, upstream code, and request id out of an error body. */
265
+ function upstreamInfo(text) {
266
+ const trimmed = typeof text === 'string' ? text.trim() : '';
267
+ if (trimmed.length === 0) return { detail: undefined, code: undefined };
268
+ try {
269
+ const parsed = JSON.parse(trimmed);
270
+ const rawDetail = parsed?.error?.message ?? parsed?.error ?? parsed?.message ?? parsed?.msg ?? parsed?.detail;
271
+ const detailText = isNonBlankString(rawDetail)
272
+ ? rawDetail.trim()
273
+ : rawDetail === undefined || rawDetail === null
274
+ ? undefined
275
+ : previewText(JSON.stringify(rawDetail), MAX_ERROR_BODY_CHARS);
276
+
277
+ const rawCode = parsed?.code ?? parsed?.error?.code ?? parsed?.error?.type;
278
+ const code = rawCode === undefined || rawCode === null || String(rawCode) === '200'
279
+ ? undefined
280
+ : String(rawCode);
281
+
282
+ const parts = [];
283
+ if (code !== undefined) parts.push(`code ${code}`);
284
+ const requestId = parsed?.request_id ?? parsed?.requestId;
285
+ if (isNonBlankString(requestId)) parts.push(`request_id ${requestId.trim()}`);
286
+ if (detailText !== undefined) parts.push(detailText);
287
+ return { detail: parts.length > 0 ? parts.join(' — ') : undefined, code };
288
+ } catch {
289
+ // Not JSON; fall through to the raw preview.
290
+ }
291
+ return { detail: previewText(trimmed, MAX_ERROR_BODY_CHARS), code: undefined };
292
+ }
293
+
294
+ /** Throw when the caller already cancelled, without dispatching a request. */
295
+ function throwIfAborted(signal, label) {
296
+ if (signal?.aborted === true) {
297
+ throw new WebError(`${label} aborted`, 'WEB_ABORTED', { cause: signal.reason });
298
+ }
299
+ }
300
+
301
+ /** Treat a structured abort or an aborted caller signal as cancellation. */
302
+ function isAborted(error, signal) {
303
+ return error?.code === 'WEB_ABORTED' || signal?.aborted === true;
304
+ }
305
+
306
+ /** Coerce an unknown mode to `auto` so a settings typo cannot break every search. */
307
+ function normalizeMode(mode) {
308
+ return SEARCH_MODES.includes(mode) ? mode : 'auto';
309
+ }
310
+
311
+ /** Join a configured base URL with a channel path, tolerating trailing slashes. */
312
+ function joinEndpoint(baseURL, path) {
313
+ const base = isNonBlankString(baseURL) ? baseURL.trim().replace(/\/+$/u, '') : '';
314
+ return `${base}/${path}`;
315
+ }
316
+
317
+ /** Error text for the combined failure message. */
318
+ function errorMessage(error) {
319
+ if (error instanceof Error && isNonBlankString(error.message)) return error.message;
320
+ return String(error);
321
+ }
package/lib/util.js ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Small dependency-free helpers shared by the parser, the two channel
3
+ * backends, and the provider registration.
4
+ *
5
+ * Keeping this module free of host imports lets the fixture tests run with a
6
+ * plain `node --test test/`.
7
+ *
8
+ * @module dsh-web-search-zai/util
9
+ */
10
+
11
+ /** Whether a value is a string that contains at least one non-whitespace character. */
12
+ export function isNonBlankString(value) {
13
+ return typeof value === 'string' && value.trim().length > 0;
14
+ }
15
+
16
+ /** Trimmed string, or `undefined` when the value is missing or blank. */
17
+ export function nonBlank(value) {
18
+ return isNonBlankString(value) ? value.trim() : undefined;
19
+ }
20
+
21
+ /** Whether a value is a plain object (not null, not an array). */
22
+ export function isPlainObject(value) {
23
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
24
+ }
25
+
26
+ /**
27
+ * Whether a value is an absolute http(s) URL. Web-search results must be
28
+ * fetchable links; anything else (`javascript:`, `mailto:`, relative paths)
29
+ * is not a source worth handing to the model.
30
+ */
31
+ export function isWebUrl(value) {
32
+ if (!isNonBlankString(value)) return false;
33
+ const candidate = value.trim();
34
+ if (!URL.canParse(candidate)) return false;
35
+ const { protocol } = new URL(candidate);
36
+ return protocol === 'http:' || protocol === 'https:';
37
+ }
38
+
39
+ /**
40
+ * Normalize a URL for first-wins deduplication: lower-case host, no fragment,
41
+ * no trailing slash. The original URL is kept on the source; only the identity
42
+ * used for deduplication changes.
43
+ *
44
+ * @returns the normalized identity, or `undefined` for an unusable URL.
45
+ */
46
+ export function normalizeUrl(value) {
47
+ if (!isNonBlankString(value)) return undefined;
48
+ let url;
49
+ try {
50
+ url = new URL(value.trim());
51
+ } catch {
52
+ return undefined;
53
+ }
54
+ url.hash = '';
55
+ if (url.pathname.length > 1) url.pathname = url.pathname.replace(/\/+$/u, '');
56
+ const normalized = url.toString();
57
+ return normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
58
+ }
59
+
60
+ /** Deduplicate sources by normalized URL, first occurrence wins. */
61
+ export function dedupeSources(sources) {
62
+ const seen = new Set();
63
+ const unique = [];
64
+ for (const source of sources) {
65
+ const key = normalizeUrl(source?.url);
66
+ if (key === undefined || seen.has(key)) continue;
67
+ seen.add(key);
68
+ unique.push(source);
69
+ }
70
+ return unique;
71
+ }
72
+
73
+ /**
74
+ * Bound a string for an error message or a response preview, appending an
75
+ * ellipsis when the value was cut. Never used for model-facing excerpts.
76
+ */
77
+ export function previewText(value, maxChars = 400) {
78
+ if (typeof value !== 'string') return '';
79
+ const collapsed = value.replace(/\s+/gu, ' ').trim();
80
+ if (collapsed.length <= maxChars) return collapsed;
81
+ return `${collapsed.slice(0, maxChars - 1)}…`;
82
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Z.ai web search",
4
+ "description": "Search the web through a Z.ai / Zhipu GLM plan or the native Z.ai search API."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Z.ai 网页搜索",
4
+ "description": "通过 Z.ai / 智谱 GLM 套餐或原生 Z.ai 搜索 API 进行网页搜索。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,87 @@
1
1
  {
2
2
  "name": "@hexiaowu/dsh-web-search-zai",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Z.ai / Zhipu GLM web-search provider for the DeepSeek Harness ctx.web seam",
5
+ "license": "MIT",
6
+ "author": "hexiaowu",
7
+ "keywords": [
8
+ "dsh",
9
+ "dsh-plugin",
10
+ "deepseek-harness",
11
+ "web-search",
12
+ "zai",
13
+ "zhipu",
14
+ "glm",
15
+ "coding-plan"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "type": "module",
21
+ "main": "./lib/index.js",
22
+ "exports": {
23
+ ".": "./lib/index.js",
24
+ "./client": "./client.js",
25
+ "./package.json": "./package.json",
26
+ "./locale/*.json": "./locale/*.json",
27
+ "./icon": "./icon.svg"
28
+ },
29
+ "files": [
30
+ "lib",
31
+ "client.js",
32
+ "locale/*.json",
33
+ "icon.svg",
34
+ "cordis.patch.yml",
35
+ "README.md",
36
+ "LICENSE",
37
+ "CHANGELOG.md"
38
+ ],
39
+ "engines": {
40
+ "node": "^22.19.0 || >=24.0.0",
41
+ "dsh": ">=0.2.2-rc.1 <0.3.0"
42
+ },
43
+ "dsh": {
44
+ "bundle": {
45
+ "patch": "./cordis.patch.yml"
46
+ },
47
+ "client": {
48
+ "platform": "web",
49
+ "immediately": true,
50
+ "inject": [
51
+ "@deepseek-ai/dsh-api-remotes",
52
+ "@deepseek-ai/dsh-client-locale",
53
+ "@deepseek-ai/dsh-client-ui-settings",
54
+ "@deepseek-ai/dsh-client-ui-settings-general"
55
+ ]
56
+ }
57
+ },
58
+ "scripts": {
59
+ "test": "node --test test/*.test.mjs",
60
+ "probe": "node test/probe.mjs",
61
+ "check": "node --check lib/index.js && node --check client.js && node --test test/*.test.mjs",
62
+ "prepublishOnly": "npm run check"
63
+ },
64
+ "peerDependencies": {
65
+ "@deepseek-ai/cordis": "~4.1.0",
66
+ "@deepseek-ai/schemastery": "~3.19.0",
67
+ "@deepseek-ai/dsh-web": "0.2.2-rc.1",
68
+ "@deepseek-ai/dsh-credentials": "0.2.2-rc.1",
69
+ "@deepseek-ai/dsh-launch-environment": "0.2.2-rc.1"
70
+ },
71
+ "repository": {
72
+ "type": "git",
73
+ "url": "git+https://github.com/hexiaowu/dsh-web-search-zai.git"
74
+ },
75
+ "homepage": "https://github.com/hexiaowu/dsh-web-search-zai#readme",
76
+ "bugs": {
77
+ "url": "https://github.com/hexiaowu/dsh-web-search-zai/issues"
78
+ },
79
+ "devDependencies": {
80
+ "@deepseek-ai/cordis": "4.1.0",
81
+ "@deepseek-ai/dsh-credentials": "0.2.2-rc.1",
82
+ "@deepseek-ai/dsh-launch-environment": "0.2.2-rc.1",
83
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
84
+ "@deepseek-ai/dsh-web": "0.2.2-rc.1",
85
+ "@deepseek-ai/schemastery": "3.19.0"
86
+ }
87
+ }