dsh-autorouter 0.0.0-stage → 0.2.0

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/icon.svg ADDED
@@ -0,0 +1,10 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
2
+ <circle cx="5" cy="6" r="2.1"/>
3
+ <circle cx="5" cy="18" r="2.1"/>
4
+ <circle cx="19" cy="12" r="2.4"/>
5
+ <path d="M7.1 6h3.2a3 3 0 0 1 3 3v.6"/>
6
+ <path d="M7.1 18h3.2a3 3 0 0 0 3-3v-.6"/>
7
+ <path d="M16.6 12h-1.1"/>
8
+ <path d="m10.4 8.1 1.2 1.9 1.2-1.9"/>
9
+ <path d="m10.4 15.9 1.2-1.9 1.2 1.9"/>
10
+ </svg>
package/index.js ADDED
@@ -0,0 +1,226 @@
1
+ /**
2
+ * AutoRouter — one DSH provider (`autorouter` / "AutoRouter") that walks a
3
+ * quota-aware fallback chain over the providers and models already registered
4
+ * in DeepSeek Harness.
5
+ *
6
+ * The plugin registers a native `LlmAdapter`. It does not proxy HTTP: each
7
+ * attempt is a nested `ctx.llm.stream()` call to a real route, so upstream
8
+ * credentials, dialects, attachments and replay state stay inside DSH.
9
+ */
10
+
11
+ import { createRequire } from 'node:module'
12
+
13
+ import z from '@deepseek-ai/schemastery'
14
+
15
+ import { AutoRouterAdapter } from './src/adapter.js'
16
+ import {
17
+ DEFAULT_CONFIG,
18
+ ENTRY_ID,
19
+ PROVIDER_ID,
20
+ matchSettingsEntry,
21
+ normalizeConfig,
22
+ resolveProfile,
23
+ } from './src/config.js'
24
+ import { installRoutes } from './src/http.js'
25
+ import { describeOrder, orderCandidates } from './src/router/select.js'
26
+ import { RouterState } from './src/state.js'
27
+
28
+ const require = createRequire(import.meta.url)
29
+ const { version: VERSION } = require('./package.json')
30
+
31
+ export const name = 'llm-autorouter'
32
+ export const inject = ['llm']
33
+
34
+ /**
35
+ * The schema is intentionally shallow: the settings page is custom, and the
36
+ * shapes below are validated by `normalizeConfig` (which also bounds every
37
+ * number). A deep schemastery tree would duplicate that logic and could reject
38
+ * a config the page can still repair.
39
+ */
40
+ export const Config = z.object({
41
+ version: z.number().default(1),
42
+ enabled: z.boolean().default(true),
43
+ debug: z.boolean().default(false),
44
+ profiles: z.array(z.any()).default([]),
45
+ gateway: z.any(),
46
+ service: z.any(),
47
+ }).extra('volatile', true)
48
+
49
+ const isLiveRef = (value) => typeof value === 'object' && value !== null && typeof value.get === 'function'
50
+
51
+ export function apply(ctx, config = DEFAULT_CONFIG) {
52
+ const logger = ctx.logger('llm-autorouter')
53
+ const fallback = normalizeConfig(isLiveRef(config) ? config.get() : config, { fallback: DEFAULT_CONFIG })
54
+ const state = new RouterState()
55
+ let llm
56
+ let settings
57
+ let handle
58
+ let registered = false
59
+ let cache
60
+ /**
61
+ * What this plugin last wrote, kept until the host document reports it back.
62
+ * `settings.describe()` projects the loader snapshot, which can lag a whole
63
+ * tick behind `settings.replace()`, so without this the page saves, then
64
+ * reads the pre-write config back and looks like the save was undone.
65
+ */
66
+ let written
67
+
68
+ const getLlm = () => llm
69
+ const getState = () => state
70
+
71
+ function getConfig() {
72
+ if (written !== undefined) {
73
+ if (written.until > Date.now()) return written.value
74
+ written = undefined
75
+ }
76
+ if (settings !== undefined && typeof settings.describe === 'function') {
77
+ try {
78
+ const descriptor = matchSettingsEntry(settings.describe())
79
+ if (descriptor !== undefined) {
80
+ if (cache !== undefined && cache.revision === descriptor.revision && Date.now() - cache.at < 5000) {
81
+ return cache.value
82
+ }
83
+ const value = normalizeConfig(descriptor.value, { fallback })
84
+ cache = { revision: descriptor.revision, value, at: Date.now() }
85
+ return value
86
+ }
87
+ } catch (error) {
88
+ logger.debug(`llm-autorouter: settings.describe failed, using the boot config: ${error.message}`)
89
+ }
90
+ }
91
+ return fallback
92
+ }
93
+
94
+ const adapter = new AutoRouterAdapter({
95
+ providerId: PROVIDER_ID,
96
+ getConfig,
97
+ getLlm,
98
+ getState,
99
+ log: {
100
+ info: (...args) => logger.info(...args),
101
+ warn: (...args) => logger.warn(...args),
102
+ debug: (...args) => logger.debug(...args),
103
+ },
104
+ })
105
+
106
+ function invalidate() {
107
+ cache = undefined
108
+ adapter.infoCache.clear()
109
+ }
110
+
111
+ function remember(value) {
112
+ written = { value, until: Date.now() + 10_000 }
113
+ invalidate()
114
+ }
115
+
116
+ function reconcile() {
117
+ if (llm === undefined) return
118
+ const enabled = getConfig().enabled !== false
119
+ if (enabled && !registered) {
120
+ try {
121
+ handle = llm.registerAdapter([PROVIDER_ID], adapter)
122
+ registered = true
123
+ logger.info(`llm-autorouter: provider "${PROVIDER_ID}" registered (${PROVIDER_ID}/<profile>)`)
124
+ } catch (error) {
125
+ if (error?.code === 'DUPLICATE_ADAPTER') {
126
+ logger.debug('llm-autorouter: adapter already registered on this fiber — multi-fiber dedupe')
127
+ } else {
128
+ throw error
129
+ }
130
+ }
131
+ } else if (!enabled && registered) {
132
+ try {
133
+ handle?.()
134
+ } catch {
135
+ /* disposed with the fiber */
136
+ }
137
+ handle = undefined
138
+ registered = false
139
+ logger.info(`llm-autorouter: provider "${PROVIDER_ID}" unregistered (disabled in settings)`)
140
+ }
141
+ }
142
+
143
+ function getSelection() {
144
+ const current = getConfig()
145
+ const now = Date.now()
146
+ const profiles = {}
147
+ for (const profile of current.profiles) {
148
+ profiles[profile.id] = describeOrder(orderCandidates({ profile, state, now }))
149
+ }
150
+ return { at: now, entryId: ENTRY_ID, profiles }
151
+ }
152
+
153
+ try {
154
+ ctx.provide('autorouter', {
155
+ name: PROVIDER_ID,
156
+ version: VERSION,
157
+ getConfig,
158
+ getState,
159
+ getSelection,
160
+ snapshot: () => state.snapshot(getConfig(), Date.now()),
161
+ resolveProfile: (model) => resolveProfile(getConfig(), model),
162
+ })
163
+ } catch (error) {
164
+ logger.debug(`llm-autorouter: service already provided on this fiber: ${error.message}`)
165
+ }
166
+
167
+ ctx.effect(() => {
168
+ const timer = setInterval(() => state.prune(), 5 * 60 * 1000)
169
+ timer.unref?.()
170
+ return () => clearInterval(timer)
171
+ }, 'llm-autorouter: state prune')
172
+
173
+ ctx.inject(['llm'], (serviceContext) => {
174
+ llm = serviceContext.llm
175
+ reconcile()
176
+ return () => {
177
+ try {
178
+ handle?.()
179
+ } catch {
180
+ /* already disposed */
181
+ }
182
+ handle = undefined
183
+ registered = false
184
+ llm = undefined
185
+ }
186
+ })
187
+
188
+ ctx.inject(['settings'], (serviceContext) => {
189
+ settings = serviceContext.settings
190
+ invalidate()
191
+ reconcile()
192
+ const dispose = ctx.on('settings/document-updated', (ns) => {
193
+ if (ns !== ENTRY_ID && !String(ns).endsWith(`:${ENTRY_ID}`)) return
194
+ written = undefined
195
+ invalidate()
196
+ reconcile()
197
+ })
198
+ return () => {
199
+ try {
200
+ dispose()
201
+ } catch {
202
+ /* already disposed */
203
+ }
204
+ settings = undefined
205
+ cache = undefined
206
+ written = undefined
207
+ }
208
+ })
209
+
210
+ ctx.inject(['webServer'], (serviceContext) =>
211
+ installRoutes({
212
+ webServer: serviceContext.webServer,
213
+ version: VERSION,
214
+ getConfig,
215
+ getSettings: () => settings,
216
+ getLlm,
217
+ getState,
218
+ getSelection,
219
+ onConfigSaved: invalidate,
220
+ onConfigWritten: remember,
221
+ logger,
222
+ }),
223
+ )
224
+
225
+ logger.debug(`llm-autorouter ${VERSION}: entry "${ENTRY_ID}", provider "${PROVIDER_ID}"`)
226
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "AutoRouter",
4
+ "description": "One virtual provider over the models you already registered: route each request along a fallback chain, switch only before the first output chunk, and carry per-route cooldown and reasoning effort.",
5
+ "detail": "README.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "AutoRouter",
4
+ "description": "把已登记的多个 provider/model 聚合成一个虚拟 provider:按回退链路由请求,失败时在首个输出块之前切换,并承接每条路由的冷却与思考强度。",
5
+ "detail": "README.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "dsh-autorouter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "AutoRouter — one DSH provider in front of a fallback chain over every registered route, with reasoning effort inherited from the caller.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Ruixin Zhan",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ZhanRuiXin/dsh-autorouter.git"
11
+ },
12
+ "homepage": "https://github.com/ZhanRuiXin/dsh-autorouter#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/ZhanRuiXin/dsh-autorouter/issues"
15
+ },
16
+ "keywords": [
17
+ "dsh",
18
+ "dsh-plugin",
19
+ "deepseek-harness",
20
+ "llm",
21
+ "router",
22
+ "fallback",
23
+ "provider",
24
+ "reasoning-effort",
25
+ "settings-ui"
26
+ ],
27
+ "main": "./index.js",
28
+ "exports": {
29
+ ".": "./index.js",
30
+ "./client": "./client.js",
31
+ "./bundle/cordis.patch.yml": "./bundle/cordis.patch.yml",
32
+ "./locale/*.json": "./locale/*.json",
33
+ "./icon": "./icon.svg",
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "index.js",
38
+ "client.js",
39
+ "src",
40
+ "bundle",
41
+ "locale",
42
+ "icon.svg",
43
+ "README.md",
44
+ "README.zh-CN.md",
45
+ "CHANGELOG.md",
46
+ "LICENSE"
47
+ ],
48
+ "scripts": {
49
+ "test": "node --test test/*.test.js"
50
+ },
51
+ "dsh": {
52
+ "bundle": {
53
+ "patch": "./bundle/cordis.patch.yml"
54
+ },
55
+ "client": {
56
+ "platform": "web",
57
+ "immediately": true,
58
+ "inject": [
59
+ "@deepseek-ai/dsh-client-locale",
60
+ "@deepseek-ai/dsh-client-ui-slots",
61
+ "@deepseek-ai/dsh-client-ui-settings"
62
+ ]
63
+ }
64
+ },
65
+ "peerDependencies": {
66
+ "@deepseek-ai/dsh-llm": "*",
67
+ "@deepseek-ai/schemastery": "*"
68
+ },
69
+ "engines": {
70
+ "node": ">=22"
71
+ }
72
+ }
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
+ }