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

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/src/index.ts ADDED
@@ -0,0 +1,389 @@
1
+ /**
2
+ * Register the DeepSeek Search and Fetch APIs in `ctx.web` as `deepseek-search-api`
3
+ * and `deepseek-fetch-api`. Each operation is one direct API request without an
4
+ * auxiliary model request. `web.searchProvider` and `web.fetchProvider` select them. Each capability's billing setting
5
+ * chooses its credential. `auto` follows the conversation: a Session whose latest model request used the
6
+ * `deepseek-account` route sends the account token to that route's origin and otherwise the API key; one on the
7
+ * `deepseek-official` route sends the API key; any other operation sends the API key and, without a key, the signed-in
8
+ * account's token. `account` sends only the account token and `api-key` only the API key. The API key is that of the
9
+ * DeepSeek API-key route, sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base without that route. The
10
+ * account token goes to the account route's origin, or outside an account conversation without that route to the origin
11
+ * of its default base URL. An operation that needs a mounted route whose settings do not resolve fails instead of
12
+ * changing its endpoint or credential. A capability with its own `*BaseURL` or `*ApiKeyEnv` uses only that endpoint and
13
+ * key instead, whatever its billing
14
+ * ([rationale](../../../../.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md#credential-resolution)).
15
+ * Both providers report themselves not ready when their next operation would have no credential.
16
+ * @module @deepseek-ai/dsh-web-deepseek-api
17
+ */
18
+ import { FiberState, type Context, type Volatile } from '@deepseek-ai/cordis'
19
+ import type {} from '@deepseek-ai/cordis-plugin-loader'
20
+ import z from '@deepseek-ai/schemastery'
21
+ import type {} from '@deepseek-ai/dsh-agent'
22
+ import { credentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials'
23
+ import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
24
+ import type {} from '@deepseek-ai/dsh-llm'
25
+ import {
26
+ deepSeekApiKeyConfigured, rejectDeepSeekAccountToken, resolveDeepSeekAccountToken, resolveDeepSeekApiKey,
27
+ } from '@deepseek-ai/dsh-llm-deepseek'
28
+ import {
29
+ plainAccountOptions, resolveAccountOptions, type Config as AccountRouteConfig,
30
+ } from '@deepseek-ai/dsh-llm-deepseek-account'
31
+ import {
32
+ plainOptions as plainOfficialOptions, resolveAdapterOptions as resolveOfficialOptions, type Config as OfficialRouteConfig,
33
+ } from '@deepseek-ai/dsh-llm-deepseek-api-key'
34
+ import type { Session } from '@deepseek-ai/dsh-session'
35
+ import type {} from '@deepseek-ai/dsh-web'
36
+ import { DeepSeekFetchApiProvider } from './fetch.ts'
37
+ import {
38
+ DEEPSEEK_DEFAULT_COUNT, DEEPSEEK_SEARCH_REQUESTS_PER_SECOND, DEEPSEEK_WEB_API_BASE_URL, DeepSeekSearchApiProvider,
39
+ } from './search.ts'
40
+ import {
41
+ isDeepSeekWebAuthReady, type DeepSeekWebAuth, type DeepSeekWebAuthSource, type DeepSeekWebGuidance,
42
+ } from './transport.ts'
43
+
44
+ export { DEEPSEEK_FETCH_API_PROVIDER_ID, DeepSeekFetchApiProvider } from './fetch.ts'
45
+ export type { DeepSeekFetchApiOptions } from './fetch.ts'
46
+ export {
47
+ DEEPSEEK_DEFAULT_COUNT, DEEPSEEK_SEARCH_API_PROVIDER_ID, DEEPSEEK_SEARCH_REQUESTS_PER_SECOND, DEEPSEEK_WEB_API_BASE_URL,
48
+ DeepSeekSearchApiProvider, mapSearchResponse,
49
+ } from './search.ts'
50
+ export type { DeepSeekSearchApiOptions } from './search.ts'
51
+
52
+ /** Cordis plugin name used by loader diagnostics. */
53
+ export const name = 'web-deepseek-api'
54
+
55
+ /** The web seam both providers register into. */
56
+ export const inject = ['web']
57
+
58
+ /**
59
+ * Settings read by the next search or fetch without re-registering either provider. A non-empty `*BaseURL` or
60
+ * `*ApiKeyEnv` gives that capability its own endpoint and key; with neither, its `*Billing` chooses its DeepSeek
61
+ * credential. Stored fields of earlier settings (`baseURL`, `apiKeyEnv`, `apiKey`) are not schema fields: they load
62
+ * without error and have no effect.
63
+ */
64
+ export interface Config {
65
+ /** Search API results per search, from 1 through 50; a smaller request bound wins. Defaults to 10. */
66
+ count: Volatile<number>
67
+ /**
68
+ * Most Search requests this plugin instance sends in any one-second window; later searches wait,
69
+ * and the wait counts against the caller's timeout. Other processes and clients on the same account
70
+ * share the account limit without coordination. Defaults to 5.
71
+ */
72
+ searchRequestsPerSecond: Volatile<number>
73
+ /** Send the triggering user question, bounded to 128 characters, as `ori_question`. Defaults to true. */
74
+ sendOriginalQuestion: Volatile<boolean>
75
+ /**
76
+ * Credential Search sends without {@link searchBaseURL} and {@link searchApiKeyEnv}. `auto` uses the conversation's
77
+ * DeepSeek account or API key while it chats on a DeepSeek model route, and otherwise the API key, then the signed-in
78
+ * account; `account` uses only the signed-in account; `api-key` uses only the API key. Defaults to `auto`.
79
+ */
80
+ searchBilling: Volatile<'auto' | 'account' | 'api-key'>
81
+ /** Credential Fetch sends without {@link fetchBaseURL} and {@link fetchApiKeyEnv}, chosen as {@link searchBilling} is. */
82
+ fetchBilling: Volatile<'auto' | 'account' | 'api-key'>
83
+ /**
84
+ * Own Search API base including its path prefix; `/search` is appended. With only {@link searchApiKeyEnv} set, the
85
+ * official base applies.
86
+ */
87
+ searchBaseURL: Volatile<string | undefined>
88
+ /** Own Search API credential reference. With only {@link searchBaseURL} set, `DEEPSEEK_API_KEY` applies. */
89
+ searchApiKeyEnv: Volatile<string | undefined>
90
+ /**
91
+ * Own Fetch API base including its path prefix; `/fetch` is appended. With only {@link fetchApiKeyEnv} set, the
92
+ * official base applies.
93
+ */
94
+ fetchBaseURL: Volatile<string | undefined>
95
+ /** Own Fetch API credential reference. With only {@link fetchBaseURL} set, `DEEPSEEK_API_KEY` applies. */
96
+ fetchApiKeyEnv: Volatile<string | undefined>
97
+ }
98
+
99
+ export const Config = z.object({
100
+ count: z.number().step(1).min(1).max(50).default(DEEPSEEK_DEFAULT_COUNT).volatile(),
101
+ searchRequestsPerSecond: z.number().step(1).min(1).default(DEEPSEEK_SEARCH_REQUESTS_PER_SECOND).volatile(),
102
+ sendOriginalQuestion: z.boolean().default(true).volatile(),
103
+ searchBilling: z.union(['auto', 'account', 'api-key'] as const).default('auto').volatile(),
104
+ fetchBilling: z.union(['auto', 'account', 'api-key'] as const).default('auto').volatile(),
105
+ searchBaseURL: z.string().volatile(),
106
+ searchApiKeyEnv: z.string().role('credential-ref').volatile(),
107
+ fetchBaseURL: z.string().volatile(),
108
+ fetchApiKeyEnv: z.string().role('credential-ref').volatile(),
109
+ })
110
+
111
+ /** A capability that resolves its endpoint and credential independently of the other. */
112
+ type Capability = 'search' | 'fetch'
113
+
114
+ /** Credential choice of one capability without its own endpoint settings. */
115
+ type Billing = Config['searchBilling'] extends Volatile<infer B> ? B : never
116
+
117
+ /** Model route whose settings an operation can depend on. */
118
+ type RouteName = keyof typeof ROUTE_PACKAGES
119
+
120
+ /**
121
+ * Rule that ordered an operation's credentials: `auto` billing in a conversation on the account route, on the API-key
122
+ * route, or anywhere else, or an explicit billing.
123
+ */
124
+ type Rule = 'account-conversation' | 'official-conversation' | 'other-conversation' | 'account' | 'api-key'
125
+
126
+ /** Path prefix of the Search and Fetch APIs under a DeepSeek origin. */
127
+ const TOOLS_PATH = '/v1/tools'
128
+
129
+ /** Credential reference of the official DeepSeek API key. */
130
+ const DEEPSEEK_API_KEY = credentialRef('DEEPSEEK_API_KEY')
131
+
132
+ /** Provider id of the DeepSeek account route. */
133
+ const ACCOUNT_PROVIDER = 'deepseek-account'
134
+
135
+ /** Provider id of the DeepSeek API-key route. */
136
+ const OFFICIAL_PROVIDER = 'deepseek-official'
137
+
138
+ /** Loader package that registers each model route. */
139
+ const ROUTE_PACKAGES = {
140
+ [OFFICIAL_PROVIDER]: '@deepseek-ai/dsh-llm-deepseek-api-key',
141
+ [ACCOUNT_PROVIDER]: '@deepseek-ai/dsh-llm-deepseek-account',
142
+ } as const
143
+
144
+ /** Display names, configuration prefix, and operation path of each capability. */
145
+ const CAPABILITY = {
146
+ search: { subject: 'Search', prefix: 'search', path: '/search' },
147
+ fetch: { subject: 'Fetch', prefix: 'fetch', path: '/fetch' },
148
+ } as const satisfies Record<Capability, { subject: DeepSeekWebGuidance['subject']; prefix: string; path: '/search' | '/fetch' }>
149
+
150
+ /**
151
+ * Read the text of the latest human prompt, the question that triggered the
152
+ * current turn. Injected user-role context carries another source kind.
153
+ * @param session - the initiating Session, when the search runs inside one.
154
+ * @returns the prompt's joined text blocks, or undefined without a prompt.
155
+ */
156
+ function latestUserQuestion(session: Session | undefined): string | undefined {
157
+ const prompt = session?.deriveMessages().findLast(message => message.role === 'user' && message.source.kind === 'user')
158
+ if (prompt === undefined) return undefined
159
+ return prompt.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')
160
+ }
161
+
162
+ /**
163
+ * Register the Search API and Fetch API providers over one live settings section. Each operation reads one settings
164
+ * snapshot and the route of the initiating Session's latest model request; each `ready()` call reads one settings
165
+ * snapshot and the route of the model request being prepared. Both resolve the same ordered credentials.
166
+ * @param ctx - plugin context owning both registrations.
167
+ * @param config - live settings, read once per operation.
168
+ */
169
+ export function apply(ctx: Context, config: Config): void {
170
+ const own = (capability: Capability) => capability === 'search'
171
+ ? { baseURL: config.searchBaseURL.get(), ref: config.searchApiKeyEnv.get(), billing: config.searchBilling.get() }
172
+ : { baseURL: config.fetchBaseURL.get(), ref: config.fetchApiKeyEnv.get(), billing: config.fetchBilling.get() }
173
+ const target = (capability: Capability, llmProvider: string | undefined) =>
174
+ resolveTarget(ctx, capability, own(capability), llmProvider)
175
+ const current = (capability: Capability) =>
176
+ target(capability, ctx.get('agents')?.currentInitiator()?.session.requestContext()?.provider)
177
+ const ready = (capability: Capability) => (llmProvider: string | undefined): Promise<boolean> =>
178
+ isDeepSeekWebAuthReady(target(capability, llmProvider).auth, CAPABILITY[capability].path)
179
+ const searchApi = new DeepSeekSearchApiProvider(() => ({
180
+ ...current('search'),
181
+ count: config.count.get(),
182
+ requestsPerSecond: config.searchRequestsPerSecond.get(),
183
+ ...config.sendOriginalQuestion.get() ? {
184
+ originalQuestion: () => latestUserQuestion(ctx.get('agents')?.currentInitiator()?.session),
185
+ } : {},
186
+ }))
187
+ const fetchApi = new DeepSeekFetchApiProvider(() => current('fetch'))
188
+ ctx.web.registerSearchProvider({
189
+ id: searchApi.id,
190
+ description: searchApi.description,
191
+ available: () => searchApi.available(),
192
+ ready: ready('search'),
193
+ search: (request, signal) => searchApi.search(request, signal),
194
+ })
195
+ ctx.web.registerFetchProvider({
196
+ id: fetchApi.id,
197
+ description: fetchApi.description,
198
+ available: () => fetchApi.available(),
199
+ ready: ready('fetch'),
200
+ fetch: (request, signal) => fetchApi.fetch(request, signal),
201
+ })
202
+ }
203
+
204
+ /**
205
+ * Resolve the ordered credentials and endpoint guidance of one capability without reading credential values. Route
206
+ * endpoints use the origin of the route's resolved Messages base URL with `/v1/tools`.
207
+ * @param ctx - context with the model, loader, credential, and account services.
208
+ * @param capability - the capability being resolved.
209
+ * @param own - the capability's own base URL and credential reference, where empty values count as unset, and its
210
+ * billing.
211
+ * @param llmProvider - provider route of the model request the operation serves.
212
+ * @returns the authentication sources and the settings endpoint failures name.
213
+ */
214
+ function resolveTarget(
215
+ ctx: Context, capability: Capability,
216
+ own: { baseURL: string | undefined; ref: string | undefined; billing: Billing }, llmProvider: string | undefined,
217
+ ): { auth: DeepSeekWebAuth; guidance: DeepSeekWebGuidance } {
218
+ const { subject, prefix } = CAPABILITY[capability]
219
+ const guidance = (custom: boolean): DeepSeekWebGuidance =>
220
+ ({ subject, plugin: name, custom, baseURLField: `${prefix}BaseURL`, apiKeyEnvField: `${prefix}ApiKeyEnv` })
221
+ const ownBaseURL = nonEmpty(own.baseURL), ownRef = nonEmpty(own.ref)
222
+ if (ownBaseURL !== undefined || ownRef !== undefined) {
223
+ const ref = ownRef === undefined ? DEEPSEEK_API_KEY : credentialRef(ownRef)
224
+ const json = JSON.stringify(ref)
225
+ return { guidance: guidance(true), auth: {
226
+ sources: [apiKeySource(ctx, ownBaseURL ?? DEEPSEEK_WEB_API_BASE_URL, ref)],
227
+ missingCredentialMessage: `DeepSeek ${subject} API sends the API key under ${json} to its own endpoint, and no key is`
228
+ + ` configured for ${json}. Guide the user to export ${json} in the launching environment, or to correct`
229
+ + ` ${name}.${prefix}ApiKeyEnv.`,
230
+ } }
231
+ }
232
+ const rule: Rule = own.billing !== 'auto' ? own.billing
233
+ : llmProvider === ACCOUNT_PROVIDER ? 'account-conversation'
234
+ : llmProvider === OFFICIAL_PROVIDER ? 'official-conversation' : 'other-conversation'
235
+ const sources = ruleSources(ctx, capability, rule)
236
+ const [ref = DEEPSEEK_API_KEY] = sources.flatMap(row => row.kind === 'api-key' && typeof row.key !== 'string' ? [row.key.ref] : [])
237
+ return { guidance: guidance(false), auth: { sources, missingCredentialMessage: missingMessage(capability, rule, ref) } }
238
+ }
239
+
240
+ /**
241
+ * The credentials one rule tries, in order.
242
+ * @param ctx - context with the model, loader, credential, and account services.
243
+ * @param capability - the capability whose diagnostics misconfigured sources name.
244
+ * @param rule - the rule.
245
+ * @returns the sources; the account source is absent in an account conversation without a mounted account route.
246
+ */
247
+ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeekWebAuthSource[] {
248
+ const accountConfig = routeConfig(ctx, ACCOUNT_PROVIDER) as AccountRouteConfig | undefined
249
+ switch (rule) {
250
+ case 'account-conversation': return accountConfig === undefined
251
+ ? [officialSource(ctx, capability)] : [accountSource(ctx, capability, accountConfig), officialSource(ctx, capability)]
252
+ case 'official-conversation':
253
+ case 'api-key': return [officialSource(ctx, capability)]
254
+ case 'other-conversation': return [officialSource(ctx, capability), accountSource(ctx, capability, accountConfig)]
255
+ case 'account': return [accountSource(ctx, capability, accountConfig)]
256
+ /* v8 ignore next -- the switch is exhaustive. */
257
+ default: return assertNever(rule)
258
+ }
259
+ }
260
+
261
+ /**
262
+ * The API key of the active DeepSeek API-key route, sent to its origin, or `DEEPSEEK_API_KEY` sent to the official base
263
+ * without that route.
264
+ * @returns the source, or a misconfigured source when the route's resolver rejects its settings.
265
+ */
266
+ function officialSource(ctx: Context, capability: Capability): DeepSeekWebAuthSource {
267
+ const config = routeConfig(ctx, OFFICIAL_PROVIDER) as OfficialRouteConfig | undefined
268
+ if (config === undefined) return apiKeySource(ctx, DEEPSEEK_WEB_API_BASE_URL, DEEPSEEK_API_KEY)
269
+ let resolved: { baseURL: string; apiKeyEnv: CredentialRef }
270
+ try { resolved = resolveOfficialOptions(plainOfficialOptions(config), launchEnvironmentOf(ctx)) }
271
+ catch (error: unknown) { return misconfigured(capability, OFFICIAL_PROVIDER, error) }
272
+ return apiKeySource(ctx, toolsBase(resolved.baseURL), resolved.apiKeyEnv)
273
+ }
274
+
275
+ /**
276
+ * The account token sent to the origin of the account route, or without that route to the origin of its default base
277
+ * URL, including `DEEPSEEK_BASE_URL`. The account service releases the token only for destinations it allows.
278
+ * @param config - the active account route's settings, or undefined for the defaults.
279
+ * @returns the source, or a misconfigured source when the route's resolver rejects its settings.
280
+ */
281
+ function accountSource(ctx: Context, capability: Capability, config: AccountRouteConfig | undefined): DeepSeekWebAuthSource {
282
+ let baseURL: string
283
+ try {
284
+ baseURL = resolveAccountOptions(config === undefined ? {} : plainAccountOptions(config), launchEnvironmentOf(ctx)).protocol.baseURL
285
+ } catch (error: unknown) { return misconfigured(capability, ACCOUNT_PROVIDER, error) }
286
+ return {
287
+ kind: 'account', baseURL: toolsBase(baseURL),
288
+ resolveToken: endpoint => resolveDeepSeekAccountToken(ctx, endpoint),
289
+ rejectToken: token => rejectDeepSeekAccountToken(ctx, token),
290
+ }
291
+ }
292
+
293
+ /** The key under `ref`, read through the shared DeepSeek credential helpers, sent to `baseURL`. */
294
+ function apiKeySource(ctx: Context, baseURL: string, ref: CredentialRef): DeepSeekWebAuthSource {
295
+ return { kind: 'api-key', baseURL, key: {
296
+ ref, configured: () => deepSeekApiKeyConfigured(ctx, ref), resolve: () => resolveDeepSeekApiKey(ctx, ref),
297
+ } }
298
+ }
299
+
300
+ /**
301
+ * The source of a credential whose model route settings do not resolve.
302
+ * @param capability - the capability that stops.
303
+ * @param route - the route whose settings failed.
304
+ * @param error - the route resolver's failure.
305
+ * @returns the source whose diagnostic names the route and both recoveries.
306
+ */
307
+ function misconfigured(capability: Capability, route: RouteName, error: unknown): DeepSeekWebAuthSource {
308
+ const { subject, prefix } = CAPABILITY[capability]
309
+ const provider = route === ACCOUNT_PROVIDER ? 'DeepSeek account model provider' : 'DeepSeek API-key model provider'
310
+ const credential = route === ACCOUNT_PROVIDER ? 'the DeepSeek account sign-in' : 'that provider\'s API key'
311
+ return { kind: 'misconfigured', message: `DeepSeek ${subject} API sends ${credential} to the origin of the ${provider}, and`
312
+ + ` that provider's settings do not resolve: ${errorMessage(error)}. ${subject} did not send the request. Guide the user`
313
+ + ' to correct that provider\'s settings on the Models page or in the deployment configuration, or to set'
314
+ + ` ${name}.${prefix}BaseURL and ${name}.${prefix}ApiKeyEnv so ${subject} uses its own endpoint.` }
315
+ }
316
+
317
+ /**
318
+ * Model-facing diagnostic for an operation billed by `rule` that has no credential to send.
319
+ * @param capability - the capability that stops.
320
+ * @param rule - the rule that ordered its credentials.
321
+ * @param keyRef - the reference of the API key the rule tries, or `DEEPSEEK_API_KEY` when it tries none.
322
+ * @returns the diagnostic naming the missing credentials and their recoveries.
323
+ */
324
+ function missingMessage(capability: Capability, rule: Rule, keyRef: CredentialRef): string {
325
+ const { subject, prefix } = CAPABILITY[capability]
326
+ const ref = JSON.stringify(keyRef)
327
+ const addKey = `add the DeepSeek API key on the Models page or export ${ref} in the launching environment`
328
+ const billing = `${name}.${prefix}Billing`
329
+ const settings = 'on the Web search and fetch settings page'
330
+ switch (rule) {
331
+ case 'account-conversation':
332
+ return `DeepSeek ${subject} API uses the DeepSeek account sign-in of this conversation, then the DeepSeek API key, and`
333
+ + ` neither is available: no signed-in DeepSeek account is available, and no key is configured for ${ref}. Guide the`
334
+ + ` user to sign in to DeepSeek, or to ${addKey}.`
335
+ case 'official-conversation':
336
+ return `DeepSeek ${subject} API uses the DeepSeek API key, as this conversation's model provider does, and no key is`
337
+ + ` configured for ${ref}. Guide the user to ${addKey}, or to sign in to DeepSeek and set ${billing} to "account"`
338
+ + ` ${settings}.`
339
+ case 'other-conversation':
340
+ return `DeepSeek ${subject} API uses the DeepSeek API key, then the DeepSeek account sign-in, and neither is available:`
341
+ + ` no key is configured for ${ref}, and no signed-in DeepSeek account is available. Guide the user to ${addKey}, or`
342
+ + ' to sign in to DeepSeek.'
343
+ case 'account':
344
+ return `DeepSeek ${subject} API bills only the signed-in DeepSeek account, and no signed-in DeepSeek account is`
345
+ + ` available. ${subject} did not send the request. Guide the user to sign in to DeepSeek, or to set ${billing} to`
346
+ + ` "api-key" or "auto" ${settings}.`
347
+ case 'api-key':
348
+ return `DeepSeek ${subject} API bills only the DeepSeek API key, and no key is configured for ${ref}. Guide the user to`
349
+ + ` ${addKey}, or to set ${billing} to "account" or "auto" ${settings}.`
350
+ /* v8 ignore next -- the switch is exhaustive. */
351
+ default: return assertNever(rule)
352
+ }
353
+ }
354
+
355
+ /** The message of a thrown value. */
356
+ function errorMessage(error: unknown): string {
357
+ return error instanceof Error ? error.message : String(error)
358
+ }
359
+
360
+ /**
361
+ * Find the effective config of the active loader entry that registers `provider`, as the model provider directory
362
+ * names it. A route registered by another package, nested settings, or an inactive entry counts as absent.
363
+ */
364
+ function routeConfig(ctx: Context, provider: RouteName): unknown {
365
+ const llm = ctx.get('llm'), loader = ctx.get('loader')
366
+ if (llm === undefined || loader === undefined || !llm.listProviders().some(row => row.id === provider)) return undefined
367
+ const directory = llm.listConfigurableProviders().find(row => row.provider === provider)
368
+ if (directory === undefined || directory.settingsPath.length !== 0) return undefined
369
+ const entry = [...loader.entries()].find(row => row.options.id === directory.settingsNs && row.options.name === ROUTE_PACKAGES[provider])
370
+ if (entry?.fiber?.state !== FiberState.ACTIVE) return undefined
371
+ return entry.fiber.effectiveConfig
372
+ }
373
+
374
+ /** The Search and Fetch API base under the origin of a Messages base URL. */
375
+ function toolsBase(messagesBaseURL: string): string {
376
+ return `${new URL(messagesBaseURL).origin}${TOOLS_PATH}`
377
+ }
378
+
379
+ /** A string with content, or undefined for an absent or empty value. */
380
+ function nonEmpty(value: string | undefined): string | undefined {
381
+ return value !== undefined && value.length > 0 ? value : undefined
382
+ }
383
+
384
+ /* v8 ignore start -- reached only by a value outside a closed union, which the compiler rejects. */
385
+ /** Reject an unhandled member of a closed union. */
386
+ function assertNever(value: never): never {
387
+ throw new Error(`web-deepseek-api: unexpected value ${String(value)}`)
388
+ }
389
+ /* v8 ignore stop */
package/src/search.ts ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * DeepSeek Search API provider: one direct request per search, without an
3
+ * auxiliary model request.
4
+ * @module @deepseek-ai/dsh-web-deepseek-api/search
5
+ */
6
+ import type { WebSearchProvider, WebSearchRequest, WebSearchResult } from '@deepseek-ai/dsh-web'
7
+ import {
8
+ dispatchDeepSeekWeb, hasDeepSeekWebCredential, invalidResponse, isRecord, searchAborted,
9
+ type DeepSeekWebAuth, type DeepSeekWebGuidance,
10
+ } from './transport.ts'
11
+
12
+ /** Stable id the Search API provider registers under in the search registry. */
13
+ export const DEEPSEEK_SEARCH_API_PROVIDER_ID = 'deepseek-search-api'
14
+
15
+ /** Default Search and Fetch API base, including its `/v1/tools` prefix; `/search` and `/fetch` are appended. */
16
+ export const DEEPSEEK_WEB_API_BASE_URL = 'https://api.deepseek.com/v1/tools'
17
+
18
+ /** Default Search API result count, the service's own default. */
19
+ export const DEEPSEEK_DEFAULT_COUNT = 10
20
+
21
+ /** Default Search requests started per second, the service's account-wide 5 QPS limit. */
22
+ export const DEEPSEEK_SEARCH_REQUESTS_PER_SECOND = 5
23
+
24
+ /** Longest `ori_question` the Search API accepts, in characters. */
25
+ const ORIGINAL_QUESTION_MAX_CHARS = 128
26
+
27
+ /** Authentication, endpoint, and result settings snapshotted for one search. */
28
+ export interface DeepSeekSearchApiOptions {
29
+ /** Ordered authentication sources of the search; `/search` is appended to the base of the source sent. */
30
+ auth: DeepSeekWebAuth
31
+ /** Settings that endpoint failures of the search name. */
32
+ guidance: DeepSeekWebGuidance
33
+ /** Results requested per search, from 1 through 50; a smaller request bound wins. */
34
+ count: number
35
+ /** Most Search requests this provider starts in any one-second window. */
36
+ requestsPerSecond: number
37
+ /** Read the user question that triggered the search; undefined or blank sends none. */
38
+ originalQuestion?: () => string | undefined
39
+ }
40
+
41
+ /**
42
+ * Validate a Search API response and project its sources into the web service.
43
+ * @param response - untrusted JSON from the Search endpoint.
44
+ * @returns sources with provider order, the display `snippet`, the model-facing `summary`, and nullable
45
+ * publication dates preserved.
46
+ * @throws {@link WebError} when the response does not contain valid search results.
47
+ */
48
+ export function mapSearchResponse(response: unknown): WebSearchResult {
49
+ if (!isRecord(response) || !Array.isArray(response.results)) throw invalidResponse()
50
+ const sources = response.results.map((item: unknown) => {
51
+ if (!isRecord(item) || typeof item.url !== 'string' || item.url.length === 0
52
+ || typeof item.title !== 'string' || typeof item.snippet !== 'string'
53
+ || (item.summary !== undefined && typeof item.summary !== 'string')
54
+ || (item.date !== null && typeof item.date !== 'string')) throw invalidResponse()
55
+ return {
56
+ url: item.url,
57
+ ...item.title.length > 0 ? { title: item.title } : {},
58
+ ...item.snippet.length > 0 ? { snippet: item.snippet } : {},
59
+ ...typeof item.summary === 'string' && item.summary.length > 0 ? { summary: item.summary } : {},
60
+ ...item.date !== null && item.date.length > 0 ? { publishedAt: item.date } : {},
61
+ }
62
+ })
63
+ return { sources, truncated: false }
64
+ }
65
+
66
+ /**
67
+ * Search through the DeepSeek Search API. HTTP redirects fail as `WEB_PROVIDER_ERROR`;
68
+ * failures after dispatch name the endpoint and tell the model how the user can configure it.
69
+ */
70
+ export class DeepSeekSearchApiProvider implements WebSearchProvider {
71
+ readonly id = DEEPSEEK_SEARCH_API_PROVIDER_ID
72
+ /** Monotonic start times (ms) of requests inside the current window, oldest first. */
73
+ private readonly starts: number[] = []
74
+ /** Picker description: what this provider suits and what it costs or cannot do. */
75
+ readonly description: NonNullable<WebSearchProvider['description']> = {
76
+ en: 'Incurs charges, paid by the account or API key chosen under Billing.',
77
+ zh: '会产生费用,由「计费方式」选定的账号或 API Key 支付。',
78
+ ja: '料金が発生し、「課金方法」で選んだアカウントまたは API キーに請求されます。',
79
+ es: 'Genera cargos, que paga la cuenta o la clave de API elegida en Facturación.',
80
+ fr: 'Entraîne des frais, payés par le compte ou la clé API choisi dans Facturation.',
81
+ de: 'Verursacht Kosten, die das unter Abrechnung gewählte Konto oder der API-Schlüssel trägt.',
82
+ ru: 'Услуга платная: оплата идёт с аккаунта или ключа API, выбранного в разделе «Оплата».',
83
+ pt: 'Gera cobranças, pagas pela conta ou chave de API escolhida em Cobrança.',
84
+ }
85
+
86
+ /**
87
+ * @param resolveOptions - the options for the NEXT search, read once at each
88
+ * search's entry so one search never mixes two settings sections.
89
+ */
90
+ constructor(private readonly resolveOptions: () => DeepSeekSearchApiOptions) {}
91
+
92
+ available(): boolean {
93
+ const options = this.resolveOptions()
94
+ return hasDeepSeekWebCredential(options.auth)
95
+ && options.auth.sources.every(source => source.kind === 'misconfigured' || URL.canParse(source.baseURL))
96
+ && isPositiveInteger(options.count) && isPositiveInteger(options.requestsPerSecond)
97
+ }
98
+
99
+ async search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult> {
100
+ const options = this.resolveOptions()
101
+ const question = boundedQuestion(options.originalQuestion?.())
102
+ return dispatchDeepSeekWeb(options.auth, {
103
+ path: '/search',
104
+ body: {
105
+ query: request.query,
106
+ count: Math.min(options.count, request.maxResults ?? options.count),
107
+ need_content: false,
108
+ ...question === undefined ? {} : { ori_question: question },
109
+ },
110
+ decode: mapSearchResponse,
111
+ waitToSend: waitSignal => this.waitForRequestSlot(options.requestsPerSecond, waitSignal),
112
+ guidance: options.guidance,
113
+ }, signal)
114
+ }
115
+
116
+ /**
117
+ * Wait until fewer than `limit` requests started within the last second,
118
+ * inclusive of its first millisecond, then record this start.
119
+ * @throws {@link WebError} `WEB_ABORTED` when `signal` aborts while waiting.
120
+ */
121
+ private async waitForRequestSlot(limit: number, signal?: AbortSignal): Promise<void> {
122
+ for (;;) {
123
+ if (signal?.aborted === true) throw searchAborted(signal)
124
+ const now = performance.now()
125
+ let oldest = this.starts[0]
126
+ while (oldest !== undefined && oldest < now - 1000) {
127
+ this.starts.shift()
128
+ oldest = this.starts[0]
129
+ }
130
+ if (oldest === undefined || this.starts.length < limit) {
131
+ this.starts.push(now)
132
+ return
133
+ }
134
+ await abortableDelay(oldest + 1001 - now, signal)
135
+ }
136
+ }
137
+ }
138
+
139
+ /** Resolve after `ms`, or early when `signal` aborts; the caller rechecks the signal. */
140
+ function abortableDelay(ms: number, signal?: AbortSignal): Promise<void> {
141
+ return new Promise((resolve) => {
142
+ const onAbort = () => {
143
+ clearTimeout(timer)
144
+ resolve()
145
+ }
146
+ const timer = setTimeout(() => {
147
+ signal?.removeEventListener('abort', onAbort)
148
+ resolve()
149
+ }, ms)
150
+ signal?.addEventListener('abort', onAbort, { once: true })
151
+ })
152
+ }
153
+
154
+ /**
155
+ * Bound the triggering question to what `ori_question` accepts: whitespace
156
+ * collapses to single spaces and the first 128 characters remain.
157
+ * @param question - the user question, when one exists.
158
+ * @returns the bounded question, or undefined when nothing remains.
159
+ */
160
+ function boundedQuestion(question: string | undefined): string | undefined {
161
+ const collapsed = question?.replace(/\s+/gu, ' ').trim() ?? ''
162
+ if (collapsed.length === 0) return undefined
163
+ return Array.from(collapsed).slice(0, ORIGINAL_QUESTION_MAX_CHARS).join('')
164
+ }
165
+
166
+ /** True for positive integral request limits. */
167
+ function isPositiveInteger(value: number): boolean {
168
+ return Number.isInteger(value) && value > 0
169
+ }