@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/CHANGELOG.md +25 -0
- package/LICENSE +21 -0
- package/README.md +258 -2
- package/client.js +538 -0
- package/cordis.patch.yml +18 -0
- package/icon.svg +12 -0
- package/lib/index.js +478 -0
- package/lib/parse.js +540 -0
- package/lib/search.js +321 -0
- package/lib/util.js +82 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +85 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Z.ai / Zhipu GLM web-search provider for the `ctx.web` seam.
|
|
3
|
+
*
|
|
4
|
+
* The provider registers as `zai` and owns two channels:
|
|
5
|
+
*
|
|
6
|
+
* - `plan`: the GLM coding-plan Messages endpoint with Anthropic's
|
|
7
|
+
* `web_search_20250305` server tool (spends plan quota).
|
|
8
|
+
* - `api`: the native `/web_search` endpoint (metered per call).
|
|
9
|
+
*
|
|
10
|
+
* `mode: auto` tries the plan channel first and falls back to the native API.
|
|
11
|
+
* If every Z.ai attempt fails (including a missing Z.ai key), the provider can
|
|
12
|
+
* hand the search to the built-in DeepSeek search providers, so `web_search`
|
|
13
|
+
* stays usable instead of going dark. Caller cancellation never falls back.
|
|
14
|
+
*
|
|
15
|
+
* Every setting is volatile, so a change on the Plugins page applies to the
|
|
16
|
+
* next search without restarting the Host; `apply` snapshots the live values at
|
|
17
|
+
* each operation instead of caching them.
|
|
18
|
+
*
|
|
19
|
+
* @module dsh-web-search-zai
|
|
20
|
+
*/
|
|
21
|
+
import z from '@deepseek-ai/schemastery';
|
|
22
|
+
import { credentialRef, isCredentialRefName } from '@deepseek-ai/dsh-credentials';
|
|
23
|
+
import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment';
|
|
24
|
+
import { WebError } from '@deepseek-ai/dsh-web';
|
|
25
|
+
import { runSearch } from './search.js';
|
|
26
|
+
import { isNonBlankString, nonBlank } from './util.js';
|
|
27
|
+
|
|
28
|
+
/** Cordis plugin name used by loader diagnostics. */
|
|
29
|
+
export const name = 'web-search-zai';
|
|
30
|
+
|
|
31
|
+
/** The web seam this provider registers into. */
|
|
32
|
+
export const inject = ['web'];
|
|
33
|
+
|
|
34
|
+
/** Provider id this plugin registers under. Must not collide with built-ins. */
|
|
35
|
+
const PROVIDER_ID = 'zai';
|
|
36
|
+
|
|
37
|
+
const DEFAULT_API_KEY_ENV = 'ZAI_CODING_CN_API_KEY';
|
|
38
|
+
const DEFAULT_MODEL = 'glm-4.6';
|
|
39
|
+
const DEFAULT_API_VERSION = '2023-06-01';
|
|
40
|
+
const DEFAULT_SEARCH_ENGINE = 'search_std';
|
|
41
|
+
/** Built-in search providers that can stand in when Z.ai is entirely down. */
|
|
42
|
+
const DEFAULT_FALLBACK_PROVIDERS = 'deepseek-official,deepseek-search-api';
|
|
43
|
+
/** Local-only HTTP endpoint behind the Settings page's Test button. */
|
|
44
|
+
const TEST_ROUTE_PATH = '/dsh-web-search-zai/test';
|
|
45
|
+
/** Local-only endpoint that reveals the current key to the Settings page. */
|
|
46
|
+
const KEY_ROUTE_PATH = '/dsh-web-search-zai/key';
|
|
47
|
+
/** Fixed test query: the point is reachability, not a user-facing search. */
|
|
48
|
+
const TEST_QUERY = '今天的人工智能新闻';
|
|
49
|
+
/** Keep the test cheap: one search, at most three sources. */
|
|
50
|
+
const TEST_MAX_RESULTS = 3;
|
|
51
|
+
/** Bound the whole test, including a slow plan call and its fallback. */
|
|
52
|
+
const TEST_TIMEOUT_MS = 45000;
|
|
53
|
+
const DEFAULT_ENDPOINTS = Object.freeze({
|
|
54
|
+
cn: Object.freeze({
|
|
55
|
+
plan: 'https://open.bigmodel.cn/api/anthropic/v1',
|
|
56
|
+
api: 'https://open.bigmodel.cn/api/paas/v4',
|
|
57
|
+
}),
|
|
58
|
+
global: Object.freeze({
|
|
59
|
+
plan: 'https://api.z.ai/api/anthropic/v1',
|
|
60
|
+
api: 'https://api.z.ai/api/paas/v4',
|
|
61
|
+
}),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Every field is `.volatile()`: the Settings/Plugins form writes it, the
|
|
66
|
+
* Host re-runs `apply` only for structural changes, and this plugin reads the
|
|
67
|
+
* live value on every search (`config.<field>.get()`).
|
|
68
|
+
*
|
|
69
|
+
* `region` picks the endpoint pair; an explicit `planBaseURL`/`apiBaseURL`
|
|
70
|
+
* wins over it. `apiKey` is the literal escape hatch; `apiKeyEnv` names a
|
|
71
|
+
* credential reference resolved per search.
|
|
72
|
+
*/
|
|
73
|
+
export const Config = z.object({
|
|
74
|
+
mode: z.string().default('auto').volatile(),
|
|
75
|
+
region: z.string().default('cn').volatile(),
|
|
76
|
+
planBaseURL: z.string().volatile(),
|
|
77
|
+
apiBaseURL: z.string().volatile(),
|
|
78
|
+
apiKey: z.string().role('secret').volatile(),
|
|
79
|
+
apiKeyEnv: z.string().role('credential-ref').default(DEFAULT_API_KEY_ENV).volatile(),
|
|
80
|
+
model: z.string().default(DEFAULT_MODEL).volatile(),
|
|
81
|
+
apiVersion: z.string().default(DEFAULT_API_VERSION).volatile(),
|
|
82
|
+
maxTokens: z.number().step(1).min(1).default(4096).volatile(),
|
|
83
|
+
maxUses: z.number().step(1).min(1).default(3).volatile(),
|
|
84
|
+
searchEngine: z.string().default(DEFAULT_SEARCH_ENGINE).volatile(),
|
|
85
|
+
count: z.number().step(1).min(1).max(50).default(10).volatile(),
|
|
86
|
+
timeoutMs: z.number().step(1).min(1000).default(25000).volatile(),
|
|
87
|
+
fallbackEnabled: z.boolean().default(true).volatile(),
|
|
88
|
+
fallbackProviders: z.string().default(DEFAULT_FALLBACK_PROVIDERS).volatile(),
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Register the provider with `ctx.web`.
|
|
93
|
+
*
|
|
94
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - the plugin context.
|
|
95
|
+
* @param {any} config - the validated row config; fields are live getters.
|
|
96
|
+
*/
|
|
97
|
+
export function apply(ctx, config) {
|
|
98
|
+
/** Snapshot the currently effective settings; never cache across operations. */
|
|
99
|
+
const options = () => snapshotOptions(config);
|
|
100
|
+
|
|
101
|
+
ctx.web.registerSearchProvider({
|
|
102
|
+
id: PROVIDER_ID,
|
|
103
|
+
// Synchronous and purely local: the seam calls this while selecting.
|
|
104
|
+
// A broken Z.ai config still counts as selectable while a fallback works.
|
|
105
|
+
available: () => {
|
|
106
|
+
const snapshot = options();
|
|
107
|
+
return isAvailable(snapshot) || hasUsableFallback(ctx, snapshot);
|
|
108
|
+
},
|
|
109
|
+
// Presence only — no network, because the Host calls it before every model step.
|
|
110
|
+
// A missing Z.ai key still admits the tool when DeepSeek can stand in.
|
|
111
|
+
ready: (llmProvider) => isSearchReady(ctx, options(), llmProvider),
|
|
112
|
+
search: async (request, signal) => {
|
|
113
|
+
const snapshot = options();
|
|
114
|
+
let zaiFailure;
|
|
115
|
+
try {
|
|
116
|
+
const apiKey = await resolveApiKey(ctx, snapshot, signal);
|
|
117
|
+
return await runSearch({
|
|
118
|
+
query: request?.query,
|
|
119
|
+
options: snapshot,
|
|
120
|
+
apiKey,
|
|
121
|
+
signal,
|
|
122
|
+
});
|
|
123
|
+
} catch (error) {
|
|
124
|
+
// A cancelled call is final: never spend another provider's quota.
|
|
125
|
+
if (isAbort(error, signal)) throw error;
|
|
126
|
+
zaiFailure = error;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (!snapshot.fallbackEnabled) throw zaiFailure;
|
|
130
|
+
return await searchFallback(ctx, snapshot, request, signal, zaiFailure);
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
registerTestRoute(ctx, options);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Register the Plugins page's "Test" endpoint. It uses the same `ctx.web.seam`
|
|
139
|
+
* as the model's tool, so it exercises the configured Z.ai channels and the
|
|
140
|
+
* DeepSeek fallback rather than a separate probe. Local requests only.
|
|
141
|
+
*/
|
|
142
|
+
function registerTestRoute(ctx, options) {
|
|
143
|
+
const register = (webServer) => {
|
|
144
|
+
const test = webServer.register({
|
|
145
|
+
kind: 'exact',
|
|
146
|
+
path: TEST_ROUTE_PATH,
|
|
147
|
+
handler: (request, response) => {
|
|
148
|
+
void handleTestRequest(ctx, request, response);
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
const key = webServer.register({
|
|
152
|
+
kind: 'exact',
|
|
153
|
+
path: KEY_ROUTE_PATH,
|
|
154
|
+
handler: (request, response) => {
|
|
155
|
+
void handleKeyRequest(ctx, options, request, response);
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
return () => {
|
|
159
|
+
test();
|
|
160
|
+
key();
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
// `webServer` may activate after this plugin: wait for it instead of reading
|
|
165
|
+
// `ctx.get` once at apply time. A headless composition never gets the service,
|
|
166
|
+
// and the search provider still works without the local endpoints.
|
|
167
|
+
if (typeof ctx.inject === 'function') {
|
|
168
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
169
|
+
webCtx.effect(() => register(webCtx.webServer), 'dsh-web-search-zai: local endpoints');
|
|
170
|
+
});
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const webServer = ctx.get('webServer');
|
|
175
|
+
if (webServer === undefined || typeof webServer.register !== 'function') return;
|
|
176
|
+
ctx.effect(() => register(webServer), 'dsh-web-search-zai: local endpoints');
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Write one JSON response (never cached, never headers already sent). */
|
|
180
|
+
function sendJson(response, status, body) {
|
|
181
|
+
if (response.writableEnded === true) return;
|
|
182
|
+
response.writeHead(status, {
|
|
183
|
+
'content-type': 'application/json; charset=utf-8',
|
|
184
|
+
'cache-control': 'no-store',
|
|
185
|
+
});
|
|
186
|
+
response.end(JSON.stringify(body));
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Reveal the current key to the Settings page. The user explicitly asked to see
|
|
191
|
+
* the value; the endpoint is loopback-only, uncached, and never logs the key.
|
|
192
|
+
*/
|
|
193
|
+
async function handleKeyRequest(ctx, options, request, response) {
|
|
194
|
+
if (request.method !== 'GET') {
|
|
195
|
+
sendJson(response, 405, { ok: false, message: 'GET only' });
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (!isLoopbackAddress(request.socket?.remoteAddress)) {
|
|
199
|
+
sendJson(response, 403, { ok: false, message: 'local access only' });
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
const apiKey = await resolveApiKey(ctx, options(), undefined);
|
|
204
|
+
sendJson(response, 200, { ok: true, apiKey });
|
|
205
|
+
} catch (error) {
|
|
206
|
+
sendJson(response, 200, {
|
|
207
|
+
ok: false,
|
|
208
|
+
code: error?.code,
|
|
209
|
+
message: messageOf(error),
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Answer one test request with a compact success or the full error. */
|
|
215
|
+
async function handleTestRequest(ctx, request, response) {
|
|
216
|
+
if (request.method !== 'GET') {
|
|
217
|
+
sendJson(response, 405, { ok: false, message: 'GET only' });
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (!isLoopbackAddress(request.socket?.remoteAddress)) {
|
|
221
|
+
sendJson(response, 403, { ok: false, message: 'local access only' });
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
try {
|
|
226
|
+
const result = await ctx.web.search(
|
|
227
|
+
{ query: TEST_QUERY, maxResults: TEST_MAX_RESULTS },
|
|
228
|
+
AbortSignal.timeout(TEST_TIMEOUT_MS),
|
|
229
|
+
);
|
|
230
|
+
sendJson(response, 200, {
|
|
231
|
+
ok: true,
|
|
232
|
+
query: TEST_QUERY,
|
|
233
|
+
count: result.sources.length,
|
|
234
|
+
truncated: result.truncated === true,
|
|
235
|
+
firstTitle: result.sources[0]?.title,
|
|
236
|
+
firstUrl: result.sources[0]?.url,
|
|
237
|
+
sources: result.sources.slice(0, 3).map((source) => ({
|
|
238
|
+
title: source.title,
|
|
239
|
+
url: source.url,
|
|
240
|
+
})),
|
|
241
|
+
});
|
|
242
|
+
} catch (error) {
|
|
243
|
+
sendJson(response, 200, {
|
|
244
|
+
ok: false,
|
|
245
|
+
query: TEST_QUERY,
|
|
246
|
+
code: error?.code,
|
|
247
|
+
message: messageOf(error),
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Loopback-only guard for the test endpoint. */
|
|
253
|
+
function isLoopbackAddress(address) {
|
|
254
|
+
if (typeof address !== 'string') return false;
|
|
255
|
+
const normalized = address.toLowerCase();
|
|
256
|
+
return normalized === '::1'
|
|
257
|
+
|| normalized === '::ffff:127.0.0.1'
|
|
258
|
+
|| normalized.startsWith('127.');
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Project the live config getters into the plain options one operation uses. */
|
|
262
|
+
function snapshotOptions(config) {
|
|
263
|
+
const region = config.region.get() === 'global' ? 'global' : 'cn';
|
|
264
|
+
const endpoints = DEFAULT_ENDPOINTS[region];
|
|
265
|
+
return {
|
|
266
|
+
mode: config.mode.get(),
|
|
267
|
+
region,
|
|
268
|
+
planBaseURL: nonBlank(config.planBaseURL.get()) ?? endpoints.plan,
|
|
269
|
+
apiBaseURL: nonBlank(config.apiBaseURL.get()) ?? endpoints.api,
|
|
270
|
+
apiKey: nonBlank(config.apiKey.get()),
|
|
271
|
+
apiKeyEnv: nonBlank(config.apiKeyEnv.get()) ?? DEFAULT_API_KEY_ENV,
|
|
272
|
+
model: nonBlank(config.model.get()) ?? DEFAULT_MODEL,
|
|
273
|
+
apiVersion: nonBlank(config.apiVersion.get()) ?? DEFAULT_API_VERSION,
|
|
274
|
+
maxTokens: config.maxTokens.get(),
|
|
275
|
+
maxUses: config.maxUses.get(),
|
|
276
|
+
searchEngine: nonBlank(config.searchEngine.get()) ?? DEFAULT_SEARCH_ENGINE,
|
|
277
|
+
count: config.count.get(),
|
|
278
|
+
timeoutMs: config.timeoutMs.get(),
|
|
279
|
+
fallbackEnabled: config.fallbackEnabled.get() !== false,
|
|
280
|
+
fallbackProviders: nonBlank(config.fallbackProviders.get()) ?? DEFAULT_FALLBACK_PROVIDERS,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Keep a malformed row from being selected and failing every search later. */
|
|
285
|
+
function isAvailable(options) {
|
|
286
|
+
return URL.canParse(options.planBaseURL)
|
|
287
|
+
&& URL.canParse(options.apiBaseURL)
|
|
288
|
+
&& Number.isInteger(options.maxTokens)
|
|
289
|
+
&& options.maxTokens > 0
|
|
290
|
+
&& Number.isInteger(options.timeoutMs)
|
|
291
|
+
&& options.timeoutMs > 0;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Whether the next search would have a credential. Reads only presence from
|
|
296
|
+
* the credential store (never the value) and never touches the network.
|
|
297
|
+
*/
|
|
298
|
+
async function isKeyConfigured(ctx, options) {
|
|
299
|
+
if (options.apiKey !== undefined) return true;
|
|
300
|
+
const ref = toCredentialRef(options.apiKeyEnv);
|
|
301
|
+
if (ref === undefined) return false;
|
|
302
|
+
|
|
303
|
+
const credentials = ctx.get('credentials');
|
|
304
|
+
if (credentials === undefined) {
|
|
305
|
+
return isNonBlankString(launchEnvironmentOf(ctx).get(ref)?.value);
|
|
306
|
+
}
|
|
307
|
+
try {
|
|
308
|
+
return (await credentials.describe(ref)).configured === true;
|
|
309
|
+
} catch {
|
|
310
|
+
return false;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Whether the tool should stay admitted: Z.ai has a key, or a built-in
|
|
316
|
+
* fallback provider is registered, available, and reports a credential.
|
|
317
|
+
* No network; the Host calls this before every model step.
|
|
318
|
+
*/
|
|
319
|
+
async function isSearchReady(ctx, options, llmProvider) {
|
|
320
|
+
if (await isKeyConfigured(ctx, options)) return true;
|
|
321
|
+
if (!options.fallbackEnabled) return false;
|
|
322
|
+
for (const { provider } of fallbackProviders(ctx, options)) {
|
|
323
|
+
if (provider === undefined || !providerAvailable(provider)) continue;
|
|
324
|
+
if (provider.ready === undefined) return true;
|
|
325
|
+
try {
|
|
326
|
+
if (await provider.ready(llmProvider)) return true;
|
|
327
|
+
} catch {
|
|
328
|
+
// Try the next fallback.
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Whether at least one configured fallback provider can currently be selected. */
|
|
335
|
+
function hasUsableFallback(ctx, options) {
|
|
336
|
+
if (!options.fallbackEnabled) return false;
|
|
337
|
+
return fallbackProviders(ctx, options).some(({ provider }) => providerAvailable(provider));
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Run the same search through the configured built-in providers after every
|
|
342
|
+
* Z.ai attempt failed. Providers already registered on the seam are called
|
|
343
|
+
* directly, so this never re-enters `ctx.web.search()` or the `zai` provider.
|
|
344
|
+
*/
|
|
345
|
+
async function searchFallback(ctx, options, request, signal, zaiFailure) {
|
|
346
|
+
const candidates = fallbackProviders(ctx, options);
|
|
347
|
+
// No fallback route exists at all: preserve the original Z.ai error and code
|
|
348
|
+
// (for example CREDENTIAL_MISSING) instead of wrapping it as a fallback failure.
|
|
349
|
+
if (!candidates.some(({ provider }) => provider !== undefined)) throw zaiFailure;
|
|
350
|
+
|
|
351
|
+
const failures = [`${PROVIDER_ID}: ${messageOf(zaiFailure)}`];
|
|
352
|
+
for (const { id, provider } of candidates) {
|
|
353
|
+
if (provider === undefined) {
|
|
354
|
+
failures.push(`${id}: not registered`);
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
if (!providerAvailable(provider)) {
|
|
358
|
+
failures.push(`${id}: unavailable`);
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
if (provider.ready !== undefined) {
|
|
362
|
+
try {
|
|
363
|
+
if (!(await provider.ready())) {
|
|
364
|
+
failures.push(`${id}: not ready (credential missing)`);
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
} catch (error) {
|
|
368
|
+
failures.push(`${id}: readiness check failed: ${messageOf(error)}`);
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
const result = await provider.search(request, signal);
|
|
374
|
+
if (result === undefined || result === null || !Array.isArray(result.sources)) {
|
|
375
|
+
failures.push(`${id}: returned no search result`);
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
return result;
|
|
379
|
+
} catch (error) {
|
|
380
|
+
if (isAbort(error, signal)) throw error;
|
|
381
|
+
failures.push(`${id}: ${messageOf(error)}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
throw new WebError(
|
|
386
|
+
'Z.ai web search failed, and every fallback provider also failed.\n'
|
|
387
|
+
+ failures.map((line) => `- ${line}`).join('\n')
|
|
388
|
+
+ '\n\nSet fallbackEnabled=false in the web-search-zai settings to fail on Z.ai alone, '
|
|
389
|
+
+ 'or fix the credentials/quotas named above.',
|
|
390
|
+
'WEB_PROVIDER_ERROR',
|
|
391
|
+
{ cause: zaiFailure },
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Registered fallback providers named by the config, in configured order. */
|
|
396
|
+
function fallbackProviders(ctx, options) {
|
|
397
|
+
const providers = ctx.web?.searchProviders;
|
|
398
|
+
if (!(providers instanceof Map)) return [];
|
|
399
|
+
const seen = new Set();
|
|
400
|
+
const candidates = [];
|
|
401
|
+
for (const raw of String(options.fallbackProviders ?? '').split(',')) {
|
|
402
|
+
const id = raw.trim();
|
|
403
|
+
if (id.length === 0 || id === PROVIDER_ID || seen.has(id)) continue;
|
|
404
|
+
seen.add(id);
|
|
405
|
+
candidates.push({ id, provider: providers.get(id) });
|
|
406
|
+
}
|
|
407
|
+
return candidates;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Defensive `available()` check for another provider. */
|
|
411
|
+
function providerAvailable(provider) {
|
|
412
|
+
try {
|
|
413
|
+
return typeof provider?.available === 'function' && provider.available() === true;
|
|
414
|
+
} catch {
|
|
415
|
+
return false;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** A cancelled call is final; do not spend another provider's quota. */
|
|
420
|
+
function isAbort(error, signal) {
|
|
421
|
+
return error?.code === 'WEB_ABORTED' || signal?.aborted === true;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Resolve the key for exactly this operation, in the same order the official
|
|
426
|
+
* provider uses: literal config first, then the credential store, then the
|
|
427
|
+
* launching environment. A rotated key therefore reaches the next search
|
|
428
|
+
* without a restart.
|
|
429
|
+
*/
|
|
430
|
+
async function resolveApiKey(ctx, options, signal) {
|
|
431
|
+
throwIfAborted(signal);
|
|
432
|
+
if (options.apiKey !== undefined) return options.apiKey;
|
|
433
|
+
|
|
434
|
+
const ref = toCredentialRef(options.apiKeyEnv);
|
|
435
|
+
let value;
|
|
436
|
+
if (ref !== undefined) {
|
|
437
|
+
const credentials = ctx.get('credentials');
|
|
438
|
+
if (credentials !== undefined) {
|
|
439
|
+
try {
|
|
440
|
+
value = (await credentials.resolve(ref))?.value;
|
|
441
|
+
} catch (error) {
|
|
442
|
+
throwIfAborted(signal);
|
|
443
|
+
throw new WebError(
|
|
444
|
+
`Z.ai web search could not read credential "${ref}": ${messageOf(error)}`,
|
|
445
|
+
'WEB_PROVIDER_ERROR',
|
|
446
|
+
{ cause: error },
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
throwIfAborted(signal);
|
|
451
|
+
if (!isNonBlankString(value)) value = launchEnvironmentOf(ctx).get(ref)?.value;
|
|
452
|
+
}
|
|
453
|
+
if (isNonBlankString(value)) return value.trim();
|
|
454
|
+
|
|
455
|
+
throw new WebError(
|
|
456
|
+
`Z.ai web search has no API key for "${options.apiKeyEnv}". `
|
|
457
|
+
+ 'Store it as that reference in the DSH credential store (the `refs:` section of ~/.dsh/.credentials.yaml, '
|
|
458
|
+
+ 'chmod 600), export it in the launching environment, or set the literal "apiKey" in the '
|
|
459
|
+
+ 'web-search-zai plugin settings.',
|
|
460
|
+
'WEB_PROVIDER_CREDENTIAL_MISSING',
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Brand a configured reference, or `undefined` when the row names none. */
|
|
465
|
+
function toCredentialRef(value) {
|
|
466
|
+
if (!isNonBlankString(value) || !isCredentialRefName(value)) return undefined;
|
|
467
|
+
return credentialRef(value);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function throwIfAborted(signal) {
|
|
471
|
+
if (signal?.aborted === true) {
|
|
472
|
+
throw new WebError('Z.ai web search aborted', 'WEB_ABORTED', { cause: signal.reason });
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function messageOf(error) {
|
|
477
|
+
return error instanceof Error && isNonBlankString(error.message) ? error.message : String(error);
|
|
478
|
+
}
|