@deepseek-ai/dsh-web-deepseek-api 0.2.2-rc.1 → 0.2.2-rc.3

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/index.js CHANGED
@@ -1,76 +1,60 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
2
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
3
3
  import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
4
+ import { deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey } from "@deepseek-ai/dsh-llm-deepseek";
5
+ import { plainAccountOptions, resolveAccountOptions } from "@deepseek-ai/dsh-llm-deepseek-account";
6
+ import { plainOptions, resolveAdapterOptions } from "@deepseek-ai/dsh-llm-deepseek-api-key";
4
7
  import { WebError } from "@deepseek-ai/dsh-web";
5
8
  //#region lib/types/transport.js
6
- const ACCOUNT_PROVIDER = "deepseek-account";
7
9
  const USER_AGENT = "deepseek-harness/0.0.1";
8
10
  /**
9
- * Resolve credential sources for one operation without retaining secret values.
10
- * @param ctx - Provider context with request routing and credential services.
11
- * @param config - Literal key and credential reference from the settings snapshot.
12
- * @returns Authentication sources for one operation.
11
+ * Check synchronously whether an operation has a source to try, without reading credentials.
12
+ * @param auth - Sources for the operation.
13
+ * @returns Whether any source is an account, a credential reference, a non-empty literal key, or a misconfigured source
14
+ * the operation reports.
13
15
  */
