@magic6/dsh-web-fallback-chain 0.0.0-stage → 0.2.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/package.json CHANGED
@@ -1,6 +1,83 @@
1
1
  {
2
2
  "name": "@magic6/dsh-web-fallback-chain",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.3",
4
+ "description": "Ranked, cost-aware web search and fetch fallback chains for DeepSeek Harness: measured provider ranking, free-only mode, and one settings page.",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "exports": {
8
+ ".": {
9
+ "default": "./src/index.js"
10
+ },
11
+ "./client": "./src/client.js",
12
+ "./cordis.patch.yml": "./cordis.patch.yml",
13
+ "./package.json": "./package.json",
14
+ "./icon.svg": "./icon.svg",
15
+ "./locale/*.json": "./locale/*.json",
16
+ "./icon": "./icon.svg"
17
+ },
18
+ "files": [
19
+ "src",
20
+ "locale",
21
+ "cordis.patch.yml",
22
+ "icon.svg",
23
+ "README.md",
24
+ "README.zh-CN.md",
25
+ "CHANGELOG.md",
26
+ "LICENSE"
27
+ ],
28
+ "scripts": {
29
+ "test": "node --test test/*.test.js",
30
+ "prepublishOnly": "npm test"
31
+ },
32
+ "keywords": [
33
+ "dsh",
34
+ "dsh-plugin",
35
+ "deepseek-harness",
36
+ "cordis",
37
+ "web-search",
38
+ "web-fetch",
39
+ "fallback",
40
+ "provider-chain",
41
+ "cost-aware"
42
+ ],
43
+ "engines": {
44
+ "node": ">=20.0.0",
45
+ "dsh": ">=0.2.2-0 <0.3.0-0"
46
+ },
47
+ "license": "MIT",
48
+ "author": "T-splines",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/T-splines/dsh-web-fallback-chain.git"
52
+ },
53
+ "homepage": "https://github.com/T-splines/dsh-web-fallback-chain#readme",
54
+ "bugs": {
55
+ "url": "https://github.com/T-splines/dsh-web-fallback-chain/issues"
56
+ },
57
+ "peerDependencies": {
58
+ "@deepseek-ai/dsh-web": "^0.2.2-rc.1",
59
+ "@deepseek-ai/schemastery": ">=3.18.2 <4.0.0-0",
60
+ "@deepseek-ai/dsh-credentials": "^0.2.2-rc.1"
61
+ },
62
+ "peerDependenciesMeta": {
63
+ "@deepseek-ai/dsh-credentials": {
64
+ "optional": true
65
+ }
66
+ },
67
+ "dsh": {
68
+ "manifestVersion": 1,
69
+ "bundle": {
70
+ "patch": "./cordis.patch.yml"
71
+ },
72
+ "client": {
73
+ "inject": [
74
+ "@deepseek-ai/dsh-client-ui-settings",
75
+ "@deepseek-ai/dsh-client-locale",
76
+ "@deepseek-ai/dsh-client-ui-plugin-manager",
77
+ "@deepseek-ai/dsh-api-remotes"
78
+ ],
79
+ "platform": "web"
80
+ }
81
+ },
82
+ "icon": "./icon.svg"
83
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Register the fetch chain — an ordered, fall-back fetch provider — with `ctx.web`.
3
+ *
4
+ * ## Why a provider instead of seam configuration
5
+ *
6
+ * The seam selects **one** provider (`fetchProvider`) and refuses to guess when
7
+ * several are usable; its own docs reject a hidden priority chain in config,
8
+ * because a fetch that silently changes transport is a fetch whose provenance is
9
+ * unknowable. The requested behaviour — "DeepSeek first, something local when
10
+ * DeepSeek cannot serve" — is therefore expressed as one explicitly pinned
11
+ * provider: its order is deployment config, and its result says what ran.
12
+ *
13
+ * ## What it does not do
14
+ *
15
+ * It holds no credentials and imports no transport. Each leg is a provider other
16
+ * plugins already registered, so this plugin needs nothing installed beside it
17
+ * and cannot disagree with how those providers are configured. A fake-ip-aware
18
+ * local fetcher (e.g. `dsh-web-fetch-fakeip`, which registers the stock `http`
19
+ * id) is picked up automatically when it is the mounted local fetcher.
20
+ *
21
+ * ## Mounting
22
+ *
23
+ * Mount it, then pin `fetchProvider: fetch-chain` in the same `- id: web` row.
24
+ * Left un-pinned the seam keeps reporting its ambiguity error, which is the
25
+ * intended way to notice a half-configured seam.
26
+ *
27
+ * ## Modes and budget
28
+ *
29
+ * The order is not one list any more: `modeOrders.fetch.<mode>` ranks legs per
30
+ * intent (`brief` / `deep` / `list` / `page`), because the benchmark behind this
31
+ * plugin found the best leg is not the same for "quote me one fact" as for "read
32
+ * me this document". An explicit mode is honoured when the caller passes one;
33
+ * otherwise the URL is classified. `minBodyChars` turns a technically-successful
34
+ * page footer into a miss so the chain actually falls through.
35
+ *
36
+ * @module dsh-web-fallback-chain/chains/fetch-plugin
37
+ */
38
+
39
+ import { CHAIN_FETCH_PROVIDER_ID, readField } from '../config.js'
40
+
41
+ export { CHAIN_FETCH_PROVIDER_ID, readField }
42
+ import { resolveLegs, runChain } from './fetch.js'
43
+ import { mergeProviders, resolveOrder, DEFAULT_MODE, MODES } from '../policy/index.js'
44
+
45
+ /** Cordis plugin name used by loader diagnostics. */
46
+
47
+
48
+ /** The web seam this provider registers into. */
49
+
50
+
51
+ export { describeAttempts, fallbackMarker, finalize, chainError } from './fetch.js'
52
+
53
+ /**
54
+ * Register the chain with `ctx.web`.
55
+ *
56
+ * The fields are volatile (see config.js): their values are read per call, so a
57
+ * save on the generated settings page takes effect on the next fetch without a
58
+ * restart. Mount-time validation still runs on the initial value — a typo caught
59
+ * at mount is a startup error, while a typo saved later degrades to an
60
+ * `unregistered` attempt instead of taking the service down.
61
+ *
62
+ * @param ctx - context whose `web` service receives the provider.
63
+ * @param config - resolved plugin configuration (values or volatile getters).
64
+ */
65
+ export function applyFetchChain(ctx, config) {
66
+ /**
67
+ * Validate the configured orders.
68
+ *
69
+ * Deliberately *not* called at mount: these fields are `volatile()`, and at
70
+ * `apply()` time this plugin's injection may not be complete, in which case
71
+ * schemastery throws `cannot get property "X" without inject`. Reading them at
72
+ * mount to validate would mean a healthy deployment fails to start over a
73
+ * diagnostic. Validation therefore runs on the first resolve — the point where
74
+ * the values are known good — and a bad configuration still fails loudly, just
75
+ * one call later, with the same message.
76
+ */
77
+ let validated = false
78
+ const validateOrders = (flat, fetchModes) => {
79
+ if (validated) return
80
+ // An empty `order` with no `modeOrders.fetch` is NOT an error: it means "use the
81
+ // shipped per-mode defaults", which is exactly what a fresh install has. Treating
82
+ // it as fatal made `available()` return false (the throw was swallowed by its
83
+ // catch), so dsh reported `web provider "fetch-chain" is registered but
84
+ // unavailable` on a deployment with nothing wrong with it.
85
+ // A mode name the resolver does not know would silently fall back to the
86
+ // classifier, which looks like the setting being ignored. Refuse it instead.
87
+ for (const mode of Object.keys(fetchModes ?? {})) {
88
+ if (!MODES.includes(mode)) {
89
+ throw new Error(`web-fetch-chain: \`modeOrders.fetch.${mode}\` is not a mode (known: ${MODES.join(', ')})`)
90
+ }
91
+ }
92
+ // Fail loud instead of recursing at fetch time.
93
+ const mentionsSelf = (ids) => Array.isArray(ids) && ids.includes(CHAIN_FETCH_PROVIDER_ID)
94
+ if (mentionsSelf(flat) || Object.values(fetchModes ?? {}).some(mentionsSelf)) {
95
+ throw new Error(`web-fetch-chain: an order cannot include "${CHAIN_FETCH_PROVIDER_ID}" (the chain itself)`)
96
+ }
97
+ validated = true
98
+ }
99
+
100
+ /**
101
+ * Which leg ids to attempt for one call.
102
+ *
103
+ * Precedence, cheapest decision first:
104
+ * 1. `modeOrders.fetch[<mode>]` when configured — the user's own ranking.
105
+ * 2. The shipped per-mode default (`dsh-web-chain-core`), which encodes the
106
+ * benchmark ranking rather than a guess.
107
+ * 3. The legacy flat `order`, which is what a pre-modes deployment has.
108
+ *
109
+ * `freeOnly` then removes billed legs without re-sorting the survivors, so
110
+ * flipping the switch is exactly reversible.
111
+ */
112
+ const ordersFor = (request) => {
113
+ const providers = mergeProviders(readField(config, 'providers', {}))
114
+ const flat = readField(config, 'order', [])
115
+ const configured = readField(config, 'modeOrders', {}) ?? {}
116
+ const fetchModes = configured.fetch ?? {}
117
+ validateOrders(flat, fetchModes)
118
+
119
+ // Resolve the mode first, so we know whether the user configured *this* one.
120
+ const prefs = { modeOrders: configured, defaultMode: readField(config, 'defaultMode', DEFAULT_MODE), freeOnly: false }
121
+ const { mode } = resolveOrder({ capability: 'fetch', request, config: prefs, providers })
122
+
123
+ // A mode the user configured uses their ranking. A mode they did not
124
+ // configure falls back to the flat order — NOT to a shipped per-mode default,
125
+ // because those name legs the deployment may never have mounted. Switching a
126
+ // deployment onto providers it did not choose would be a surprise, so the
127
+ // shipped defaults are only used when no flat order exists either.
128
+ const configuredForMode = Array.isArray(fetchModes[mode]) && fetchModes[mode].length > 0
129
+ const base = configuredForMode
130
+ ? fetchModes[mode]
131
+ : (flat.length > 0 ? flat : (resolveOrder({ capability: 'fetch', request, config: prefs, providers }).order))
132
+
133
+ const freeOnly = readField(config, 'freeOnly', true) === true
134
+ const order = freeOnly ? base.filter((id) => providers[id]?.cost !== 'paid') : base
135
+ return {
136
+ mode,
137
+ order,
138
+ skippedForCost: base.filter((id) => !order.includes(id)),
139
+ }
140
+ }
141
+
142
+ // One diagnostic per distinct reason, so a per-request call does not flood the log.
143
+ const complained = new Set()
144
+ const complain = (what, error) => {
145
+ const message = `${what}: ${error instanceof Error ? error.message : String(error)}`
146
+ if (complained.has(message)) return
147
+ complained.add(message)
148
+ try {
149
+ ctx.logger?.warn?.(`web-fallback: fetch chain reports unavailable — %s`, message)
150
+ } catch {
151
+ // A logger that throws must not turn a diagnostic into a second failure.
152
+ }
153
+ }
154
+
155
+ const provider = {
156
+ id: CHAIN_FETCH_PROVIDER_ID,
157
+ /**
158
+ * Usable when at least one configured provider is registered and reports
159
+ * itself usable. Never makes a network call (the seam requires that).
160
+ */
161
+ available: () => {
162
+ // `available()` must never throw — the seam calls it to choose a provider, and a
163
+ // throw there surfaces as the opaque "registered but unavailable". But swallowing
164
+ // the reason made a misconfigured order look like a deployment with no keys: the
165
+ // only way to find out was to read this file. So: still return false, but say why
166
+ // once, on the host log.
167
+ try {
168
+ const { legs } = resolveLegs(ctx.web.fetchProviders, ordersFor({ url: '' }).order, CHAIN_FETCH_PROVIDER_ID)
169
+ return legs.some((leg) => {
170
+ try {
171
+ return leg.provider.available() === true
172
+ } catch (error) {
173
+ complain('a leg threw from available()', error)
174
+ return false
175
+ }
176
+ })
177
+ } catch (error) {
178
+ complain('the chain could not resolve its order', error)
179
+ return false
180
+ }
181
+ },
182
+ fetch: (request, signal) => {
183
+ // Resolved per fetch: another plugin may have (un)mounted a leg since mount,
184
+ // and the settings page may have rewritten the order since the last call.
185
+ const { order } = ordersFor(request)
186
+ const { legs, missing } = resolveLegs(ctx.web.fetchProviders, order, CHAIN_FETCH_PROVIDER_ID)
187
+ return runChain(legs, missing, {
188
+ annotateFallback: readField(config, 'annotateFallback', true),
189
+ minBodyChars: readField(config, 'minBodyChars', 0),
190
+ }, request, signal)
191
+ },
192
+ }
193
+
194
+ ctx.web.registerFetchProvider(provider)
195
+
196
+ // Reading a volatile() field needs injection to be complete; at apply() time it
197
+ // may not be, and schemastery then throws `cannot get property "X" without
198
+ // inject`. The order is wanted only for this log line, so a failure must not
199
+ // take the provider down — the chain resolves lazily on the first fetch.
200
+ try {
201
+ const initial = ordersFor({ url: '' })
202
+ ctx.logger?.info?.(
203
+ `web-fetch-chain: registered as "${CHAIN_FETCH_PROVIDER_ID}" (mode=${initial.mode}) order [${initial.order.join(' → ')}]`
204
+ + (readField(config, 'freeOnly', true) === true ? ' (free only)' : '')
205
+ + (readField(config, 'annotateFallback', true) === false ? ' (fallback annotation off)' : '')
206
+ + (readField(config, 'minBodyChars', 0) > 0 ? ` (min body ${readField(config, 'minBodyChars', 0)}c)` : ''),
207
+ )
208
+ } catch (error) {
209
+ ctx.logger?.info?.(
210
+ `web-fetch-chain: registered as "${CHAIN_FETCH_PROVIDER_ID}"; order resolves on first fetch (${String(error?.message ?? error).slice(0, 120)})`,
211
+ )
212
+ }
213
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * The chain: resolve the configured provider ids against the live registry, try
3
+ * them in order, return the first result, and make a degraded fetch legible.
4
+ *
5
+ * Three rules this file exists to enforce:
6
+ *
7
+ * 1. **No silent degradation.** A fallback that succeeds looks exactly like a
8
+ * first-choice success to the model, so the winner's provenance is appended
9
+ * to the body (configurable) and every attempt is reported on the error when
10
+ * nothing succeeds. A page fetched locally because DeepSeek was out of budget
11
+ * must not read like a page fetched by DeepSeek.
12
+ * 2. **Resolution happens per fetch, not per mount.** Providers are mounted by
13
+ * other plugins in whatever order the profile lists them; resolving at call
14
+ * time means the chain never holds a stale view of the seam.
15
+ * 3. **Cancellation is not a failure.** Once the caller's signal is aborted the
16
+ * chain rethrows instead of quietly trying the next leg — a cancelled fetch
17
+ * must not turn into a real request on another transport.
18
+ *
19
+ * @module dsh-web-fallback-chain/chains/fetch
20
+ */
21
+
22
+ import { WebError } from '@deepseek-ai/dsh-web'
23
+
24
+ /** How much of a provider's message is kept in the attempt record. */
25
+ const MESSAGE_LIMIT = 300
26
+
27
+ /** Shorten a message for the attempt record; the full error stays as `cause`. */
28
+ function shorten(value) {
29
+ const text = String(value ?? '')
30
+ return text.length > MESSAGE_LIMIT ? `${text.slice(0, MESSAGE_LIMIT)}…` : text
31
+ }
32
+
33
+ /** The machine-routable code of a provider failure, or a neutral fallback. */
34
+ function codeOf(error) {
35
+ const code = error?.code
36
+ return typeof code === 'string' && code.length > 0 ? code : 'WEB_PROVIDER_ERROR'
37
+ }
38
+
39
+ /** One line describing an earlier attempt, used in the marker and the error. */
40
+ export function describeAttempt(attempt) {
41
+ const parts = [`${attempt.leg}=${attempt.outcome}`]
42
+ if (attempt.code !== undefined) parts.push(`(${attempt.code})`)
43
+ if (attempt.length !== undefined) parts.push(`[${attempt.length}c]`)
44
+ return parts.join('')
45
+ }
46
+
47
+ /**
48
+ * The character length of a fetch result's body.
49
+ *
50
+ * Reads `body.content` rather than serialising the result, because the length
51
+ * floor is about how much text the model would receive, not about metadata.
52
+ *
53
+ * @param result - a fetch result.
54
+ * @returns the content length, or 0 when there is no body.
55
+ */
56
+ export function bodyLength(result) {
57
+ const content = result?.body?.content
58
+ return typeof content === 'string' ? content.length : 0
59
+ }
60
+
61
+ /** Render the attempt list for humans and for the model. */
62
+ export function describeAttempts(attempts) {
63
+ return attempts.map(describeAttempt).join(', ')
64
+ }
65
+
66
+ /**
67
+ * Resolve the configured order against the live registry.
68
+ *
69
+ * @param registry - `ctx.web.fetchProviders` (`Map<id, WebFetchProvider>`).
70
+ * @param order - configured provider ids.
71
+ * @param selfId - the chain's own id, refused to prevent infinite recursion.
72
+ * @returns `{legs, missing}` where a missing id is reported, never dropped.
73
+ */
74
+ export function resolveLegs(registry, order, selfId) {
75
+ const legs = []
76
+ const missing = []
77
+ for (const id of order ?? []) {
78
+ if (id === selfId) {
79
+ throw new WebError(`web fetch chain cannot include itself ("${selfId}") in its order`, 'WEB_PROVIDER_ERROR')
80
+ }
81
+ const provider = registry?.get?.(id)
82
+ if (provider === undefined) missing.push(id)
83
+ else legs.push({ label: id, provider })
84
+ }
85
+ return { legs, missing }
86
+ }
87
+
88
+ /**
89
+ * Build the provenance marker appended to a fallback fetch's body.
90
+ *
91
+ * Deliberately one short line at the end: it travels with the content, so any
92
+ * consumer that reads the body sees the degradation, and it disappears entirely
93
+ * when the first leg serves.
94
+ */
95
+ export function fallbackMarker(attempts, winner) {
96
+ // `unregistered` legs are named in the attempt list because a *configured* id that
97
+ // does not resolve is a real problem worth seeing. But a leg the deployment never
98
+ // mounted (the local `http` fetcher belongs to another plugin) is not "an earlier leg
99
+ // that did not serve" — it was never a candidate. Filtering it keeps the marker about
100
+ // what actually happened, which is the only reason to print it at all.
101
+ // Every attempt is reported, including `unregistered` ones: a configured id that
102
+ // resolves to nothing is a real fault and dropping it is how it stays invisible.
103
+ //
104
+ // What changed is only that a CLEAN fetch no longer gets a marker. Printing
105
+ // "earlier legs: http=unregistered" when the first leg served was noise — `http` is
106
+ // normally supplied by another plugin, so it is expected to be absent here.
107
+ const earlier = attempts.slice(0, -1)
108
+ if (earlier.length === 0) return ''
109
+
110
+ // Everything is reported. An `unregistered` id means a provider the order names is
111
+ // not mounted, and dropping that from the marker would hide exactly the
112
+ // misconfiguration worth knowing about ("I asked for deepseek-fetch-rich and nothing
113
+ // said it was missing"). The marker is kept short instead: only blockers are listed,
114
+ // and a clean fetch with nothing but absent legs still says so in a few characters.
115
+ return `\n\n---\n[fetch-chain] this page was retrieved by the "${winner}" leg; earlier legs did not serve: ${describeAttempts(earlier)}`
116
+ }
117
+
118
+ /**
119
+ * Attach provenance to a result whose leg was not the first attempt.
120
+ *
121
+ * @param result - the winning leg's result.
122
+ * @param attempts - every attempt, winner last.
123
+ * @param annotate - whether to append the marker.
124
+ * @returns the result, annotated when a fallback happened.
125
+ */
126
+ export function finalize(result, attempts, annotate) {
127
+ if (!annotate || attempts.length <= 1) return result
128
+ const winner = attempts[attempts.length - 1].leg
129
+ const marker = fallbackMarker(attempts, winner)
130
+ return {
131
+ ...result,
132
+ body: { ...result.body, content: `${result.body.content}${marker}` },
133
+ }
134
+ }
135
+
136
+ /**
137
+ * The error thrown when no leg served: every attempt is named, so the failure is
138
+ * attributable rather than a generic "fetch failed".
139
+ */
140
+ export function chainError(url, attempts, cause) {
141
+ const error = new WebError(
142
+ `web fetch chain failed for ${url}: ${describeAttempts(attempts)}`,
143
+ attempts.some((attempt) => attempt.outcome === 'failed') ? 'WEB_PROVIDER_ERROR' : 'WEB_PROVIDER_UNAVAILABLE',
144
+ cause === undefined ? undefined : { cause },
145
+ )
146
+ error.attempts = attempts
147
+ return error
148
+ }
149
+
150
+ /**
151
+ * Run the legs in order and return the first result.
152
+ *
153
+ * @param legs - resolved legs, in order.
154
+ * @param missing - configured ids with no registered provider.
155
+ * @param options - `{annotateFallback, minBodyChars}`.
156
+ * @param request - the seam's fetch request.
157
+ * @param signal - cancellation signal forwarded to every leg.
158
+ * @returns the winning result, annotated when a fallback happened.
159
+ * @throws {WebError} when no leg served, or when the caller aborted.
160
+ */
161
+ export async function runChain(legs, missing, options, request, signal) {
162
+ const attempts = missing.map((id) => ({ leg: id, outcome: 'unregistered', code: 'WEB_PROVIDER_CONFIGURED_MISSING' }))
163
+ const floor = Number.isFinite(options?.minBodyChars) ? options.minBodyChars : 0
164
+ if (legs.length === 0) {
165
+ throw chainError(
166
+ request?.url,
167
+ attempts.length > 0 ? attempts : [{ leg: 'none', outcome: 'unavailable', code: 'WEB_PROVIDER_UNAVAILABLE' }],
168
+ )
169
+ }
170
+ let firstError
171
+ let shortest = null
172
+ for (const leg of legs) {
173
+ let usable = false
174
+ try {
175
+ usable = leg.provider.available() === true
176
+ } catch (error) {
177
+ attempts.push({ leg: leg.label, outcome: 'unavailable', code: codeOf(error), message: shorten(error?.message) })
178
+ continue
179
+ }
180
+ if (!usable) {
181
+ attempts.push({ leg: leg.label, outcome: 'unavailable', code: 'WEB_PROVIDER_UNAVAILABLE' })
182
+ continue
183
+ }
184
+ try {
185
+ const result = await leg.provider.fetch(request, signal)
186
+ const length = bodyLength(result)
187
+ // The floor is off by default and is a deliberate re-fetch trigger when set:
188
+ // "my sites are all long, so a stub means extraction failed". It is NOT a quality
189
+ // judgement — length cannot distinguish a footer from a short real page, and using
190
+ // it that way replaced a correct 156-character answer with 958 characters of the
191
+ // same paragraph in six languages.
192
+ if (floor > 0 && length < floor) {
193
+ // Successful transport, payload below the configured floor: record and continue.
194
+ attempts.push({ leg: leg.label, outcome: 'short', statusCode: result.statusCode, length })
195
+ if (shortest === null || length > shortest.length) shortest = { leg: leg.label, length, result }
196
+ continue
197
+ }
198
+ attempts.push({ leg: leg.label, outcome: 'served', statusCode: result.statusCode, length })
199
+ return finalize(result, attempts, options.annotateFallback !== false)
200
+ } catch (error) {
201
+ attempts.push({ leg: leg.label, outcome: 'failed', code: codeOf(error), message: shorten(error?.message) })
202
+ if (firstError === undefined) firstError = error
203
+ // A cancelled fetch is the caller's decision, not the leg's failure.
204
+ if (signal?.aborted) throw error
205
+ }
206
+ }
207
+ // Every leg came back short. Returning the longest beats returning nothing, as
208
+ // long as the caller can see that it happened.
209
+ if (shortest !== null) {
210
+ // The chosen leg was already recorded as a `short` attempt. Promote that
211
+ // record instead of appending a second one, so the marker reads
212
+ // "a=short[100c], b=short[400c]" once each rather than repeating the winner.
213
+ const index = attempts.findIndex((a) => a.leg === shortest.leg && a.outcome === 'short')
214
+ const record = { leg: shortest.leg, outcome: 'short', statusCode: shortest.result.statusCode, length: shortest.length }
215
+ if (index >= 0) attempts[index] = record
216
+ else attempts.push(record)
217
+ // Re-order so the winner is last: finalize treats the last entry as the leg
218
+ // that served, and every earlier one as a leg that did not.
219
+ const winner = attempts.splice(attempts.indexOf(record), 1)[0]
220
+ attempts.push(winner)
221
+ return finalize(shortest.result, attempts, options.annotateFallback !== false)
222
+ }
223
+ throw chainError(request?.url, attempts, firstError)
224
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Register the search chain with `ctx.web`.
3
+ *
4
+ * Kept apart from `./search.js` so the execution logic stays testable without a
5
+ * context: this file is the only part that knows about `ctx`.
6
+ *
7
+ * @module dsh-web-fallback-chain/chains/search-plugin
8
+ */
9
+
10
+ import { CHAIN_SEARCH_PROVIDER_ID, readField } from '../config.js'
11
+
12
+ export { CHAIN_SEARCH_PROVIDER_ID, readField }
13
+ import { mergeProviders, resolveOrder, DEFAULT_MODE, MODES } from '../policy/index.js'
14
+ import { capSources, finalize, resolveLegs, runSearchChain } from './search.js'
15
+
16
+ export function applySearchChain(ctx, config) {
17
+ /**
18
+ * Validate the configured mode names, on first resolve rather than at mount.
19
+ *
20
+ * These fields are `volatile()`, and reading them during `apply()` may run
21
+ * before injection completes, where schemastery throws. A bad mode name still
22
+ * fails loudly — just on the first search instead of at startup.
23
+ */
24
+ let validated = false
25
+ const validateModes = (searchModes) => {
26
+ if (validated) return
27
+ for (const mode of Object.keys(searchModes ?? {})) {
28
+ if (!MODES.includes(mode)) {
29
+ throw new Error(`web-search-chain: \`modeOrders.search.${mode}\` is not a mode (known: ${MODES.join(', ')})`)
30
+ }
31
+ }
32
+ validated = true
33
+ }
34
+
35
+ const ordersFor = (request) => {
36
+ const providers = mergeProviders(readField(config, 'providers', {}))
37
+ const flat = readField(config, 'searchOrder', [])
38
+ const configured = readField(config, 'modeOrders', {}) ?? {}
39
+ const searchModes = configured.search ?? {}
40
+ validateModes(searchModes)
41
+ const prefs = { modeOrders: configured, defaultMode: readField(config, 'defaultMode', DEFAULT_MODE), freeOnly: false }
42
+ const { mode } = resolveOrder({ capability: 'search', request, config: prefs, providers })
43
+ const configuredForMode = Array.isArray(searchModes[mode]) && searchModes[mode].length > 0
44
+ const base = configuredForMode
45
+ ? searchModes[mode]
46
+ : (flat.length > 0 ? flat : resolveOrder({ capability: 'search', request, config: prefs, providers }).order)
47
+ const freeOnly = readField(config, 'freeOnly', true) === true
48
+ const order = freeOnly ? base.filter((id) => providers[id]?.cost !== 'paid') : base
49
+ return { mode, order, skippedForCost: base.filter((id) => !order.includes(id)) }
50
+ }
51
+
52
+ /** The per-source budget for the mode, read from the winning leg's metadata. */
53
+ const capFor = (mode, order) => {
54
+ const providers = mergeProviders(readField(config, 'providers', {}))
55
+ const winner = order[0]
56
+ const caps = winner === undefined ? undefined : providers[winner]?.maxChars
57
+ const cap = caps?.[mode]
58
+ return typeof cap === 'number' ? cap : null
59
+ }
60
+
61
+ const provider = {
62
+ id: CHAIN_SEARCH_PROVIDER_ID,
63
+ available: () => {
64
+ try {
65
+ const { order } = ordersFor({ query: '' })
66
+ const { legs } = resolveLegs(ctx.web.searchProviders, order, CHAIN_SEARCH_PROVIDER_ID)
67
+ return legs.some((leg) => {
68
+ try {
69
+ return leg.provider.available() === true
70
+ } catch {
71
+ return false
72
+ }
73
+ })
74
+ } catch {
75
+ return false
76
+ }
77
+ },
78
+ search: (request, signal) => {
79
+ const { mode, order } = ordersFor(request)
80
+ const { legs, missing } = resolveLegs(ctx.web.searchProviders, order, CHAIN_SEARCH_PROVIDER_ID)
81
+ return runSearchChain(legs, missing, {
82
+ annotateFallback: readField(config, 'annotateFallback', true),
83
+ cap: capFor(mode, order),
84
+ }, request, signal)
85
+ },
86
+ }
87
+
88
+ ctx.web.registerSearchProvider(provider)
89
+
90
+ // Resolve the initial order defensively.
91
+ //
92
+ // Reading a `volatile()` field needs the plugin's injection to be complete, and
93
+ // at `apply()` time it may not be: schemastery then throws
94
+ // `cannot get property "X" without inject`. The order is wanted only for the
95
+ // startup log line, so a failure here must not take the provider down — the
96
+ // chain resolves lazily on the first real call, which runs after injection.
97
+ try {
98
+ const initial = ordersFor({ query: '' })
99
+ ctx.logger?.info?.(
100
+ `web-search-chain: registered as "${CHAIN_SEARCH_PROVIDER_ID}" (mode=${initial.mode}) order [${initial.order.join(' → ')}]`
101
+ + (readField(config, 'freeOnly', true) === true ? ' (free only)' : ''),
102
+ )
103
+ } catch (error) {
104
+ ctx.logger?.info?.(
105
+ `web-search-chain: registered as "${CHAIN_SEARCH_PROVIDER_ID}"; order resolves on first search (${String(error?.message ?? error).slice(0, 120)})`,
106
+ )
107
+ }
108
+ }