dsh-autorouter 0.0.0-stage → 0.2.1

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/adapter.js ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The virtual provider. Everything dialect-specific stays inside the upstream
3
+ * adapters DSH already registered: this class only picks a route and forwards
4
+ * the call, which is why attachments, typed tool history and replay state keep
5
+ * working without an HTTP translation layer.
6
+ */
7
+
8
+ import { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm'
9
+
10
+ import {
11
+ PROVIDER_NAME,
12
+ enabledEntries,
13
+ resolveProfile,
14
+ } from './config.js'
15
+ import { resolveProfileInfo, toModelInfo } from './router/model-info.js'
16
+ import { walkRoute } from './router/walk.js'
17
+
18
+ const INFO_TTL_MS = 60_000
19
+
20
+ export function routeError(message, code) {
21
+ return LlmError.fromFailure({ message, code })
22
+ }
23
+
24
+ export class AutoRouterAdapter extends LlmAdapter {
25
+ constructor(deps) {
26
+ super()
27
+ this.deps = deps
28
+ this.infoCache = new Map()
29
+ }
30
+
31
+ providerInfo(provider) {
32
+ return { id: provider, name: PROVIDER_NAME }
33
+ }
34
+
35
+ providerRetryPolicy() {
36
+ return undefined
37
+ }
38
+
39
+ async infoOf(provider, model, signal) {
40
+ const llm = this.deps.getLlm()
41
+ if (llm === undefined) return undefined
42
+ try {
43
+ return await llm.resolveModelInfo(provider, model, signal)
44
+ } catch {
45
+ return undefined
46
+ }
47
+ }
48
+
49
+ async resolveProfileModel(profile, signal) {
50
+ const cacheKey = profile.id
51
+ const cached = this.infoCache.get(cacheKey)
52
+ const now = Date.now()
53
+ if (cached !== undefined && now - cached.at < INFO_TTL_MS) return cached.value
54
+ const resolved = await resolveProfileInfo(
55
+ profile,
56
+ (provider, model) => this.infoOf(provider, model, signal),
57
+ profile.policy,
58
+ )
59
+ const value = toModelInfo(this.deps.providerId ?? 'autorouter', profile, resolved)
60
+ this.infoCache.set(cacheKey, { at: now, value })
61
+ return value
62
+ }
63
+
64
+ async listModels(provider) {
65
+ const config = this.deps.getConfig()
66
+ const profiles = config.profiles.filter((profile) => profile.enabled)
67
+ return Promise.all(
68
+ profiles.map(async (profile) => {
69
+ const info = await this.resolveProfileModel(profile)
70
+ return {
71
+ provider,
72
+ id: profile.id,
73
+ name: info.name,
74
+ ...(info.description === undefined ? {} : { description: info.description }),
75
+ inputModalities: info.inputModalities,
76
+ }
77
+ }),
78
+ )
79
+ }
80
+
81
+ async resolveModel(provider, model, signal) {
82
+ const config = this.deps.getConfig()
83
+ const profile = resolveProfile(config, model)
84
+ if (profile === undefined) return { provider, id: model, name: model }
85
+ try {
86
+ return await this.resolveProfileModel(profile, signal)
87
+ } catch {
88
+ return { provider, id: model, name: profile.name }
89
+ }
90
+ }
91
+
92
+ imageRequestPricing(provider, model) {
93
+ try {
94
+ const config = this.deps.getConfig()
95
+ const profile = resolveProfile(config, model)
96
+ const entry = profile === undefined ? undefined : enabledEntries(profile)[0]
97
+ const llm = this.deps.getLlm()
98
+ if (entry === undefined || llm === undefined) return undefined
99
+ return llm.imageRequestPricing(entry.provider, entry.model)
100
+ } catch {
101
+ return undefined
102
+ }
103
+ }
104
+
105
+ stream(options) {
106
+ const config = this.deps.getConfig()
107
+ if (config.enabled !== true) {
108
+ throw routeError('AutoRouter is disabled in Settings → AutoRouter.', 'AUTOROUTER_DISABLED')
109
+ }
110
+ const profile = resolveProfile(config, options.model)
111
+ if (profile === undefined) {
112
+ const known = config.profiles.map((item) => item.id).join(', ')
113
+ throw routeError(
114
+ known === ''
115
+ ? 'AutoRouter has no profile yet: create one in Settings → AutoRouter, then pick it as the model.'
116
+ : `AutoRouter: unknown virtual model "${String(options.model)}" — pick one of ${known}.`,
117
+ 'UNKNOWN_MODEL',
118
+ )
119
+ }
120
+ if (profile.enabled !== true) {
121
+ throw routeError(`AutoRouter: virtual model "${profile.id}" is disabled.`, 'PROFILE_DISABLED')
122
+ }
123
+ if (enabledEntries(profile).length === 0) {
124
+ throw routeError(`AutoRouter: the chain of "${profile.id}" is empty.`, 'EMPTY_CHAIN')
125
+ }
126
+ const llm = this.deps.getLlm()
127
+ if (llm === undefined) {
128
+ throw routeError('AutoRouter: the llm runtime is unavailable.', 'LLM_UNAVAILABLE')
129
+ }
130
+ return walkRoute({
131
+ options: { ...options, provider: this.deps.providerId ?? 'autorouter' },
132
+ profile,
133
+ config,
134
+ state: this.deps.getState(),
135
+ streamFn: (attempt) => llm.stream(attempt),
136
+ infoOf: (provider, model, signal) => this.infoOf(provider, model, signal),
137
+ makeError: routeError,
138
+ log: this.deps.log ?? {},
139
+ })
140
+ }
141
+ }
package/src/config.js ADDED
@@ -0,0 +1,350 @@
1
+ /**
2
+ * AutoRouter configuration: defaults, normalization and pure helpers.
3
+ *
4
+ * This module deliberately imports nothing from DSH so it can be unit-tested
5
+ * with plain `node --test` outside the harness.
6
+ */
7
+
8
+ export const PROVIDER_ID = 'autorouter'
9
+ export const PROVIDER_NAME = 'AutoRouter'
10
+ /** Profile-entry id / settings namespace. Must match bundle/cordis.patch.yml. */
11
+ export const ENTRY_ID = 'llm-autorouter'
12
+ export const CONFIG_VERSION = 1
13
+
14
+ /**
15
+ * The loader materialises a bundle-inserted row as `include:<patch id>`, while
16
+ * a row written directly into the profile patch keeps its own id. Resolve both
17
+ * instead of pinning one spelling.
18
+ */
19
+ export function matchSettingsEntry(descriptors, entryId = ENTRY_ID) {
20
+ const list = Array.isArray(descriptors) ? descriptors : []
21
+ for (const ns of [entryId, `include:${entryId}`]) {
22
+ const hit = list.find((item) => item?.ns === ns)
23
+ if (hit !== undefined) return hit
24
+ }
25
+ return list.find((item) => typeof item?.ns === 'string' && item.ns.endsWith(`:${entryId}`))
26
+ }
27
+
28
+ export const DEFAULT_TRIGGER_CODES = ['AUTH', 'QUOTA', 'RATE_LIMIT']
29
+ export const DEFAULT_TRIGGER_STATUSES = [401, 402, 403, 408, 409, 425, 429, 500, 502, 503, 504, 529]
30
+
31
+ export const EFFORT_ORDER = ['off', 'minimal', 'low', 'medium', 'high', 'max']
32
+
33
+ export const DEFAULT_POLICY = {
34
+ sticky: true,
35
+ stickinessTtlMs: 30 * 60 * 1000,
36
+ maxSwitches: 8,
37
+ cooldownMs: 5 * 60 * 1000,
38
+ cooldownJitterRatio: 0.2,
39
+ recovery: 'timer',
40
+ triggerCodes: [...DEFAULT_TRIGGER_CODES],
41
+ triggerStatuses: [...DEFAULT_TRIGGER_STATUSES],
42
+ failureWindowMs: 2 * 60 * 1000,
43
+ failureThreshold: 3,
44
+ backoffBaseMs: 1000,
45
+ backoffMaxMs: 15 * 1000,
46
+ honorRetryAfter: true,
47
+ retryOnNetwork: true,
48
+ effortPolicy: 'clamp',
49
+ contextPolicy: 'min',
50
+ defaultContextWindow: 128000,
51
+ timezone: 'Asia/Shanghai',
52
+ utcOffsetMinutes: 480,
53
+ timeWindows: [],
54
+ }
55
+
56
+ export const DEFAULT_CONFIG = {
57
+ version: CONFIG_VERSION,
58
+ enabled: true,
59
+ debug: false,
60
+ // Empty on purpose: a fresh install routes nothing until the operator
61
+ // builds a chain from the providers they actually have credentials for.
62
+ profiles: [],
63
+ gateway: {
64
+ enabled: false,
65
+ /** Served model id -> profile id. Empty means "every enabled profile". */
66
+ models: {},
67
+ },
68
+ service: {
69
+ url: '',
70
+ token: '',
71
+ timeoutMs: 8000,
72
+ },
73
+ }
74
+
75
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
76
+ const clone = (value) => (typeof structuredClone === 'function' ? structuredClone(value) : JSON.parse(JSON.stringify(value)))
77
+
78
+ function finiteNumber(value, fallback, { min = -Infinity, max = Infinity } = {}) {
79
+ const number = typeof value === 'string' && value.trim() !== '' ? Number(value) : value
80
+ if (typeof number !== 'number' || !Number.isFinite(number)) return fallback
81
+ return Math.min(max, Math.max(min, number))
82
+ }
83
+
84
+ function text(value, fallback = '') {
85
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback
86
+ }
87
+
88
+ function boolean(value, fallback) {
89
+ return typeof value === 'boolean' ? value : fallback
90
+ }
91
+
92
+ function stringList(value, fallback) {
93
+ if (!Array.isArray(value)) return [...fallback]
94
+ const list = value.filter((item) => typeof item === 'string' && item.trim() !== '').map((item) => item.trim())
95
+ return list.length > 0 ? [...new Set(list)] : [...fallback]
96
+ }
97
+
98
+ function statusList(value, fallback) {
99
+ if (!Array.isArray(value)) return [...fallback]
100
+ const list = value.map((item) => Number(item)).filter((item) => Number.isInteger(item) && item >= 100 && item <= 599)
101
+ return list.length > 0 ? [...new Set(list)] : [...fallback]
102
+ }
103
+
104
+ /** `HH:MM` or already-normalized minutes -> minutes since local midnight. */
105
+ export function parseClock(value) {
106
+ if (typeof value === 'number' && Number.isFinite(value)) {
107
+ const minutes = Math.round(value)
108
+ return minutes >= 0 && minutes < 1440 ? minutes : undefined
109
+ }
110
+ if (typeof value !== 'string') return undefined
111
+ const match = /^(\d{1,2}):(\d{2})$/.exec(value.trim())
112
+ if (match === null) return undefined
113
+ const hours = Number(match[1])
114
+ const minutes = Number(match[2])
115
+ if (hours > 23 || minutes > 59) return undefined
116
+ return hours * 60 + minutes
117
+ }
118
+
119
+ function normalizeRange(raw) {
120
+ if (!isObject(raw)) return undefined
121
+ const from = parseClock(raw.from)
122
+ const to = parseClock(raw.to)
123
+ if (from === undefined || to === undefined) return undefined
124
+ return { from, to }
125
+ }
126
+
127
+ function normalizeTimeWindow(raw, index) {
128
+ if (!isObject(raw)) return undefined
129
+ // One named window = one fallback chain, but it may be spread over several
130
+ // disjoint stretches of the day (e.g. 00:30–08:30 and 22:00–23:30). A config
131
+ // still written as a single `{ from, to }` pair is folded into a one-range
132
+ // list, so old files load unchanged.
133
+ const source = Array.isArray(raw.ranges) ? raw.ranges : [{ from: raw.from, to: raw.to }]
134
+ const ranges = source.map(normalizeRange).filter((item) => item !== undefined)
135
+ if (ranges.length === 0) return undefined
136
+ const id = text(raw.id, `window-${index + 1}`)
137
+ return {
138
+ id,
139
+ label: text(raw.label, id),
140
+ ranges,
141
+ utcOffsetMinutes: finiteNumber(raw.utcOffsetMinutes, DEFAULT_POLICY.utcOffsetMinutes, { min: -720, max: 840 }),
142
+ order: Array.isArray(raw.order)
143
+ ? raw.order.filter((item) => typeof item === 'string' && item.trim() !== '').map((item) => item.trim())
144
+ : [],
145
+ }
146
+ }
147
+
148
+ function normalizeEffortMap(raw) {
149
+ if (!isObject(raw)) return {}
150
+ const map = {}
151
+ for (const [key, value] of Object.entries(raw)) {
152
+ if (typeof key !== 'string' || key === '') continue
153
+ if (value === null || value === false || value === '') {
154
+ map[key] = null
155
+ } else if (typeof value === 'string') {
156
+ map[key] = value
157
+ }
158
+ }
159
+ return map
160
+ }
161
+
162
+ function normalizeEntry(raw, index, seen) {
163
+ if (!isObject(raw)) return undefined
164
+ const provider = text(raw.provider)
165
+ const model = text(raw.model)
166
+ if (provider === '' || model === '' || provider === PROVIDER_ID) return undefined
167
+ const key = `${provider}/${model}`
168
+ if (seen.has(key)) return undefined
169
+ seen.add(key)
170
+ const id = text(raw.id, key).replace(/\s+/g, '-')
171
+ return {
172
+ id,
173
+ enabled: boolean(raw.enabled, true),
174
+ provider,
175
+ model,
176
+ label: text(raw.label, `${provider} · ${model}`),
177
+ cooldownMs: finiteNumber(raw.cooldownMs, DEFAULT_POLICY.cooldownMs, { min: 0, max: 7 * 24 * 60 * 60 * 1000 }),
178
+ effortMap: normalizeEffortMap(raw.effortMap),
179
+ }
180
+ }
181
+
182
+ function normalizePolicy(raw) {
183
+ const source = isObject(raw) ? raw : {}
184
+ const base = DEFAULT_POLICY
185
+ const recovery = source.recovery === 'half-open' ? 'half-open' : 'timer'
186
+ const effortPolicy = source.effortPolicy === 'drop' || source.effortPolicy === 'fail' ? source.effortPolicy : 'clamp'
187
+ const contextPolicy = source.contextPolicy === 'fixed' ? 'fixed' : 'min'
188
+ return {
189
+ sticky: boolean(source.sticky, base.sticky),
190
+ stickinessTtlMs: finiteNumber(source.stickinessTtlMs, base.stickinessTtlMs, { min: 60_000, max: 24 * 60 * 60 * 1000 }),
191
+ maxSwitches: Math.floor(finiteNumber(source.maxSwitches, base.maxSwitches, { min: 0, max: 32 })),
192
+ cooldownMs: finiteNumber(source.cooldownMs, base.cooldownMs, { min: 0, max: 24 * 60 * 60 * 1000 }),
193
+ cooldownJitterRatio: finiteNumber(source.cooldownJitterRatio, base.cooldownJitterRatio, { min: 0, max: 1 }),
194
+ recovery,
195
+ triggerCodes: stringList(source.triggerCodes, base.triggerCodes),
196
+ triggerStatuses: statusList(source.triggerStatuses, base.triggerStatuses),
197
+ failureWindowMs: finiteNumber(source.failureWindowMs, base.failureWindowMs, { min: 0, max: 24 * 60 * 60 * 1000 }),
198
+ failureThreshold: Math.floor(finiteNumber(source.failureThreshold, base.failureThreshold, { min: 1, max: 100 })),
199
+ backoffBaseMs: finiteNumber(source.backoffBaseMs, base.backoffBaseMs, { min: 0, max: 10 * 60 * 1000 }),
200
+ backoffMaxMs: finiteNumber(source.backoffMaxMs, base.backoffMaxMs, { min: 0, max: 30 * 60 * 1000 }),
201
+ honorRetryAfter: boolean(source.honorRetryAfter, base.honorRetryAfter),
202
+ retryOnNetwork: boolean(source.retryOnNetwork, base.retryOnNetwork),
203
+ effortPolicy,
204
+ contextPolicy,
205
+ defaultContextWindow: Math.floor(finiteNumber(source.defaultContextWindow, base.defaultContextWindow, { min: 8_000, max: 10_000_000 })),
206
+ timezone: text(source.timezone, base.timezone),
207
+ utcOffsetMinutes: Math.floor(finiteNumber(source.utcOffsetMinutes, base.utcOffsetMinutes, { min: -720, max: 840 })),
208
+ timeWindows: Array.isArray(source.timeWindows)
209
+ ? source.timeWindows.map((item, index) => normalizeTimeWindow(item, index)).filter((item) => item !== undefined)
210
+ : [],
211
+ }
212
+ }
213
+
214
+ function normalizeProfile(raw, index) {
215
+ if (!isObject(raw)) return undefined
216
+ const id = text(raw.id, index === 0 ? 'auto' : `profile-${index + 1}`)
217
+ // Dedupe within this profile only: the same upstream route may legitimately
218
+ // appear in more than one profile's chain.
219
+ const seenEntryKeys = new Set()
220
+ const chain = Array.isArray(raw.chain)
221
+ ? raw.chain.map((entry, entryIndex) => normalizeEntry(entry, entryIndex, seenEntryKeys)).filter((entry) => entry !== undefined)
222
+ : []
223
+ return {
224
+ id,
225
+ name: text(raw.name, id === 'auto' ? 'Auto' : id),
226
+ aliases: Array.isArray(raw.aliases)
227
+ ? raw.aliases.filter((alias) => typeof alias === 'string' && alias.trim() !== '' && alias.trim() !== id).map((alias) => alias.trim())
228
+ : [],
229
+ enabled: boolean(raw.enabled, true),
230
+ description: text(raw.description, ''),
231
+ chain,
232
+ policy: normalizePolicy(raw.policy),
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Turn whatever the settings file / UI sent into a complete, bounded config.
238
+ * Unknown keys are dropped on purpose: the wire format is the schema.
239
+ */
240
+ export function normalizeConfig(raw, { fallback = DEFAULT_CONFIG } = {}) {
241
+ const source = isObject(raw) ? raw : {}
242
+ const profiles = Array.isArray(source.profiles) ? source.profiles : fallback.profiles
243
+ const seenProfileIds = new Set()
244
+ const normalizedProfiles = []
245
+ for (const [index, profile] of profiles.entries()) {
246
+ const next = normalizeProfile(profile, index)
247
+ if (next === undefined) continue
248
+ if (seenProfileIds.has(next.id)) continue
249
+ seenProfileIds.add(next.id)
250
+ normalizedProfiles.push(next)
251
+ }
252
+ const gateway = isObject(source.gateway) ? source.gateway : {}
253
+ const service = isObject(source.service) ? source.service : {}
254
+ return {
255
+ version: CONFIG_VERSION,
256
+ enabled: boolean(source.enabled, fallback.enabled),
257
+ debug: boolean(source.debug, fallback.debug),
258
+ profiles: normalizedProfiles,
259
+ gateway: {
260
+ enabled: boolean(gateway.enabled, false),
261
+ models: isObject(gateway.models)
262
+ ? Object.fromEntries(
263
+ Object.entries(gateway.models).filter(
264
+ ([key, value]) => keysAreText(key) && typeof value === 'string' && value.trim() !== '',
265
+ ),
266
+ )
267
+ : {},
268
+ },
269
+ service: {
270
+ url: text(service.url, ''),
271
+ token: text(service.token, ''),
272
+ timeoutMs: Math.floor(finiteNumber(service.timeoutMs, 8000, { min: 500, max: 120_000 })),
273
+ },
274
+ }
275
+ }
276
+
277
+ function keysAreText(key) {
278
+ return typeof key === 'string' && key.trim() !== ''
279
+ }
280
+
281
+ /** Resolve a virtual model id (profile id or alias) to its profile. */
282
+ export function resolveProfile(config, model) {
283
+ const id = typeof model === 'string' ? model.trim() : ''
284
+ if (id === '') return undefined
285
+ return config.profiles.find((profile) => profile.id === id || profile.aliases.includes(id))
286
+ }
287
+
288
+ export function routeKey(provider, model) {
289
+ return `${provider}/${model}`
290
+ }
291
+
292
+ export function entryKey(entry) {
293
+ return routeKey(entry.provider, entry.model)
294
+ }
295
+
296
+ export function enabledProfiles(config) {
297
+ return config.profiles.filter((profile) => profile.enabled)
298
+ }
299
+
300
+ export function enabledEntries(profile) {
301
+ return profile.chain.filter((entry) => entry.enabled)
302
+ }
303
+
304
+ export function localMinutes(now, utcOffsetMinutes) {
305
+ const shifted = new Date(now + utcOffsetMinutes * 60_000)
306
+ return shifted.getUTCHours() * 60 + shifted.getUTCMinutes()
307
+ }
308
+
309
+ export function timeWindowMatches(window, now, utcOffsetMinutes = window.utcOffsetMinutes ?? 0) {
310
+ const minutes = localMinutes(now, utcOffsetMinutes)
311
+ // A window may cover several disjoint stretches of the day. A stored window
312
+ // that still carries a single `{ from, to }` pair is read the same way, so
313
+ // configs written before ranges existed keep matching.
314
+ const ranges = Array.isArray(window.ranges) ? window.ranges : [{ from: window.from, to: window.to }]
315
+ return ranges.some((range) => {
316
+ const from = Number(range.from)
317
+ const to = Number(range.to)
318
+ if (!Number.isFinite(from) || !Number.isFinite(to)) return false
319
+ if (from === to) return true
320
+ if (from < to) return minutes >= from && minutes < to
321
+ return minutes >= from || minutes < to
322
+ })
323
+ }
324
+
325
+ /** The first matching time window in config order, or `undefined`. */
326
+ export function activeTimeWindow(policy, now) {
327
+ return (policy.timeWindows ?? []).find((window) => timeWindowMatches(window, now, policy.utcOffsetMinutes))
328
+ }
329
+
330
+ /**
331
+ * Reorder a chain for the active time window. Entries named in `order` come
332
+ * first in that order; the rest keep their configured order.
333
+ */
334
+ export function applyTimeWindow(entries, window) {
335
+ if (window === undefined) return entries
336
+ const rank = new Map(window.order.map((id, index) => [id, index]))
337
+ const rankOf = (entry) => rank.get(entry.id) ?? rank.get(`${entry.provider}/${entry.model}`)
338
+ return [...entries].sort((left, right) => {
339
+ const leftRank = rankOf(left)
340
+ const rightRank = rankOf(right)
341
+ if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank
342
+ if (leftRank !== undefined) return -1
343
+ if (rightRank !== undefined) return 1
344
+ return 0
345
+ })
346
+ }
347
+
348
+ export function isEntryEligible(entry) {
349
+ return entry.enabled && entry.provider !== PROVIDER_ID && typeof entry.model === 'string' && entry.model !== ''
350
+ }