14
- function deepSeekWebAuth(ctx, config) {
15
- const apiKeyEnv = credentialRef(config.apiKeyEnv);
16
- const literalApiKey = config.apiKey !== void 0 && config.apiKey.length > 0 ? config.apiKey : void 0;
17
- return {
18
- ...literalApiKey === void 0 ? {} : { apiKey: literalApiKey },
19
- resolveAccountToken: async (endpoint) => {
20
- if (ctx.get("agents")?.currentInitiator()?.session.requestContext()?.provider !== ACCOUNT_PROVIDER) return void 0;
21
- return await ctx.get("deepseekAccount")?.resolveToken(endpoint);
22
- },
23
- resolveApiKey: async () => {
24
- const credentials = ctx.get("credentials");
25
- if (credentials !== void 0) return (await credentials.resolve(apiKeyEnv))?.value;
26
- const ambient = launchEnvironmentOf(ctx).get(apiKeyEnv);
27
- return ambient !== void 0 && ambient.value.length > 0 ? ambient.value : void 0;
28
- },
29
- apiKeyEnv
30
- };
16
+ function hasDeepSeekWebCredential(auth) {
17
+ return auth.sources.some((source) => source.kind !== "api-key" || typeof source.key !== "string" || source.key.length > 0);
31
18
  }
32
19
  /**
33
- * Whether an operation for a model request on `route` has a credential, checked in the order the
34
- * operation resolves them: the account token first on the account route, then the API key. A failed
35
- * read answers false, because the operation fails on that read instead of trying the next credential.
36
- * Only presence is checked: the key's value is not read and the endpoint is not contacted, so a wrong
37
- * key still counts as configured.
38
- * @param ctx - Provider context with the account, credential, and environment planes.
39
- * @param config - Literal key, credential reference, and API base from the settings snapshot.
40
- * @param route - Provider route of the model request being prepared.
41
- * @returns Whether the account token or an API key is available to that operation.
20
+ * Check whether an operation would find a credential, reading the sources in the order {@link dispatchDeepSeekWeb}
21
+ * does. An account source reads its token for the operation's endpoint; a referenced key is only checked for presence,
22
+ * so a malformed or wrong key counts as ready. A misconfigured source or a failed read answers false without reading
23
+ * later sources, because the operation fails there too. Nothing is sent and nothing is retained.
24
+ * @param auth - Sources for the operation.
25
+ * @param path - Operation path appended to each source's base.
26
+ * @returns Whether a source before any misconfigured or unreadable one is present.
42
27
  */
43
- async function deepSeekWebCredentialReady(ctx, config, route) {
44
- const account = ctx.get("deepseekAccount");
45
- if (route === ACCOUNT_PROVIDER && account !== void 0) {
46
- let token;
47
- try {
48
- token = await account.resolveToken(config.baseURL);
49
- } catch (_unreadableGrant) {
50
- return false;
28
+ async function isDeepSeekWebAuthReady(auth, path) {
29
+ for (const source of auth.sources) switch (source.kind) {
30
+ case "misconfigured": return false;
31
+ case "account": {
32
+ let token;
33
+ try {
34
+ token = await source.resolveToken(joinPath(source.baseURL, path));
35
+ } catch (_unreadableGrant) {
36
+ return false;
37
+ }
38
+ if (token !== void 0 && token.length > 0) return true;
39
+ break;
51
40
  }
52
- if (token !== void 0 && token.length > 0) return true;
53
- }
54
- if (config.apiKey !== void 0 && config.apiKey.length > 0) return true;
55
- const apiKeyEnv = credentialRef(config.apiKeyEnv);
56
- const credentials = ctx.get("credentials");
57
- if (credentials === void 0) {
58
- const ambient = launchEnvironmentOf(ctx).get(apiKeyEnv);
59
- return ambient !== void 0 && ambient.value.length > 0;
60
- }
61
- try {
62
- return (await credentials.describe(apiKeyEnv)).configured;
63
- } catch (_unreadableStore) {
64
- return false;
41
+ case "api-key": {
42
+ const { key } = source;
43
+ if (typeof key === "string") {
44
+ if (key.length > 0) return true;
45
+ break;
46
+ }
47
+ try {
48
+ if (await key.configured()) return true;
49
+ } catch (_unreadableStore) {
50
+ return false;
51
+ }
52
+ break;
53
+ }
54
+ /* v8 ignore next -- the switch is exhaustive. */
55
+ default: return assertNever$1(source);
65
56
  }
66
- }
67
- /**
68
- * Check whether an authentication source exists; does not resolve credentials.
69
- * @param auth - Sources for the operation.
70
- * @returns Whether a literal key or resolver is present.
71
- */
72
- function hasDeepSeekWebCredential(auth) {
73
- return (auth.apiKey?.length ?? 0) > 0 || auth.resolveApiKey !== void 0 || auth.resolveAccountToken !== void 0;
57
+ return false;
74
58
  }
75
59
  /** Narrow a remote JSON object.
76
60
  * @param value - Untrusted JSON.
@@ -85,15 +69,17 @@ function isRecord(value) {
85
69
  function invalidResponse() {
86
70
  return new WebError("DeepSeek returned an invalid response body", "WEB_PROVIDER_ERROR");
87
71
  }
88
- /** Dispatch one operation using a single settings and credential snapshot.
89
- * @param options - Authentication sources for this operation.
90
- * @param request - Resolved endpoint, JSON payload, and response decoder.
72
+ /** Dispatch one operation using a single settings and credential snapshot: one request, with the first present source.
73
+ * @param options - Ordered authentication sources for this operation.
74
+ * @param request - Operation path, JSON payload, and response decoder.
91
75
  * @param signal - Caller cancellation signal.
92
76
  * @returns The validated provider result.
93
77
  */
94
78
  async function dispatchDeepSeekWeb(options, request, signal) {
95
- const { endpoint, body, decode, recordRequest, guidance } = request;
79
+ const { body, decode, recordRequest, guidance } = request;
96
80
  const auth = await authHeaders(options, request, signal);
81
+ const { endpoint } = auth;
82
+ await request.waitToSend?.(signal);
97
83
  throwIfSearchAborted(signal);
98
84
  recordRequest?.(endpoint);
99
85
  throwIfSearchAborted(signal);
@@ -119,6 +105,7 @@ async function dispatchDeepSeekWeb(options, request, signal) {
119
105
  if (!response.ok) {
120
106
  const status = response.status;
121
107
  let message = `DeepSeek API error (HTTP ${status})`;
108
+ let aborted;
122
109
  try {
123
110
  const parsed = await response.json();
124
111
  if (isRecord(parsed)) {
@@ -126,9 +113,15 @@ async function dispatchDeepSeekWeb(options, request, signal) {
126
113
  if (typeof detail === "string" && detail.length > 0) message += `: ${detail}`;
127
114
  }
128
115
  } catch (error) {
129
- if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error);
116
+ if (signal?.aborted === true || isAbortError(error)) aborted = searchAborted(signal, error);
117
+ }
118
+ if (status === 401 && auth.kind === "account") {
119
+ try {
120
+ await auth.reject?.();
121
+ } catch (_credentialRemovalFailed) {}
122
+ throw aborted ?? accountRejectedError(message);
130
123
  }
131
- if (status === 401 && auth.kind === "account") throw accountRejectedError(message);
124
+ if (aborted !== void 0) throw aborted;
132
125
  throw searchEndpointError(guidance, endpoint, message);
133
126
  }
134
127
  try {
@@ -146,53 +139,77 @@ function accountRejectedError(message) {
146
139
  }
147
140
  /**
148
141
  * Add endpoint recovery instructions to failures that occur after request dispatch begins.
149
- * @param options - the plugin, settings field, and settings page the guidance names.
142
+ * @param options - the plugin and settings fields the guidance names.
150
143
  * @param endpoint - the dispatched endpoint.
151
144
  * @param message - the failure description.
152
145
  * @param cause - the underlying failure, when one exists.
153
146
  * @returns the provider failure with recovery instructions.
154
147
  */
155
148
  function searchEndpointError(options, endpoint, message, cause) {
156
- return new WebError(`${message}\n\nThe web request used endpoint ${JSON.stringify(endpoint)}. ${options.subject} endpoint configuration is separate from chat. If that endpoint is not intended, guide the user to Plugins > Built-in plugin settings > ${options.page}, where they can change and save ${options.label}. If that settings page is unavailable, the user can set ${options.plugin}.${options.field} to a trusted DeepSeek endpoint. Only the user should choose or change the endpoint.`, "WEB_PROVIDER_ERROR", cause === void 0 ? void 0 : { cause });
149
+ const { subject, plugin } = options;
150
+ const baseURLField = `${plugin}.${options.baseURLField}`, apiKeyEnvField = `${plugin}.${options.apiKeyEnvField}`;
151
+ const recovery = options.custom ? `${subject} sends the API key under ${apiKeyEnvField} to ${baseURLField}. If that endpoint is not intended, guide the user to correct ${baseURLField} and ${apiKeyEnvField}, or to remove both so ${subject} uses the DeepSeek credential of the conversation.` : `${subject} derives this endpoint from the base URL of the DeepSeek model provider whose credential it uses. If that endpoint is not intended, guide the user to check that provider's base URL on the Models page, or to set ${baseURLField} to a trusted DeepSeek endpoint and ${apiKeyEnvField} to the credential reference of its API key.`;
152
+ return new WebError(`${message}\n\nThe web request used endpoint ${JSON.stringify(endpoint)}. ${recovery} Only the user should choose or change the endpoint.`, "WEB_PROVIDER_ERROR", cause === void 0 ? void 0 : { cause });
157
153
  }
158
154
  /**
159
155
  * Resolve one operation's authentication headers without retaining a credential on the provider.
160
- * @param options - the caller's snapshot, so the credential and the endpoint it is sent to come from one section.
161
- * @param request - the resolved request; its endpoint scopes the account token.
156
+ * @param auth - the caller's ordered sources, each binding its credential to the base it is sent to.
157
+ * @param request - the resolved request; its path under the source's base is the endpoint.
162
158
  * @param signal - abort signal for the surrounding operation.
163
- * @returns the account-token header when one resolves, otherwise the API-key headers, tagged by credential kind.
159
+ * @returns the headers and endpoint of the first present source, tagged by credential kind.
160
+ * @throws {@link WebError} `WEB_PROVIDER_MISCONFIGURED` at a misconfigured source, `WEB_PROVIDER_ERROR` when a read
161
+ * fails, `WEB_ABORTED` on cancellation, and `WEB_PROVIDER_CREDENTIAL_MISSING` when no source is present.
164
162
  */
165
- async function authHeaders(options, request, signal) {
166
- const { resolveAccountToken } = options;
167
- const token = resolveAccountToken === void 0 ? void 0 : await resolveCredential(() => resolveAccountToken(request.endpoint), signal);
168
- if (token !== void 0 && token.length > 0) return {
169
- kind: "account",
170
- headers: { "x-dsh-auth-token": token }
171
- };
172
- const apiKey = await resolveApiKey(options, request.guidance.plugin, signal);
173
- return {
174
- kind: "api-key",
175
- headers: {
176
- ...request.apiKeyHeaders?.(apiKey),
177
- "authorization": `Bearer ${apiKey}`
163
+ async function authHeaders(auth, request, signal) {
164
+ throwIfSearchAborted(signal);
165
+ for (const source of auth.sources) {
166
+ throwIfSearchAborted(signal);
167
+ switch (source.kind) {
168
+ case "misconfigured": throw new WebError(source.message, "WEB_PROVIDER_MISCONFIGURED");
169
+ case "account": {
170
+ const endpoint = joinPath(source.baseURL, request.path);
171
+ const token = await resolveCredential(() => source.resolveToken(endpoint), signal);
172
+ if (token !== void 0 && token.length > 0) return {
173
+ kind: "account",
174
+ endpoint,
175
+ headers: { "x-dsh-auth-token": token },
176
+ reject: async () => {
177
+ await source.rejectToken(token);
178
+ }
179
+ };
180
+ break;
181
+ }
182
+ case "api-key": {
183
+ const { key } = source;
184
+ let apiKey;
185
+ if (typeof key === "string") apiKey = key;
186
+ else apiKey = await resolveCredential(key.resolve, signal);
187
+ if (apiKey !== void 0 && apiKey.length > 0) return {
188
+ kind: "api-key",
189
+ endpoint: joinPath(source.baseURL, request.path),
190
+ headers: {
191
+ ...request.apiKeyHeaders?.(apiKey),
192
+ "authorization": `Bearer ${apiKey}`
193
+ }
194
+ };
195
+ break;
196
+ }
197
+ /* v8 ignore next -- the switch is exhaustive. */
198
+ default: return assertNever$1(source);
178
199
  }
179
- };
200
+ }
201
+ throw new WebError(auth.missingCredentialMessage ?? "DeepSeek web access has no credential to send", "WEB_PROVIDER_CREDENTIAL_MISSING");
180
202
  }
181
- /**
182
- * Resolve one operation's API key without retaining it on the provider.
183
- * @param options - the caller's snapshot, so the key and the endpoint it is sent to come from one section.
184
- * @param plugin - configuration namespace named by the missing-key diagnostic.
185
- * @param signal - abort signal for the surrounding operation.
186
- * @returns the resolved key.
187
- */
188
- async function resolveApiKey(options, plugin, signal) {
189
- throwIfSearchAborted(signal);
190
- if (options.apiKey !== void 0 && options.apiKey.length > 0) return options.apiKey;
191
- const { resolveApiKey } = options;
192
- const resolved = resolveApiKey === void 0 ? void 0 : await resolveCredential(resolveApiKey, signal);
193
- if (resolved !== void 0 && resolved.length > 0) return resolved;
194
- throw new WebError(`DeepSeek web access has no API key for "${options.apiKeyEnv ?? "DEEPSEEK_API_KEY"}"; store it through the credentials service (the web Models page writes it), export it in the launching environment, or set a literal "apiKey" in the ${plugin} config; a conversation using a DeepSeek Account model searches with the account sign-in instead`, "WEB_PROVIDER_CREDENTIAL_MISSING");
203
+ /** Append an operation path to an API base, without doubling a trailing slash. */
204
+ function joinPath(baseURL, path) {
205
+ return `${baseURL.replace(/\/+$/u, "")}${path}`;
195
206
  }
207
+ /* v8 ignore start -- reached only by a value outside a closed union, which the compiler rejects. */
208
+ /** Reject an unhandled member of a closed union. */
209
+ function assertNever$1(value) {
210
+ throw new Error(`web-deepseek-api: unexpected credential source ${JSON.stringify(value)}`);
211
+ }
212
+ /* v8 ignore stop */
196
213
  /**
197
214
  * Run one credential resolver under the search's cancellation signal. An
198
215
  * already-cancelled search never starts the resolver.
@@ -228,7 +245,7 @@ function abortable(operation, signal) {
228
245
  resolve(value);
229
246
  }, (error) => {
230
247
  signal.removeEventListener("abort", onAbort);
231
- reject(new Error(String(error).replace(/^Error: /u, ""), { cause: error }));
248
+ reject(error instanceof Error ? error : new Error(String(error), { cause: error }));
232
249
  });
233
250
  });
234
251
  }
@@ -236,7 +253,12 @@ function abortable(operation, signal) {
236
253
  function throwIfSearchAborted(signal) {
237
254
  if (signal?.aborted === true) throw searchAborted(signal);
238
255
  }
239
- /** Build the provider's stable cancellation error while retaining the caller's reason. */
256
+ /**
257
+ * Build the provider's stable cancellation error while retaining the caller's reason.
258
+ * @param signal - the aborted caller signal; its reason becomes the cause.
259
+ * @param fallback - the cause when the signal has not aborted, such as a fetch `AbortError`.
260
+ * @returns a `WEB_ABORTED` error.
261
+ */
240
262
  function searchAborted(signal, fallback) {
241
263
  return new WebError("DeepSeek web request aborted", "WEB_ABORTED", { cause: signal?.aborted === true ? signal.reason : fallback });
242
264
  }
@@ -245,6 +267,58 @@ function isAbortError(error) {
245
267
  return error instanceof DOMException && error.name === "AbortError";
246
268
  }
247
269
  //#endregion
270
+ //#region lib/types/fetch.js
271
+ /** Stable id the Fetch API provider registers under in the fetch registry. */
272
+ const DEEPSEEK_FETCH_API_PROVIDER_ID = "deepseek-fetch-api";
273
+ /**
274
+ * Fetch page Markdown through the DeepSeek Fetch API. The API reports neither the
275
+ * target's status nor a final URL, and it fails when the target yields no usable
276
+ * content, so a success is the requested page retrieved with HTTP 200.
277
+ */
278
+ var DeepSeekFetchApiProvider = class {
279
+ resolveOptions;
280
+ id = DEEPSEEK_FETCH_API_PROVIDER_ID;
281
+ /** Picker description: what this provider suits and what it costs or cannot do. */
282
+ description = {
283
+ en: "Can't reach intranet or local addresses. Incurs charges, paid by the account or API key chosen under Billing.",
284
+ zh: "无法访问内网和本机。会产生费用,由「计费方式」选定的账号或 API Key 支付。",
285
+ ja: "イントラネットやローカルのアドレスにはアクセスできません。料金が発生し、「課金方法」で選んだアカウントまたは API キーに請求されます。",
286
+ es: "No puede acceder a direcciones de la intranet ni locales. Genera cargos, que paga la cuenta o la clave de API elegida en Facturación.",
287
+ fr: "N'accède pas aux adresses intranet ou locales. Entraîne des frais, payés par le compte ou la clé API choisi dans Facturation.",
288
+ de: "Erreicht keine Intranet- oder lokalen Adressen. Verursacht Kosten, die das unter Abrechnung gewählte Konto oder der API-Schlüssel trägt.",
289
+ ru: "Адреса интрасети и локальные адреса недоступны. Услуга платная: оплата идёт с аккаунта или ключа API, выбранного в разделе «Оплата».",
290
+ pt: "Não acessa endereços da intranet nem locais. Gera cobranças, pagas pela conta ou chave de API escolhida em Cobrança."
291
+ };
292
+ /** @param resolveOptions - the options for the NEXT fetch, read once at each fetch's entry. */
293
+ constructor(resolveOptions) {
294
+ this.resolveOptions = resolveOptions;
295
+ }
296
+ available() {
297
+ const options = this.resolveOptions();
298
+ return hasDeepSeekWebCredential(options.auth) && options.auth.sources.every((source) => source.kind === "misconfigured" || URL.canParse(source.baseURL));
299
+ }
300
+ fetch(request, signal) {
301
+ const options = this.resolveOptions();
302
+ return dispatchDeepSeekWeb(options.auth, {
303
+ path: "/fetch",
304
+ body: { url: request.url },
305
+ decode: (payload) => {
306
+ if (!isRecord(payload) || typeof payload.content !== "string") throw invalidResponse();
307
+ return {
308
+ url: request.url,
309
+ statusCode: 200,
310
+ body: {
311
+ kind: "text",
312
+ content: payload.content
313
+ },
314
+ truncated: false
315
+ };
316
+ },
317
+ guidance: options.guidance
318
+ }, signal);
319
+ }
320
+ };
321
+ //#endregion
248
322
  //#region lib/types/search.js
249
323
  /** Stable id the Search API provider registers under in the search registry. */
250
324
  const DEEPSEEK_SEARCH_API_PROVIDER_ID = "deepseek-search-api";
@@ -252,15 +326,10 @@ const DEEPSEEK_SEARCH_API_PROVIDER_ID = "deepseek-search-api";
252
326
  const DEEPSEEK_WEB_API_BASE_URL = "https://api.deepseek.com/v1/tools";
253
327
  /** Default Search API result count, the service's own default. */
254
328
  const DEEPSEEK_DEFAULT_COUNT = 10;
329
+ /** Default Search requests started per second, the service's account-wide 5 QPS limit. */
330
+ const DEEPSEEK_SEARCH_REQUESTS_PER_SECOND = 5;
255
331
  /** Longest `ori_question` the Search API accepts, in characters. */
256
332
  const ORIGINAL_QUESTION_MAX_CHARS = 128;
257
- /** Settings named by endpoint failures of either API in this package. */
258
- const DEEPSEEK_WEB_API_GUIDANCE = {
259
- plugin: "web-deepseek-api",
260
- field: "baseURL",
261
- label: "Search / Fetch API base URL",
262
- page: "Web search"
263
- };
264
333
  /**
265
334
  * Validate a Search API response and project its sources into the web service.
266
335
  * @param response - untrusted JSON from the Search endpoint.
@@ -291,6 +360,19 @@ function mapSearchResponse(response) {
291
360
  var DeepSeekSearchApiProvider = class {
292
361
  resolveOptions;
293
362
  id = DEEPSEEK_SEARCH_API_PROVIDER_ID;
363
+ /** Monotonic start times (ms) of requests inside the current window, oldest first. */
364
+ starts = [];
365
+ /** Picker description: what this provider suits and what it costs or cannot do. */
366
+ description = {
367
+ en: "Incurs charges, paid by the account or API key chosen under Billing.",
368
+ zh: "会产生费用,由「计费方式」选定的账号或 API Key 支付。",
369
+ ja: "料金が発生し、「課金方法」で選んだアカウントまたは API キーに請求されます。",
370
+ es: "Genera cargos, que paga la cuenta o la clave de API elegida en Facturación.",
371
+ fr: "Entraîne des frais, payés par le compte ou la clé API choisi dans Facturation.",
372
+ de: "Verursacht Kosten, die das unter Abrechnung gewählte Konto oder der API-Schlüssel trägt.",
373
+ ru: "Услуга платная: оплата идёт с аккаунта или ключа API, выбранного в разделе «Оплата».",
374
+ pt: "Gera cobranças, pagas pela conta ou chave de API escolhida em Cobrança."
375
+ };
294
376
  /**
295
377
  * @param resolveOptions - the options for the NEXT search, read once at each
296
378
  * search's entry so one search never mixes two settings sections.
@@ -300,13 +382,13 @@ var DeepSeekSearchApiProvider = class {
300
382
  }
301
383
  available() {
302
384
  const options = this.resolveOptions();
303
- return hasDeepSeekWebCredential(options) && URL.canParse(options.baseURL) && isPositiveInteger(options.count);
385
+ return hasDeepSeekWebCredential(options.auth) && options.auth.sources.every((source) => source.kind === "misconfigured" || URL.canParse(source.baseURL)) && isPositiveInteger(options.count) && isPositiveInteger(options.requestsPerSecond);
304
386
  }
305
- search(request, signal) {
387
+ async search(request, signal) {
306
388
  const options = this.resolveOptions();
307
389
  const question = boundedQuestion(options.originalQuestion?.());
308
- return dispatchDeepSeekWeb(options, {
309
- endpoint: `${options.baseURL.replace(/\/+$/u, "")}/search`,
390
+ return dispatchDeepSeekWeb(options.auth, {
391
+ path: "/search",
310
392
  body: {
311
393
  query: request.query,
312
394
  count: Math.min(options.count, request.maxResults ?? options.count),
@@ -314,13 +396,46 @@ var DeepSeekSearchApiProvider = class {
314
396
  ...question === void 0 ? {} : { ori_question: question }
315
397
  },
316
398
  decode: mapSearchResponse,
317
- guidance: {
318
- subject: "Search",
319
- ...DEEPSEEK_WEB_API_GUIDANCE
320
- }
399
+ waitToSend: (waitSignal) => this.waitForRequestSlot(options.requestsPerSecond, waitSignal),
400
+ guidance: options.guidance
321
401
  }, signal);
322
402
  }
403
+ /**
404
+ * Wait until fewer than `limit` requests started within the last second,
405
+ * inclusive of its first millisecond, then record this start.
406
+ * @throws {@link WebError} `WEB_ABORTED` when `signal` aborts while waiting.
407
+ */
408
+ async waitForRequestSlot(limit, signal) {
409
+ for (;;) {
410
+ if (signal?.aborted === true) throw searchAborted(signal);
411
+ const now = performance.now();
412
+ let oldest = this.starts[0];
413
+ while (oldest !== void 0 && oldest < now - 1e3) {
414
+ this.starts.shift();
415
+ oldest = this.starts[0];
416
+ }
417
+ if (oldest === void 0 || this.starts.length < limit) {
418
+ this.starts.push(now);
419
+ return;
420
+ }
421
+ await abortableDelay(oldest + 1001 - now, signal);
422
+ }
423
+ }
323
424
  };
425
+ /** Resolve after `ms`, or early when `signal` aborts; the caller rechecks the signal. */
426
+ function abortableDelay(ms, signal) {
427
+ return new Promise((resolve) => {
428
+ const onAbort = () => {
429
+ clearTimeout(timer);
430
+ resolve();
431
+ };
432
+ const timer = setTimeout(() => {
433
+ signal?.removeEventListener("abort", onAbort);
434
+ resolve();
435
+ }, ms);
436
+ signal?.addEventListener("abort", onAbort, { once: true });
437
+ });
438
+ }
324
439
  /**
325
440
  * Bound the triggering question to what `ori_question` accepts: whitespace
326
441
  * collapses to single spaces and the first 128 characters remain.
@@ -337,62 +452,56 @@ function isPositiveInteger(value) {
337
452
  return Number.isInteger(value) && value > 0;
338
453
  }
339
454
  //#endregion
340
- //#region lib/types/fetch.js
341
- /** Stable id the Fetch API provider registers under in the fetch registry. */
342
- const DEEPSEEK_FETCH_API_PROVIDER_ID = "deepseek-fetch-api";
343
- /**
344
- * Fetch page Markdown through the DeepSeek Fetch API. The API reports neither the
345
- * target's status nor a final URL, and it fails when the target yields no usable
346
- * content, so a success is the requested page retrieved with HTTP 200.
347
- */
348
- var DeepSeekFetchApiProvider = class {
349
- resolveOptions;
350
- id = DEEPSEEK_FETCH_API_PROVIDER_ID;
351
- /** @param resolveOptions - the options for the NEXT fetch, read once at each fetch's entry. */
352
- constructor(resolveOptions) {
353
- this.resolveOptions = resolveOptions;
354
- }
355
- available() {
356
- const options = this.resolveOptions();
357
- return hasDeepSeekWebCredential(options) && URL.canParse(options.baseURL);
358
- }
359
- fetch(request, signal) {
360
- const options = this.resolveOptions();
361
- return dispatchDeepSeekWeb(options, {
362
- endpoint: `${options.baseURL.replace(/\/+$/u, "")}/fetch`,
363
- body: { url: request.url },
364
- decode: (payload) => {
365
- if (!isRecord(payload) || typeof payload.content !== "string") throw invalidResponse();
366
- return {
367
- url: request.url,
368
- statusCode: 200,
369
- body: {
370
- kind: "text",
371
- content: payload.content
372
- },
373
- truncated: false
374
- };
375
- },
376
- guidance: {
377
- subject: "Fetch",
378
- ...DEEPSEEK_WEB_API_GUIDANCE
379
- }
380
- }, signal);
381
- }
382
- };
383
- //#endregion
384
455
  //#region lib/types/index.js
385
456
  /** Cordis plugin name used by loader diagnostics. */
386
457
  const name = "web-deepseek-api";
387
458
  /** The web seam both providers register into. */
388
459
  const inject = ["web"];
389
460
  const Config = z.object({
390
- apiKey: z.string().role("secret").volatile(),
391
- apiKeyEnv: z.string().role("credential-ref").default("DEEPSEEK_API_KEY").volatile(),
392
- baseURL: z.string().default(DEEPSEEK_WEB_API_BASE_URL).volatile(),
393
461
  count: z.number().step(1).min(1).max(50).default(10).volatile(),
394
- sendOriginalQuestion: z.boolean().default(true).volatile()
462
+ searchRequestsPerSecond: z.number().step(1).min(1).default(5).volatile(),
463
+ sendOriginalQuestion: z.boolean().default(true).volatile(),
464
+ searchBilling: z.union([
465
+ "auto",
466
+ "account",
467
+ "api-key"
468
+ ]).default("auto").volatile(),
469
+ fetchBilling: z.union([
470
+ "auto",
471
+ "account",
472
+ "api-key"
473
+ ]).default("auto").volatile(),
474
+ searchBaseURL: z.string().volatile(),
475
+ searchApiKeyEnv: z.string().role("credential-ref").volatile(),
476
+ fetchBaseURL: z.string().volatile(),
477
+ fetchApiKeyEnv: z.string().role("credential-ref").volatile()
395
478
  });
479
+ /** Path prefix of the Search and Fetch APIs under a DeepSeek origin. */
480
+ const TOOLS_PATH = "/v1/tools";
481
+ /** Credential reference of the official DeepSeek API key. */
482
+ const DEEPSEEK_API_KEY = credentialRef("DEEPSEEK_API_KEY");
483
+ /** Provider id of the DeepSeek account route. */
484
+ const ACCOUNT_PROVIDER = "deepseek-account";
485
+ /** Provider id of the DeepSeek API-key route. */
486
+ const OFFICIAL_PROVIDER = "deepseek-official";
487
+ /** Loader package that registers each model route. */
488
+ const ROUTE_PACKAGES = {
489
+ [OFFICIAL_PROVIDER]: "@deepseek-ai/dsh-llm-deepseek-api-key",
490
+ [ACCOUNT_PROVIDER]: "@deepseek-ai/dsh-llm-deepseek-account"
491
+ };
492
+ /** Display names, configuration prefix, and operation path of each capability. */
493
+ const CAPABILITY = {
494
+ search: {
495
+ subject: "Search",
496
+ prefix: "search",
497
+ path: "/search"
498
+ },
499
+ fetch: {
500
+ subject: "Fetch",
501
+ prefix: "fetch",
502
+ path: "/fetch"
503
+ }
504
+ };
396
505
  /**
397
506
  * Read the text of the latest human prompt, the question that triggered the
398
507
  * current turn. Injected user-role context carries another source kind.
@@ -405,44 +514,223 @@ function latestUserQuestion(session) {
405
514
  return prompt.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n");
406
515
  }
407
516
  /**
408
- * Register the Search API and Fetch API providers over one live settings section. Each provider's
409
- * `ready()` answers whether an operation for a model request on the given route would have a
410
- * credential to send.
517
+ * Register the Search API and Fetch API providers over one live settings section. Each operation reads one settings
518
+ * snapshot and the route of the initiating Session's latest model request; each `ready()` call reads one settings
519
+ * snapshot and the route of the model request being prepared. Both resolve the same ordered credentials.
411
520
  * @param ctx - plugin context owning both registrations.
412
521
  * @param config - live settings, read once per operation.
413
522
  */
414
523
  function apply(ctx, config) {
415
- const keyConfig = () => ({
416
- apiKey: config.apiKey.get(),
417
- apiKeyEnv: config.apiKeyEnv.get()
418
- });
419
- const auth = () => deepSeekWebAuth(ctx, keyConfig());
420
- const ready = (llmProvider) => deepSeekWebCredentialReady(ctx, {
421
- ...keyConfig(),
422
- baseURL: config.baseURL.get()
423
- }, llmProvider);
524
+ const own = (capability) => capability === "search" ? {
525
+ baseURL: config.searchBaseURL.get(),
526
+ ref: config.searchApiKeyEnv.get(),
527
+ billing: config.searchBilling.get()
528
+ } : {
529
+ baseURL: config.fetchBaseURL.get(),
530
+ ref: config.fetchApiKeyEnv.get(),
531
+ billing: config.fetchBilling.get()
532
+ };
533
+ const target = (capability, llmProvider) => resolveTarget(ctx, capability, own(capability), llmProvider);
534
+ const current = (capability) => target(capability, ctx.get("agents")?.currentInitiator()?.session.requestContext()?.provider);
535
+ const ready = (capability) => (llmProvider) => isDeepSeekWebAuthReady(target(capability, llmProvider).auth, CAPABILITY[capability].path);
424
536
  const searchApi = new DeepSeekSearchApiProvider(() => ({
425
- ...auth(),
426
- baseURL: config.baseURL.get(),
537
+ ...current("search"),
427
538
  count: config.count.get(),
539
+ requestsPerSecond: config.searchRequestsPerSecond.get(),
428
540
  ...config.sendOriginalQuestion.get() ? { originalQuestion: () => latestUserQuestion(ctx.get("agents")?.currentInitiator()?.session) } : {}
429
541
  }));
430
- const fetchApi = new DeepSeekFetchApiProvider(() => ({
431
- ...auth(),
432
- baseURL: config.baseURL.get()
433
- }));
542
+ const fetchApi = new DeepSeekFetchApiProvider(() => current("fetch"));
434
543
  ctx.web.registerSearchProvider({
435
544
  id: searchApi.id,
545
+ description: searchApi.description,
436
546
  available: () => searchApi.available(),
437
- ready,
547
+ ready: ready("search"),
438
548
  search: (request, signal) => searchApi.search(request, signal)
439
549
  });
440
550
  ctx.web.registerFetchProvider({
441
551
  id: fetchApi.id,
552
+ description: fetchApi.description,
442
553
  available: () => fetchApi.available(),
443
- ready,
554
+ ready: ready("fetch"),
444
555
  fetch: (request, signal) => fetchApi.fetch(request, signal)
445
556
  });
446
557
  }
558
+ /**
559
+ * Resolve the ordered credentials and endpoint guidance of one capability without reading credential values. Route
560
+ * endpoints use the origin of the route's resolved Messages base URL with `/v1/tools`.
561
+ * @param ctx - context with the model, loader, credential, and account services.
562
+ * @param capability - the capability being resolved.
563
+ * @param own - the capability's own base URL and credential reference, where empty values count as unset, and its
564
+ * billing.
565
+ * @param llmProvider - provider route of the model request the operation serves.
566
+ * @returns the authentication sources and the settings endpoint failures name.
567
+ */
568
+ function resolveTarget(ctx, capability, own, llmProvider) {
569
+ const { subject, prefix } = CAPABILITY[capability];
570
+ const guidance = (custom) => ({
571
+ subject,
572
+ plugin: name,
573
+ custom,
574
+ baseURLField: `${prefix}BaseURL`,
575
+ apiKeyEnvField: `${prefix}ApiKeyEnv`
576
+ });
577
+ const ownBaseURL = nonEmpty(own.baseURL), ownRef = nonEmpty(own.ref);
578
+ if (ownBaseURL !== void 0 || ownRef !== void 0) {
579
+ const ref = ownRef === void 0 ? DEEPSEEK_API_KEY : credentialRef(ownRef);
580
+ const json = JSON.stringify(ref);
581
+ return {
582
+ guidance: guidance(true),
583
+ auth: {
584
+ sources: [apiKeySource(ctx, ownBaseURL ?? "https://api.deepseek.com/v1/tools", ref)],
585
+ missingCredentialMessage: `DeepSeek ${subject} API sends the API key under ${json} to its own endpoint, and no key is configured for ${json}. Guide the user to export ${json} in the launching environment, or to correct ${name}.${prefix}ApiKeyEnv.`
586
+ }
587
+ };
588
+ }
589
+ const rule = own.billing !== "auto" ? own.billing : llmProvider === ACCOUNT_PROVIDER ? "account-conversation" : llmProvider === OFFICIAL_PROVIDER ? "official-conversation" : "other-conversation";
590
+ const sources = ruleSources(ctx, capability, rule);
591
+ const [ref = DEEPSEEK_API_KEY] = sources.flatMap((row) => row.kind === "api-key" && typeof row.key !== "string" ? [row.key.ref] : []);
592
+ return {
593
+ guidance: guidance(false),
594
+ auth: {
595
+ sources,
596
+ missingCredentialMessage: missingMessage(capability, rule, ref)
597
+ }
598
+ };
599
+ }
600
+ /**
601
+ * The credentials one rule tries, in order.
602
+ * @param ctx - context with the model, loader, credential, and account services.
603
+ * @param capability - the capability whose diagnostics misconfigured sources name.
604
+ * @param rule - the rule.
605
+ * @returns the sources; the account source is absent in an account conversation without a mounted account route.
606
+ */
607
+ function ruleSources(ctx, capability, rule) {
608
+ const accountConfig = routeConfig(ctx, ACCOUNT_PROVIDER);
609
+ switch (rule) {
610
+ case "account-conversation": return accountConfig === void 0 ? [officialSource(ctx, capability)] : [accountSource(ctx, capability, accountConfig), officialSource(ctx, capability)];
611
+ case "official-conversation":
612
+ case "api-key": return [officialSource(ctx, capability)];
613
+ case "other-conversation": return [officialSource(ctx, capability), accountSource(ctx, capability, accountConfig)];
614
+ case "account": return [accountSource(ctx, capability, accountConfig)];
615
+ /* v8 ignore next -- the switch is exhaustive. */
616
+ default: return assertNever(rule);
617
+ }
618
+ }
619
+ /**
620
+ * The API key of the active DeepSeek API-key route, sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base
621
+ * without that route.
622
+ * @returns the source, or a misconfigured source when the route's resolver rejects its settings.
623
+ */
624
+ function officialSource(ctx, capability) {
625
+ const config = routeConfig(ctx, OFFICIAL_PROVIDER);
626
+ if (config === void 0) return apiKeySource(ctx, DEEPSEEK_WEB_API_BASE_URL, DEEPSEEK_API_KEY);
627
+ let resolved;
628
+ try {
629
+ resolved = resolveAdapterOptions(plainOptions(config), launchEnvironmentOf(ctx));
630
+ } catch (error) {
631
+ return misconfigured(capability, OFFICIAL_PROVIDER, error);
632
+ }
633
+ return apiKeySource(ctx, toolsBase(resolved.baseURL), resolved.apiKeyEnv);
634
+ }
635
+ /**
636
+ * The account token sent to the origin of the account route, or without that route to the origin of its default base
637
+ * URL, including `DEEPSEEK_BASE_URL`. The account service releases the token only for destinations it allows.
638
+ * @param config - the active account route's settings, or undefined for the defaults.
639
+ * @returns the source, or a misconfigured source when the route's resolver rejects its settings.
640
+ */
641
+ function accountSource(ctx, capability, config) {
642
+ let baseURL;
643
+ try {
644
+ baseURL = resolveAccountOptions(config === void 0 ? {} : plainAccountOptions(config), launchEnvironmentOf(ctx)).protocol.baseURL;
645
+ } catch (error) {
646
+ return misconfigured(capability, ACCOUNT_PROVIDER, error);
647
+ }
648
+ return {
649
+ kind: "account",
650
+ baseURL: toolsBase(baseURL),
651
+ resolveToken: (endpoint) => resolveDeepSeekAccountToken(ctx, endpoint),
652
+ rejectToken: (token) => rejectDeepSeekAccountToken(ctx, token)
653
+ };
654
+ }
655
+ /** The key under `ref`, read through the shared DeepSeek credential helpers, sent to `baseURL`. */
656
+ function apiKeySource(ctx, baseURL, ref) {
657
+ return {
658
+ kind: "api-key",
659
+ baseURL,
660
+ key: {
661
+ ref,
662
+ configured: () => deepSeekApiKeyConfigured(ctx, ref),
663
+ resolve: () => resolveDeepSeekApiKey(ctx, ref)
664
+ }
665
+ };
666
+ }
667
+ /**
668
+ * The source of a credential whose model route settings do not resolve.
669
+ * @param capability - the capability that stops.
670
+ * @param route - the route whose settings failed.
671
+ * @param error - the route resolver's failure.
672
+ * @returns the source whose diagnostic names the route and both recoveries.
673
+ */
674
+ function misconfigured(capability, route, error) {
675
+ const { subject, prefix } = CAPABILITY[capability];
676
+ return {
677
+ kind: "misconfigured",
678
+ message: `DeepSeek ${subject} API sends ${route === ACCOUNT_PROVIDER ? "the DeepSeek account sign-in" : "that provider's API key"} to the origin of the ${route === ACCOUNT_PROVIDER ? "DeepSeek account model provider" : "DeepSeek API-key model provider"}, and that provider's settings do not resolve: ${errorMessage(error)}. ${subject} did not send the request. Guide the user to correct that provider's settings on the Models page or in the deployment configuration, or to set ${name}.${prefix}BaseURL and ${name}.${prefix}ApiKeyEnv so ${subject} uses its own endpoint.`
679
+ };
680
+ }
681
+ /**
682
+ * Model-facing diagnostic for an operation billed by `rule` that has no credential to send.
683
+ * @param capability - the capability that stops.
684
+ * @param rule - the rule that ordered its credentials.
685
+ * @param keyRef - the reference of the API key the rule tries, or `DEEPSEEK_API_KEY` when it tries none.
686
+ * @returns the diagnostic naming the missing credentials and their recoveries.
687
+ */
688
+ function missingMessage(capability, rule, keyRef) {
689
+ const { subject, prefix } = CAPABILITY[capability];
690
+ const ref = JSON.stringify(keyRef);
691
+ const addKey = `add the DeepSeek API key on the Models page or export ${ref} in the launching environment`;
692
+ const billing = `${name}.${prefix}Billing`;
693
+ const settings = "on the Web search and fetch settings page";
694
+ switch (rule) {
695
+ case "account-conversation": return `DeepSeek ${subject} API uses the DeepSeek account sign-in of this conversation, then the DeepSeek API key, and neither is available: no signed-in DeepSeek account is available, and no key is configured for ${ref}. Guide the user to sign in to DeepSeek, or to ${addKey}.`;
696
+ case "official-conversation": return `DeepSeek ${subject} API uses the DeepSeek API key, as this conversation's model provider does, and no key is configured for ${ref}. Guide the user to ${addKey}, or to sign in to DeepSeek and set ${billing} to "account" ${settings}.`;
697
+ case "other-conversation": return `DeepSeek ${subject} API uses the DeepSeek API key, then the DeepSeek account sign-in, and neither is available: no key is configured for ${ref}, and no signed-in DeepSeek account is available. Guide the user to ${addKey}, or to sign in to DeepSeek.`;
698
+ case "account": return `DeepSeek ${subject} API bills only the signed-in DeepSeek account, and no signed-in DeepSeek account is available. ${subject} did not send the request. Guide the user to sign in to DeepSeek, or to set ${billing} to "api-key" or "auto" ${settings}.`;
699
+ case "api-key": return `DeepSeek ${subject} API bills only the DeepSeek API key, and no key is configured for ${ref}. Guide the user to ${addKey}, or to set ${billing} to "account" or "auto" ${settings}.`;
700
+ /* v8 ignore next -- the switch is exhaustive. */
701
+ default: return assertNever(rule);
702
+ }
703
+ }
704
+ /** The message of a thrown value. */
705
+ function errorMessage(error) {
706
+ return error instanceof Error ? error.message : String(error);
707
+ }
708
+ /**
709
+ * Find the effective config of the active loader entry that registers `provider`, as the model provider directory
710
+ * names it. A route registered by another package, nested settings, or an inactive entry counts as absent.
711
+ */
712
+ function routeConfig(ctx, provider) {
713
+ const llm = ctx.get("llm"), loader = ctx.get("loader");
714
+ if (llm === void 0 || loader === void 0 || !llm.listProviders().some((row) => row.id === provider)) return void 0;
715
+ const directory = llm.listConfigurableProviders().find((row) => row.provider === provider);
716
+ if (directory === void 0 || directory.settingsPath.length !== 0) return void 0;
717
+ const entry = [...loader.entries()].find((row) => row.options.id === directory.settingsNs && row.options.name === ROUTE_PACKAGES[provider]);
718
+ if (entry?.fiber?.state !== 2) return void 0;
719
+ return entry.fiber.effectiveConfig;
720
+ }
721
+ /** The Search and Fetch API base under the origin of a Messages base URL. */
722
+ function toolsBase(messagesBaseURL) {
723
+ return `${new URL(messagesBaseURL).origin}${TOOLS_PATH}`;
724
+ }
725
+ /** A string with content, or undefined for an absent or empty value. */
726
+ function nonEmpty(value) {
727
+ return value !== void 0 && value.length > 0 ? value : void 0;
728
+ }
729
+ /* v8 ignore start -- reached only by a value outside a closed union, which the compiler rejects. */
730
+ /** Reject an unhandled member of a closed union. */
731
+ function assertNever(value) {
732
+ throw new Error(`web-deepseek-api: unexpected value ${String(value)}`);
733
+ }
734
+ /* v8 ignore stop */
447
735
  //#endregion
448
- export { Config, DEEPSEEK_DEFAULT_COUNT, DEEPSEEK_FETCH_API_PROVIDER_ID, DEEPSEEK_SEARCH_API_PROVIDER_ID, DEEPSEEK_WEB_API_BASE_URL, DeepSeekFetchApiProvider, DeepSeekSearchApiProvider, apply, inject, mapSearchResponse, name };
736
+ export { Config, DEEPSEEK_DEFAULT_COUNT, DEEPSEEK_FETCH_API_PROVIDER_ID, DEEPSEEK_SEARCH_API_PROVIDER_ID, DEEPSEEK_SEARCH_REQUESTS_PER_SECOND, DEEPSEEK_WEB_API_BASE_URL, DeepSeekFetchApiProvider, DeepSeekSearchApiProvider, apply, inject, mapSearchResponse, name };