@magic6/dsh-web-fallback-chain 0.0.0-stage → 0.2.4

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/config.js ADDED
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Plugin configuration for `dsh-web-fallback-chain`.
3
+ *
4
+ * One schema, one page. The chains, the vendors and the shared policy used to be
5
+ * four packages with four schemas, which meant four settings pages and a user
6
+ * who had to know which one to open. They are one plugin now: everything that a
7
+ * deployment can reasonably want to change is a field here.
8
+ *
9
+ * ## Why these fields are `volatile()`
10
+ *
11
+ * A volatile field is what puts an entry on the dsh settings surface: the
12
+ * settings service describes only the volatile subset of a plugin's schema, and
13
+ * the browser generates the page from it — dsh's own components, no custom form
14
+ * to keep in sync. Writes land in the active profile's patch (the same file a
15
+ * deployment configures by hand) and apply live, so reordering the chain needs
16
+ * no restart.
17
+ *
18
+ * A volatile field reaches the plugin as a getter (`{ get(): T }`) because its
19
+ * value may change while the service runs. `readField` below accepts both shapes,
20
+ * so plain objects (tests, non-UI callers) work unchanged.
21
+ *
22
+ * ## Reading volatile fields
23
+ *
24
+ * Reading one before this plugin's injection completes throws
25
+ * `cannot get property "X" without inject`. Nothing here reads config at mount
26
+ * for that reason: validation and resolution happen on the first real call.
27
+ *
28
+ * @module dsh-web-fallback-chain/config
29
+ */
30
+
31
+ import z from '@deepseek-ai/schemastery'
32
+ import { MODES } from './policy/modes.js'
33
+
34
+ /** Provider id the fetch chain registers; pin it as `fetchProvider`. */
35
+ export const CHAIN_FETCH_PROVIDER_ID = 'fetch-chain'
36
+
37
+ /** Provider id the search chain registers; pin it as `searchProvider`. */
38
+ export const CHAIN_SEARCH_PROVIDER_ID = 'search-chain'
39
+
40
+ /** Server-side DeepSeek legs. Both bill per successful request. */
41
+ export const DEEPSEEK_SEARCH_PROVIDER_ID = 'deepseek-search-rich'
42
+ export const DEEPSEEK_FETCH_PROVIDER_ID = 'deepseek-fetch-rich'
43
+
44
+ /** The local HTTP(S) fetcher's id, whoever mounts it. */
45
+ export const LOCAL_FETCH_PROVIDER_ID = 'http'
46
+
47
+ /**
48
+ * Read one config field, accepting both a resolved value and a volatile getter.
49
+ *
50
+ * Resolution is per call on purpose: a settings-page edit must reach the next
51
+ * search or fetch without remounting the plugin.
52
+ *
53
+ * @param config - resolved plugin config (plain values or volatile getters).
54
+ * @param key - field name.
55
+ * @param fallback - value used when the field is absent.
56
+ * @returns the current value.
57
+ */
58
+ export function readField(config, key, fallback) {
59
+ const raw = config?.[key]
60
+ const value = raw !== null && typeof raw === 'object' && typeof raw.get === 'function' ? raw.get() : raw
61
+ return value === undefined ? fallback : value
62
+ }
63
+
64
+ /**
65
+ * Move billed providers last, preserving relative order inside each group.
66
+ *
67
+ * A stable partition rather than a sort: the configured order keeps deciding
68
+ * everything except which side of the paid/free line each leg sits on, so turning
69
+ * the switch on and off is exactly reversible.
70
+ *
71
+ * `paid` is supplied by the caller from the merged provider metadata. The default
72
+ * list exists only so a caller with no metadata still gets sane behaviour;
73
+ * deriving from metadata is always preferred, because a hard-coded list goes stale
74
+ * the moment a new billed leg is added.
75
+ *
76
+ * @param order - configured provider ids.
77
+ * @param paid - ids that bill per request.
78
+ * @returns the effective order.
79
+ */
80
+ export function paidLast(order, paid = [DEEPSEEK_FETCH_PROVIDER_ID, DEEPSEEK_SEARCH_PROVIDER_ID]) {
81
+ const billed = Array.isArray(paid) ? paid : []
82
+ return [
83
+ ...order.filter((id) => !billed.includes(id)),
84
+ ...order.filter((id) => billed.includes(id)),
85
+ ]
86
+ }
87
+
88
+ /**
89
+ * One provider-metadata override, as a user would write it in the patch.
90
+ *
91
+ * Permissive on purpose: `policy/providers.js` validates the merged result and
92
+ * reports the offending id and field, so this schema does not duplicate those
93
+ * rules and cannot drift from them.
94
+ */
95
+ const ProviderOverride = z.object({
96
+ cost: z.union([z.const('free'), z.const('paid')]).description('是否计费;freeOnly 只读取这一项'),
97
+ quality: z.number().min(0).max(10).description('排序用 0–10 分,越大越靠前'),
98
+ maxChars: z.dict(z.number()).description('按模式的每条字符预算,如 { brief: 300, deep: 1200 }'),
99
+ requiresKey: z.string().description('需要的环境变量名,仅用于预检提示'),
100
+ kinds: z.array(z.string()).description('该档能提供的能力:search / fetch'),
101
+ note: z.string().description('给人看的一行说明'),
102
+ }).description('覆盖或新增一个 provider 的元数据')
103
+
104
+ const modeUnion = z.union(MODES.map((m) => z.const(m)))
105
+
106
+ export const Config = z.object({
107
+ // ─── the switch that matters ─────────────────────────────────────────────
108
+
109
+ /**
110
+ * Skip every provider whose metadata says `cost: paid`.
111
+ *
112
+ * On by default. Measured: the billed fetch leg returned a site footer (332 and
113
+ * 142 characters) with HTTP 200 on several sites, so it "succeeded" while
114
+ * serving nothing and the chain never fell through. A free leg that fails
115
+ * loudly is easier to recover from than a paid leg that quietly succeeds.
116
+ */
117
+ freeOnly: z.boolean().default(true).volatile()
118
+ .description('仅使用免费工具。打开后,链里标记为 paid 的档会被跳过'),
119
+
120
+ /**
121
+ * Mode used when the request does not imply one.
122
+ *
123
+ * Delivery detail: the model-facing `web_search` / `web_fetch` tools accept
124
+ * only `{queries}` / `{url}` and the seam has no channel for a mode, so in
125
+ * practice a URL's shape or the query's shape decides. This is the fallback
126
+ * for the cases the classifier cannot place.
127
+ */
128
+ defaultMode: modeUnion.default('brief').volatile()
129
+ .description('无法判断意图时用的模式。brief 最省 token,deep 要全文'),
130
+
131
+ // ─── per-mode ranking ────────────────────────────────────────────────────
132
+
133
+ /**
134
+ * Per-capability, per-mode orders: `{ fetch: { brief: [...] }, search: {...} }`.
135
+ *
136
+ * Empty means the shipped per-mode defaults, which encode this repository's
137
+ * benchmark ranking. A mode you do not configure falls back to `order`; if `order`
138
+ * is empty too, the shipped list applies, which is how the no-config default works.
139
+ */
140
+ modeOrders: z.dict(z.dict(z.array(z.string())))
141
+ .description('按模式排的档位顺序,如 { fetch: { brief: [http, anysearch] } }')
142
+ .volatile(),
143
+
144
+ /**
145
+ * Flat order, used for any mode `modeOrders` does not cover.
146
+ *
147
+ * Empty is valid when `modeOrders` is configured, which is the recommended
148
+ * shape: the shipped defaults are per-mode and better than one flat list.
149
+ */
150
+ order: z.array(z.string()).default([])
151
+ .description('抓取链:未在 modeOrders.fetch 中配置的模式使用的顺序')
152
+ .volatile(),
153
+
154
+ /**
155
+ * The search chain's flat order, symmetric with `order`.
156
+ *
157
+ * Separate from `order` on purpose: one key shared by both capabilities means
158
+ * editing the fetch ranking silently rewrites the search ranking. They are
159
+ * different questions and get different answers.
160
+ */
161
+ searchOrder: z.array(z.string()).default([])
162
+ .description('搜索链:未在 modeOrders.search 中配置的模式使用的顺序')
163
+ .volatile(),
164
+
165
+ // ─── the fetch chain's floor ─────────────────────────────────────────────
166
+
167
+ /**
168
+ * A fetched body shorter than this counts as a miss, so the chain continues.
169
+ *
170
+ * **Off by default (0).** It was 600, and that turned out to be worse than the
171
+ * problem it solved. Length cannot tell a site footer (142–332 chars) apart from a
172
+ * legitimately short page: `example.com` has 171 characters of real content, and
173
+ * under the 600 floor it was rejected, so the chain fell through to a leg that
174
+ * happened to return 958 characters — the same paragraph repeated in six languages.
175
+ * A longer, worse answer that looks like a success.
176
+ *
177
+ * Only HTTP status decides now. When this is left at 0 every 2xx/4xx payload is
178
+ * returned as fetched, and the provenance marker records how many characters each
179
+ * leg produced, so an unusually short answer is visible rather than silently
180
+ * replaced. Set it above 0 only if you know your sites are all long.
181
+ */
182
+ minBodyChars: z.number().min(0).default(0).volatile()
183
+ .description('抓取正文少于这个字符数算未命中,继续下一档。默认 0 = 关闭:只看 HTTP 状态'),
184
+
185
+ // ─── legible degradation ─────────────────────────────────────────────────
186
+
187
+ /**
188
+ * Append a one-line provenance marker when an earlier leg did not serve.
189
+ *
190
+ * A degraded fetch that is indistinguishable from a clean one is a fetch whose
191
+ * reliability you cannot reason about. Off only for byte-comparison tests.
192
+ */
193
+ annotateFallback: z.boolean().default(true).volatile()
194
+ .description('回落发生在正文/首条结果末尾留一行说明,不静默降级'),
195
+
196
+ // ─── which legs to mount ─────────────────────────────────────────────────
197
+
198
+ /**
199
+ * Which legs this plugin registers. Empty means all of them.
200
+ *
201
+ * A leg whose key is missing still registers and reports `available() === false`,
202
+ * so the chain names it in the attempts instead of looking unconfigured.
203
+ */
204
+ enable: z.array(z.string())
205
+ .description('挂载哪些档;留空=全部。无 key 的档仍注册但自报不可用')
206
+ .volatile(),
207
+
208
+ // ─── provider metadata ───────────────────────────────────────────────────
209
+
210
+ /**
211
+ * Provider metadata: cost, quality, per-mode budget.
212
+ *
213
+ * Redeclaring a built-in id patches it field-by-field; a new id adds a leg this
214
+ * plugin never tested, which then participates in ordering, `freeOnly` and the
215
+ * per-mode budget exactly like a built-in.
216
+ */
217
+ providers: z.dict(ProviderOverride).default({}).volatile()
218
+ .description('覆盖内置档的元数据,或新增你自己的档'),
219
+
220
+ // ─── transport ───────────────────────────────────────────────────────────
221
+
222
+ timeoutMs: z.number().min(1000).default(30000).volatile()
223
+ .description('单次请求超时(毫秒)'),
224
+
225
+ /** Send `need_content: true` to DeepSeek search (same price, ~9× the payload). */
226
+ deepseekNeedContent: z.boolean().default(false).volatile()
227
+ .description('DeepSeek 搜索返回全文(不额外计费,但响应大很多)'),
228
+
229
+ /**
230
+ * AnySearch vertical domain tag, e.g. `code.doc` or `finance.quote`.
231
+ *
232
+ * Empty means general web search. A tag changes what the query *means*, not
233
+ * just its ranking: `cordis registerService` under `general.general` returns the
234
+ * EU research database CORDIS; under `code.doc` it returns the actual source
235
+ * docs. Explicit opt-in for that reason.
236
+ */
237
+ anysearchTag: z.string().default('').volatile()
238
+ .description('AnySearch 垂直域,如 code.doc / academic.paper;留空=通用搜索'),
239
+
240
+ /** Extra AnySearch vertical params, as `key=value,key2=value2`. */
241
+ anysearchParams: z.string().default('').volatile()
242
+ .description('垂直域的必填参数,如 library=cordis'),
243
+ })
244
+
245
+ export default Config
package/src/index.js ADDED
@@ -0,0 +1,137 @@
1
+ /**
2
+ * `dsh-web-fallback-chain` — one plugin that gives the web seam a ranked, cost-aware
3
+ * fallback chain for both search and fetch.
4
+ *
5
+ * ## The problem it solves
6
+ *
7
+ * `ctx.web` selects exactly **one** provider per capability. Its own docs say the
8
+ * configured id "is NOT a hidden priority chain", and it throws
9
+ * `WEB_PROVIDER_AMBIGUOUS` when more than one provider is usable. So a deployment
10
+ * that wants "best first, something free when the best is unavailable" cannot
11
+ * express that in seam config at all — it has to be one pinned provider whose
12
+ * internal order is explicit. That is what this plugin registers.
13
+ *
14
+ * ## What it registers
15
+ *
16
+ * | id | capability | what it is |
17
+ * |:--|:--|:--|
18
+ * | `fetch-chain` | fetch | ordered fallback across the managed legs |
19
+ * | `search-chain` | search | the same for search |
20
+ * | `deepseek-search-rich` | search | DeepSeek, mapping `summary` not just `snippet` |
21
+ * | `deepseek-fetch-rich` | fetch | DeepSeek fetch |
22
+ * | `anysearch` | both | AnySearch, the leg that won on bot-walled sites |
23
+ * | `tavily` | both | Tavily, the only leg here that extracts PDFs |
24
+ *
25
+ * Pin `searchProvider: search-chain` and `fetchProvider: fetch-chain`, and the
26
+ * chain decides which underlying leg runs.
27
+ *
28
+ * ## Why one package and not four
29
+ *
30
+ * This started as four packages (shared policy / vendors / fetch chain / search
31
+ * chain) on a single-responsibility argument. That argument was wrong in practice:
32
+ * it produced four settings pages, a package that could not be configured at all
33
+ * (the shared policy has no `apply()`), and a lockstep-upgrade problem where the
34
+ * two chains had to be bumped together by hand. Modules are the right unit for
35
+ * internal separation; a package is the right unit for installing and configuring,
36
+ * and there should be exactly one of those.
37
+ *
38
+ * ## Shape
39
+ *
40
+ * ```
41
+ * config.js one schema -> one settings page
42
+ * policy/ who is free, which mode wants which order, how much text
43
+ * providers/ the vendor HTTP legs
44
+ * chains/ the ordering and fallback logic
45
+ * client.js the settings page itself
46
+ * ```
47
+ *
48
+ * `policy` is imported by both chains on purpose: search and fetch must agree on
49
+ * what "free" means and on how a mode maps to an order, and two copies of that
50
+ * rule would drift the moment one learned about a new leg.
51
+ *
52
+ * ## The one rule that is easy to break
53
+ *
54
+ * A `volatile()` config field **must** have a `.default()` **and** must be present
55
+ * in the profile patch. schemastery reads every declared field while resolving the
56
+ * schema, before this plugin's injection completes; a missing field is read through
57
+ * the context proxy and throws `cannot get property "X" without inject`. That
58
+ * happens inside config resolution, so no try/catch in `apply()` can catch it, and
59
+ * the provider silently never registers — the seam then reports
60
+ * `configured web provider "search-chain" is not registered` with nothing in the
61
+ * log to explain it. `cordis.patch.yml` in this package lists every field.
62
+ *
63
+ * @module dsh-web-fallback-chain
64
+ */
65
+
66
+ import { CHAIN_FETCH_PROVIDER_ID, CHAIN_SEARCH_PROVIDER_ID, Config, readField } from './config.js'
67
+ import { buildProviders } from './providers/index.js'
68
+ import { applyFetchChain } from './chains/fetch-plugin.js'
69
+ import { applySearchChain } from './chains/search-plugin.js'
70
+ import { applyPromptSection } from './prompt.js'
71
+
72
+ /** Cordis plugin name used by loader diagnostics. */
73
+ export const name = 'web-fallback'
74
+
75
+ /**
76
+ * The web seam this plugin registers into.
77
+ *
78
+ * `systemPrompt` and `tools` are collaborators of the prompt section, probed at
79
+ * call time rather than listed here: making them hard dependencies would stop
80
+ * the providers from registering on a deployment that composes without them,
81
+ * which is a much worse failure than losing one prompt section.
82
+ */
83
+ export const inject = ['web']
84
+
85
+ export { Config }
86
+ export { CHAIN_FETCH_PROVIDER_ID, CHAIN_SEARCH_PROVIDER_ID, readField, paidLast } from './config.js'
87
+ export { buildProviders } from './providers/index.js'
88
+ export { runChain, resolveLegs, finalize, describeAttempts, chainError, fallbackMarker, bodyLength } from './chains/fetch.js'
89
+ export { runSearchChain, capSources } from './chains/search.js'
90
+ export {
91
+ DEFAULTS, KINDS, mergeProviders, partitionByCost, missingKey,
92
+ MODES, DEFAULT_MODE, DEFAULT_MODE_ORDERS, classifyFetch, classifySearch, resolveOrder, capText,
93
+ } from './policy/index.js'
94
+
95
+ /**
96
+ * Register every provider and both chains.
97
+ *
98
+ * Order matters only in that the chains must be able to find the vendor legs by
99
+ * the time a fetch or search happens — which registration guarantees, since
100
+ * resolution happens per call rather than at mount.
101
+ *
102
+ * @param ctx - context whose `web` service receives the providers.
103
+ * @param config - resolved plugin configuration.
104
+ */
105
+ export function apply(ctx, config) {
106
+ // A key entered in the settings page lands in the credential store, which takes
107
+ // precedence over `process.env`. Reading only the environment made those keys
108
+ // invisible to the providers, so the page said "set" while every call said 401.
109
+ const credentials = typeof ctx.get === 'function' ? ctx.get('credentials') : undefined
110
+ const { search, fetch: fetchers } = buildProviders(config, process.env, credentials)
111
+
112
+ const registered = { search: [], fetch: [] }
113
+ for (const [id, provider] of search) {
114
+ ctx.web.registerSearchProvider(provider)
115
+ registered.search.push(id)
116
+ }
117
+ for (const [id, provider] of fetchers) {
118
+ ctx.web.registerFetchProvider(provider)
119
+ registered.fetch.push(id)
120
+ }
121
+
122
+ applyFetchChain(ctx, config)
123
+ applySearchChain(ctx, config)
124
+ applyPromptSection(ctx)
125
+
126
+ // The only mount-time config read, and it reads fields the schema already
127
+ // resolved. Nothing else here touches config until the first real call.
128
+ ctx.logger?.info?.(
129
+ `web-fallback: registered search [${registered.search.join(', ')}] + ${CHAIN_SEARCH_PROVIDER_ID}, `
130
+ + `fetch [${registered.fetch.join(', ')}] + ${CHAIN_FETCH_PROVIDER_ID}`
131
+ + (readField(config, 'freeOnly', true) === true ? ' (free only)' : ''),
132
+ )
133
+ }
134
+
135
+ export { PROMPT_SECTION, PROMPT_TEXT, applyPromptSection } from './prompt.js'
136
+
137
+ export default { name, inject, Config, apply }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Shared policy for the search and fetch fallback chains.
3
+ *
4
+ * This package holds no provider and makes no network call. It is the piece the
5
+ * two chain plugins have in common:
6
+ *
7
+ * - {@link module:dsh-web-fallback-chain/policy/providers} — what each leg costs, how good
8
+ * it is, how much text to keep, and how a user adds a leg we never tested.
9
+ * - {@link module:dsh-web-fallback-chain/policy/modes} — what kind of material the caller
10
+ * needs (`brief` / `deep` / `list` / `page`), how that picks an order, and how
11
+ * `freeOnly` removes the billed legs without re-sorting anything.
12
+ *
13
+ * Splitting it out is deliberate: search and fetch must agree on what "free"
14
+ * means and on how a mode maps to an order, and two copies of that rule would
15
+ * drift the moment one of them learned about a new leg.
16
+ *
17
+ * @module dsh-web-fallback-chain/policy
18
+ */
19
+
20
+ export {
21
+ DEFAULTS,
22
+ KINDS,
23
+ mergeProviders,
24
+ partitionByCost,
25
+ missingKey,
26
+ } from './providers.js'
27
+
28
+ export {
29
+ MODES,
30
+ DEFAULT_MODE,
31
+ DEFAULT_MODE_ORDERS,
32
+ classifyFetch,
33
+ classifySearch,
34
+ resolveOrder,
35
+ readField,
36
+ capText,
37
+ } from './modes.js'
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Modes: the answer to "what kind of material does the caller need".
3
+ *
4
+ * ## Why modes exist instead of one chain
5
+ *
6
+ * The benchmark behind this plugin found the ranking is not the same job for
7
+ * every request: for a headline answer the cheap legs are within one point of
8
+ * the paid one, while for a page whose whole text you must read the paid leg's
9
+ * completeness matters and its silent failures do not. A single order has to
10
+ * compromise; a small set of named intents does not.
11
+ *
12
+ * ## Why the model cannot pick one yet
13
+ *
14
+ * The seam's request is `{ url }` for fetch and `{ query, maxResults }` for
15
+ * search — there is no field to carry an intent, and adding one means changing
16
+ * the host tool layer. So modes are selected by
17
+ * (a) an explicit per-call option when a caller can pass it (our own tools),
18
+ * (b) a URL/query classifier as a fallback, and
19
+ * (c) `defaultMode` otherwise. Today the host tool always lands on (b)/(c);
20
+ * when the tool layer learns to pass a mode, nothing below has to change.
21
+ *
22
+ * ## The four modes
23
+ *
24
+ * - `brief` — a fact to quote. Smallest cap, cheapest legs first, because at 300
25
+ * chars per result the free and paid legs scored 5/10 and 6/10.
26
+ * - `deep` — read a document. Biggest cap, paid legs allowed to lead: this is
27
+ * the only mode where their completeness pays for itself.
28
+ * - `list` — enumerate items (news front page, search listing, comment thread).
29
+ * Medium cap; the failure to avoid is returning navigation instead of items.
30
+ * - `page` — one URL the user already chose. No truncation of our own, and the
31
+ * only mode where the local leg's structural fidelity beats server extraction.
32
+ *
33
+ * @module dsh-web-chain-core/modes
34
+ */
35
+
36
+ /** Every mode name, cheapest-first ordering intent is expressed in config, not here. */
37
+ export const MODES = ['brief', 'deep', 'list', 'page']
38
+
39
+ /** Mode used when nothing else decides. `brief` is the cheapest safe default. */
40
+ export const DEFAULT_MODE = 'brief'
41
+
42
+ /**
43
+ * Per-capability default orders, strictly best-first by measured `quality`.
44
+ * Free and paid legs are interleaved by score; `freeOnly` skips the paid ones at
45
+ * call time without reordering, so the ranking is one list and the switch is
46
+ * exactly reversible.
47
+ *
48
+ * These are the *shipped* defaults. A deployment that measures its own numbers
49
+ * should override `modeOrders` in config — the plugin never re-sorts these.
50
+ */
51
+ export const DEFAULT_MODE_ORDERS = {
52
+ search: {
53
+ brief: ['deepseek-search-rich', 'anysearch', 'tavily'],
54
+ deep: ['deepseek-search-rich', 'anysearch', 'tavily'],
55
+ list: ['deepseek-search-rich', 'anysearch', 'tavily'],
56
+ page: ['deepseek-search-rich', 'anysearch', 'tavily'],
57
+ },
58
+ fetch: {
59
+ // Strictly by measured quality, descending, for every mode.
60
+ //
61
+ // An earlier revision put `http` (quality 4.0, the lowest) first on the
62
+ // reasoning that it is fastest and structurally best, and that the billed leg
63
+ // degrades silently. That was wrong about what a fallback chain means: **first
64
+ // means primary**, so leading with the weakest leg makes the weakest leg the one
65
+ // that actually serves every request, with the better legs only as backups.
66
+ // Silent degradation is what `minBodyChars` exists for, and it is already
67
+ // accounted for in the measured score — so re-ordering around it double-counted
68
+ // the same risk.
69
+ brief: ['anysearch', 'tavily', 'deepseek-fetch-rich', 'http'],
70
+ deep: ['anysearch', 'tavily', 'deepseek-fetch-rich', 'http'],
71
+ list: ['anysearch', 'tavily', 'deepseek-fetch-rich', 'http'],
72
+ page: ['anysearch', 'tavily', 'deepseek-fetch-rich', 'http'],
73
+ },
74
+ }
75
+
76
+ /** URL shapes that mean "read this document", not "search for something". */
77
+ const DEEP_URL = /(\/20\d{2}\/\d{2}\/|\/docs?\/|\/wiki\/|\/blog\/|\.pdf($|\?)|\/issues?\/\d|\/pull\/\d|\/releases?\/|\/readme|\/guides?\/|\/tutorials?\/|\/reference\/|\/manual\/|\/handbook\/|\/questions?\/\d|\/question\/\d|\/answers?\/\d|\/posts?\/\d|\/articles?\/|\/notes?\/\d|\/entry\/\d)/i
78
+ /** URL shapes that are front pages, tag pages or search listings. */
79
+ const LIST_URL = /(\/$|\/news\/?$|\/tag\/|\/tags\/|\/category\/|\/archive|\/page\/\d|\/search\?|\/questions\/?$|\/comments\/?$|\/\?|index\.html?$)/i
80
+ /** Queries that ask for many items rather than one fact. */
81
+ const LIST_QUERY = /(列表|有哪些|新闻|头条|排行榜|最新消息|汇总|list|news|headlines|releases|changelog)/i
82
+ /** Queries that ask for a definition, value or one fact. */
83
+ const BRIEF_QUERY = /(是什么|多少|谁|何时|哪一?年|天气|股价|版本|what is|who|when|how (much|many)|price|version|weather)/i
84
+
85
+ /**
86
+ * Classify a fetch request into a mode.
87
+ *
88
+ * `DEEP_URL` is checked first: a dated blog post (`/2025/09/18/Rust-1.90.0/`)
89
+ * also ends in a slash, so testing the trailing-slash list rule first would
90
+ * misfile exactly the pages that most need their full text. A specific document
91
+ * shape therefore outranks the generic "looks like a front page" shape.
92
+ *
93
+ * Deliberately conservative elsewhere: an unreadable shape lands on `brief`, the
94
+ * cheapest mode, because over-fetching is the failure this plugin exists to
95
+ * avoid.
96
+ *
97
+ * @param request - the seam's fetch request (`{ url }`).
98
+ * @returns one of {@link MODES}.
99
+ */
100
+ export function classifyFetch(request) {
101
+ const url = String(request?.url ?? '')
102
+ if (DEEP_URL.test(url)) return 'deep'
103
+ if (LIST_URL.test(url)) return 'list'
104
+ return 'brief'
105
+ }
106
+
107
+ /**
108
+ * Classify a search request into a mode.
109
+ *
110
+ * @param request - the seam's search request (`{ query, maxResults }`).
111
+ * @returns one of {@link MODES} (never `page`: a query is not a URL).
112
+ */
113
+ export function classifySearch(request) {
114
+ const query = String(request?.query ?? '')
115
+ if (LIST_QUERY.test(query) && !BRIEF_QUERY.test(query)) return 'list'
116
+ return 'brief'
117
+ }
118
+
119
+ /** Read one config field, accepting both a resolved value and a volatile getter. */
120
+ export function readField(config, key, fallback) {
121
+ const raw = config?.[key]
122
+ const value = raw !== null && typeof raw === 'object' && typeof raw.get === 'function' ? raw.get() : raw
123
+ return value === undefined ? fallback : value
124
+ }
125
+
126
+ /**
127
+ * Resolve the order to attempt for one call.
128
+ *
129
+ * Precedence: an explicit mode passed by the caller, then the classifier, then
130
+ * `defaultMode`. The chosen order is then filtered for budget when `freeOnly` is
131
+ * on — never re-sorted, because the configured order is the user's decision.
132
+ *
133
+ * @param options - `{ capability, mode, request, config, providers }`.
134
+ * @returns `{ mode, order, skippedForCost }`.
135
+ */
136
+ export function resolveOrder({ capability, mode, request, config, providers }) {
137
+ const freeOnly = readField(config, 'freeOnly', true) === true
138
+ const defaultMode = readField(config, 'defaultMode', DEFAULT_MODE)
139
+ const overrides = readField(config, 'modeOrders', {}) ?? {}
140
+ const shipped = DEFAULT_MODE_ORDERS[capability] ?? {}
141
+
142
+ const explicit = typeof mode === 'string' && MODES.includes(mode) ? mode : undefined
143
+ const classified = explicit === undefined
144
+ ? (capability === 'fetch' ? classifyFetch(request) : classifySearch(request))
145
+ : explicit
146
+ const chosen = explicit ?? (classified || defaultMode)
147
+
148
+ const configured = overrides?.[capability]?.[chosen]
149
+ const order = Array.isArray(configured) && configured.length > 0
150
+ ? configured
151
+ : (shipped[chosen] ?? [])
152
+
153
+ if (!freeOnly) return { mode: chosen, order, skippedForCost: [] }
154
+
155
+ const kept = []
156
+ const skipped = []
157
+ for (const id of order) {
158
+ if (providers?.[id]?.cost === 'paid') skipped.push(id)
159
+ else kept.push(id)
160
+ }
161
+ return { mode: chosen, order: kept, skippedForCost: skipped }
162
+ }
163
+
164
+ /**
165
+ * Truncate text to a provider's per-mode budget.
166
+ *
167
+ * Truncation happens here rather than in the chain so every leg is capped by the
168
+ * same rule, and a leg that returns more than its budget cannot quietly cost the
169
+ * caller more context than the mode asked for.
170
+ *
171
+ * @param text - body content.
172
+ * @param cap - character budget, or null/undefined for no cap.
173
+ * @returns `{ text, truncated }`.
174
+ */
175
+ export function capText(text, cap) {
176
+ const s = typeof text === 'string' ? text : ''
177
+ if (cap === null || cap === undefined || !Number.isFinite(cap) || s.length <= cap) return { text: s, truncated: false }
178
+ return { text: `${s.slice(0, cap)}…`, truncated: true }
179
+ }