dsh-model-routing 0.0.0-stage → 1.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sunner-ds
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,77 @@
1
- # Temporary Holding Version
1
+ # 模型分工 / Model routing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给五类工作各指定一个模型,并看用量和余额:规划与文案、写代码、出图、看图审错、决策与执行。模型列表不是写死的——它读你在 DSH 里已经配好的提供方。
4
+
5
+ Assign a model to each of five kinds of work, and watch usage and balance. The model list is not hard-coded: it is read from the providers you already configured in DSH.
6
+
7
+ ## 安装 / Install
8
+
9
+ `
10
+ dsh plugin add dsh-model-routing
11
+ `
12
+
13
+ 装不上的话,用仓库地址或压缩包:
14
+
15
+ `
16
+ dsh plugin add https://github.com/downer-dr/dsh-model-routing.git
17
+
18
+ # 或者(不依赖 git)
19
+ https://codeload.github.com/downer-dr/dsh-model-routing/tar.gz/refs/heads/master
20
+ `
21
+
22
+ 本地开发直接指向目录:DSH → 插件 → 添加插件。
23
+
24
+ **装完重启会话(或刷新页面),侧栏就有「模型分工」。**
25
+
26
+ Install with dsh plugin add dsh-model-routing, or use the git URL / tarball above.
27
+ Restart the session (or refresh) afterwards; **Model routing** then appears in the sidebar.
28
+
29
+ ## 它解决什么 / What it solves
30
+
31
+ 一个会话里的事不是一类:写方案要长上下文、出图要能画、审图要能看图、改文件必须谨慎。这些活的最佳模型不是同一个。
32
+ 插件把分工变成一份可以随时改的配置,并把用量集中到一页上。
33
+
34
+ Work in one session is not one kind: planning needs a long context, image work needs a drawing model, review needs vision, and edits must be careful. The best model differs per job. This plugin turns that division into one editable config page, with usage in the same place.
35
+
36
+ ## 用法 / Usage
37
+
38
+ 1. 安装本插件并在插件管理里启用;
39
+ 2. 打开左侧栏的「模型分工」(设置里也有同一页);
40
+ 3. 每一行选一个模型,点「保存」。
41
+
42
+ 1. Install and enable the plugin.
43
+ 2. Open **Model routing** in the sidebar (the same page is under Settings).
44
+ 3. Pick a model on each row and press **Save**.
45
+
46
+ ## 模型从哪来 / Where the list comes from
47
+
48
+ 下拉里的选项来自你的 profile 配置(`~/.dsh/profiles/<name>/cordis.patch.yml` 里 `llm-pi-ai` 的 `providers`):提供方 id + 模型 id。
49
+ 所以**先在 DSH 设置里把提供方配好**,这里才有东西可选;没配就用手动添加。
50
+
51
+ The dropdown is built from your profile config (`llm-pi-ai` → `providers` in `~/.dsh/profiles/<name>/cordis.patch.yml`): provider id plus model ids.
52
+ So configure providers in DSH Settings first; otherwise use the manual input.
53
+
54
+ ## 存在哪 / Where it is stored
55
+
56
+ ```
57
+ ~/.dsh/model-routing.json 分工配置(routing + balances)
58
+ ~/.dsh/model-routing-usage.json 调用日志(可选,用于中转用量表)
59
+ ```
60
+
61
+ 本机(deepseek)那块的用量读 `~/.dsh/storages/cost-meter/ledger.json`,装了 dsh-cost-meter 才有数。
62
+
63
+ ## 局限 / Limitations
64
+
65
+ - **它不调用模型**。这份配置是一份"该用谁"的约定,真正调用由 agent 或你自己的脚本完成。
66
+ - 余额只能手填:中转站一般没有公开的余额接口。
67
+ - 用量表里的"中转"一列来自 `model-routing-usage.json`,需要外部脚本往里记;不记就是空的。
68
+ - 模型列表读取依赖 profile 配置文件的结构,DSH 大版本改动时可能失效。
69
+
70
+ - **It does not call models.** The config is an agreement about who should do what; the actual calls come from the agent or your own scripts.
71
+ - Balance is manual: relays rarely expose a public balance API.
72
+ - The relay usage column reads `model-routing-usage.json`, which needs an external script to record calls.
73
+ - Catalog parsing depends on the profile config layout and may need updating when DSH changes it.
74
+
75
+ ## 许可 / License
76
+
77
+ MIT.
package/client.js ADDED
@@ -0,0 +1,564 @@
1
+ // 模型分工:浏览器侧。在主侧栏和设置页提供入口。
2
+ window.__ModuleLoader__.load({
3
+ id: 'dsh-model-routing',
4
+ factory(require) {
5
+ const React = require('react')
6
+ const h = React.createElement
7
+ const { useState, useEffect } = React
8
+
9
+ const BASE = '/dsh-model-routing'
10
+ const PANEL = 'model-routing'
11
+ const LABEL = '模型分工'
12
+
13
+ function ModelRouting() {
14
+ const STRINGS = {
15
+ zh: {
16
+ title: '模型分工',
17
+ lead: '为五类任务分别指定模型,并查看各家用量与余额。',
18
+ tasks: '任务分工',
19
+ save: '保存',
20
+ saving: '保存中…',
21
+ saved: '已保存',
22
+ restoreDefaults: '恢复默认',
23
+ loading: '加载中…',
24
+ ready: '就绪',
25
+ notLoaded: '未加载',
26
+ unsavedChanges: '有未保存修改',
27
+ emptyCatalog: '还没在 DSH 里配置模型提供方。请在设置 → 模型里添加,或手动填写。',
28
+ addManual: '手动添加',
29
+ manualPlaceholder: 'provider/model',
30
+ noLongerConfigured: '已不存在',
31
+ missingModelSuffix: (label) => `(${label})`,
32
+ usageAndBalance: '用量与余额',
33
+ routedUsage: '中转用量',
34
+ provider: '提供方',
35
+ calls: '调用次数',
36
+ input: '输入',
37
+ output: '输出',
38
+ balance: '手记余额',
39
+ date: '日期',
40
+ noRoutedUsage: '尚未使用分身模型',
41
+ localTitle: '本机(deepseek)最近 7 天',
42
+ balanceNote: '余额中转站不提供接口,由你手填;用量来自本机记录的调用日志。',
43
+ readConfigError: '读不到配置:',
44
+ saveFailed: '保存失败:',
45
+ invalidResponse: '响应无效',
46
+ errorSeparator: ';',
47
+ planningLabel: '规划与文案',
48
+ planningHint: '长文论证、写说明稿、审改文字。',
49
+ codeLabel: '写代码',
50
+ codeHint: '写脚本、改配置、生成图表的代码。',
51
+ imageLabel: '出图',
52
+ imageHint: '生成或改写图片、封面、插图;不写代码。',
53
+ reviewLabel: '看图审错',
54
+ reviewHint: '检查图纸、界面和版面,指出问题。',
55
+ executeLabel: '决策与执行',
56
+ executeHint: '唯一能改文件、运行脚本并做最终验证。',
57
+ },
58
+ en: {
59
+ title: 'Model routing',
60
+ lead: 'Pick a model for each of the five kinds of work, and check usage and balance.',
61
+ tasks: 'Model per task',
62
+ save: 'Save',
63
+ saving: 'Saving…',
64
+ saved: 'Saved',
65
+ restoreDefaults: 'Restore defaults',
66
+ loading: 'Loading…',
67
+ ready: 'Ready',
68
+ notLoaded: 'Not loaded',
69
+ unsavedChanges: 'Unsaved changes',
70
+ emptyCatalog: 'No model provider is configured in DSH yet. Add one in Settings → Models, or fill it in by hand.',
71
+ addManual: 'Add by hand',
72
+ manualPlaceholder: 'provider/model',
73
+ noLongerConfigured: 'no longer configured',
74
+ missingModelSuffix: (label) => ` (${label})`,
75
+ usageAndBalance: 'Usage and balance',
76
+ routedUsage: 'Routed usage',
77
+ provider: 'Provider',
78
+ calls: 'Calls',
79
+ input: 'Input',
80
+ output: 'Output',
81
+ balance: 'Balance',
82
+ date: 'Date',
83
+ noRoutedUsage: 'No routed model used yet',
84
+ localTitle: 'This machine (deepseek), last 7 days',
85
+ balanceNote: 'Relays expose no balance API, so balances are typed in by hand; usage comes from the local call log.',
86
+ readConfigError: 'Could not read config: ',
87
+ saveFailed: 'Save failed: ',
88
+ invalidResponse: 'Invalid response',
89
+ errorSeparator: '; ',
90
+ planningLabel: 'Planning and writing',
91
+ planningHint: 'Long arguments, documentation, editing prose.',
92
+ codeLabel: 'Code',
93
+ codeHint: 'Scripts, configuration changes, chart-generating code.',
94
+ imageLabel: 'Images',
95
+ imageHint: 'Generate or edit images, covers and illustrations; no code.',
96
+ reviewLabel: 'Review',
97
+ reviewHint: 'Inspect drawings, interfaces and layouts, and name the problems.',
98
+ executeLabel: 'Execution',
99
+ executeHint: 'The only role that edits files, runs scripts and verifies the result.',
100
+ },
101
+ }
102
+
103
+ const lang = (() => {
104
+ try {
105
+ const htmlLang = document.documentElement.getAttribute('lang') || ''
106
+ if (htmlLang) return htmlLang.toLowerCase().startsWith('zh') ? 'zh' : 'en'
107
+ } catch {}
108
+ try {
109
+ const nav = navigator.language || ''
110
+ return nav.toLowerCase().startsWith('zh') ? 'zh' : 'en'
111
+ } catch {}
112
+ return 'en'
113
+ })()
114
+ const t = STRINGS[lang] || STRINGS.en
115
+
116
+ const React = require('react')
117
+ const h = React.createElement
118
+ const { useEffect, useRef, useState } = React
119
+ const base = '/dsh-model-routing'
120
+ const routes = [
121
+ { key: 'planning', label: t.planningLabel, hint: t.planningHint },
122
+ { key: 'code', label: t.codeLabel, hint: t.codeHint },
123
+ { key: 'image', label: t.imageLabel, hint: t.imageHint },
124
+ { key: 'review', label: t.reviewLabel, hint: t.reviewHint },
125
+ { key: 'execute', label: t.executeLabel, hint: t.executeHint },
126
+ ]
127
+ const styles = {
128
+ wrap: {
129
+ boxSizing: 'border-box',
130
+ width: '100%',
131
+ maxWidth: 760,
132
+ padding: '18px 22px',
133
+ fontSize: 13,
134
+ lineHeight: 1.7,
135
+ },
136
+ title: { fontSize: 17, fontWeight: 600, margin: '0 0 6px' },
137
+ badge: { fontSize: 11, opacity: 0.6, marginBottom: 10 },
138
+ section: { marginTop: 18 },
139
+ sectionTitle: { fontSize: 13, fontWeight: 600, margin: '0 0 8px' },
140
+ row: {
141
+ display: 'grid',
142
+ gridTemplateColumns: '110px minmax(0, 1fr)',
143
+ alignItems: 'center',
144
+ gap: 12,
145
+ padding: '8px 0',
146
+ borderBottom: '1px solid rgba(127,127,127,0.18)',
147
+ },
148
+ label: { fontWeight: 500 },
149
+ hint: { opacity: 0.62, fontSize: 12, marginTop: 2 },
150
+ field: {
151
+ boxSizing: 'border-box',
152
+ width: '100%',
153
+ maxWidth: 320,
154
+ padding: '5px 8px',
155
+ borderRadius: 6,
156
+ border: '1px solid rgba(127,127,127,0.35)',
157
+ background: 'transparent',
158
+ color: 'inherit',
159
+ fontSize: 12.5,
160
+ },
161
+ actions: { marginTop: 12, display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'center' },
162
+ button: {
163
+ padding: '6px 14px',
164
+ borderRadius: 6,
165
+ border: '1px solid rgba(127,127,127,0.4)',
166
+ background: 'rgba(127,127,127,0.10)',
167
+ color: 'inherit',
168
+ fontSize: 12.5,
169
+ },
170
+ muted: { opacity: 0.65, fontSize: 12 },
171
+ error: { color: '#df8b7c', fontSize: 12 },
172
+ table: { width: '100%', borderCollapse: 'collapse', fontSize: 12 },
173
+ th: { textAlign: 'left', fontWeight: 500, opacity: 0.65, padding: '4px 6px' },
174
+ td: { padding: '4px 6px', borderTop: '1px solid rgba(127,127,127,0.15)' },
175
+ }
176
+
177
+ const [catalog, setCatalog] = useState(null)
178
+ const [server, setServer] = useState(null)
179
+ const [draft, setDraft] = useState(null)
180
+ const [loading, setLoading] = useState(true)
181
+ const [saving, setSaving] = useState(false)
182
+ const [loadError, setLoadError] = useState('')
183
+ const [saveError, setSaveError] = useState('')
184
+ const [saved, setSaved] = useState(null)
185
+ const [manualText, setManualText] = useState('')
186
+ const [manualModels, setManualModels] = useState([])
187
+ const saveRequest = useRef(null)
188
+
189
+ async function request(path, options) {
190
+ const response = await fetch(base + path, {
191
+ credentials: 'same-origin',
192
+ ...options,
193
+ })
194
+ if (!response.ok) throw new Error('HTTP ' + response.status)
195
+ return response.json()
196
+ }
197
+
198
+ useEffect(() => {
199
+ const controller = new AbortController()
200
+ const options = { cache: 'no-store', signal: controller.signal }
201
+
202
+ async function load() {
203
+ const [catalogResult, stateResult] = await Promise.allSettled([
204
+ request('/catalog', options),
205
+ request('/state', options),
206
+ ])
207
+ if (controller.signal.aborted) return
208
+
209
+ if (catalogResult.status === 'fulfilled') {
210
+ setCatalog(catalogResult.value.providers)
211
+ }
212
+ if (stateResult.status === 'fulfilled') {
213
+ const data = stateResult.value
214
+ setServer(data)
215
+ setDraft({ routing: data.routing, balances: data.balances })
216
+ }
217
+
218
+ const failures = [
219
+ ['/catalog', catalogResult],
220
+ ['/state', stateResult],
221
+ ].filter(([, result]) => result.status === 'rejected')
222
+ if (failures.length) {
223
+ setLoadError(t.readConfigError + failures.map(([path, result]) =>
224
+ path + ' ' + (result.reason?.message || String(result.reason)),
225
+ ).join(t.errorSeparator))
226
+ }
227
+ setLoading(false)
228
+ }
229
+
230
+ load()
231
+ return () => {
232
+ controller.abort()
233
+ saveRequest.current?.abort()
234
+ saveRequest.current = null
235
+ }
236
+ }, [])
237
+
238
+ useEffect(() => {
239
+ if (!saved) return
240
+ const timer = setTimeout(() => setSaved(null), 2000)
241
+ return () => clearTimeout(timer)
242
+ }, [saved])
243
+
244
+ const busy = loading || saving
245
+ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key)
246
+ const serverBalances = server?.balances ?? {}
247
+ const draftBalances = draft?.balances ?? {}
248
+ const balanceNames = Object.keys(draftBalances)
249
+ const dirty = Boolean(draft && server && (
250
+ routes.some(({ key }) =>
251
+ draft.routing[key]?.provider !== server.routing[key]?.provider ||
252
+ draft.routing[key]?.model !== server.routing[key]?.model,
253
+ ) ||
254
+ balanceNames.length !== Object.keys(serverBalances).length ||
255
+ balanceNames.some((name) =>
256
+ !hasOwn(serverBalances, name) || draftBalances[name] !== serverBalances[name],
257
+ )
258
+ ))
259
+
260
+ function updateDraft(update) {
261
+ if (busy || saveRequest.current || !draft) return
262
+ setDraft(update)
263
+ setSaved(null)
264
+ }
265
+
266
+ async function save() {
267
+ if (busy || saveRequest.current || !draft) return
268
+ const controller = new AbortController()
269
+ saveRequest.current = controller
270
+ setSaving(true)
271
+ setSaved(null)
272
+ setSaveError('')
273
+
274
+ try {
275
+ const data = await request('/routing', {
276
+ method: 'POST',
277
+ headers: { 'Content-Type': 'application/json' },
278
+ body: JSON.stringify({ routing: draft.routing, balances: draft.balances }),
279
+ signal: controller.signal,
280
+ })
281
+ if (controller.signal.aborted) return
282
+ if (data.ok !== true || !data.routing || !data.balances) {
283
+ throw new Error(data.error || t.invalidResponse)
284
+ }
285
+ const readback = { routing: data.routing, balances: data.balances }
286
+ setServer((previous) => ({ ...previous, ...readback }))
287
+ setDraft(readback)
288
+ setSaved(readback)
289
+ } catch (error) {
290
+ if (!controller.signal.aborted) {
291
+ setSaveError(t.saveFailed + (error?.message || String(error)))
292
+ }
293
+ } finally {
294
+ if (saveRequest.current === controller) {
295
+ saveRequest.current = null
296
+ setSaving(false)
297
+ }
298
+ }
299
+ }
300
+
301
+ const groups = new Map()
302
+ for (const provider of catalog ?? []) {
303
+ groups.set(provider.id, {
304
+ label: provider.displayName || provider.id,
305
+ models: new Set(provider.models),
306
+ })
307
+ }
308
+
309
+ const catalogEmpty = catalog !== null &&
310
+ !Array.from(groups.values()).some(({ models }) => models.size > 0)
311
+
312
+ for (const { provider, model } of manualModels) {
313
+ if (!groups.has(provider)) {
314
+ groups.set(provider, { label: provider, models: new Set() })
315
+ }
316
+ groups.get(provider).models.add(model)
317
+ }
318
+
319
+ const modelValue = ({ provider, model }) => provider + '|' + model
320
+ const hasModel = ({ provider, model }) => groups.get(provider)?.models.has(model)
321
+ const modelsByValue = new Map()
322
+ const groupOptions = []
323
+ for (const [provider, { label, models }] of groups) {
324
+ if (!models.size) continue
325
+ const options = Array.from(models, (model) => {
326
+ const selection = { provider, model }
327
+ const value = modelValue(selection)
328
+ modelsByValue.set(value, selection)
329
+ return h('option', { key: model, value }, model)
330
+ })
331
+ groupOptions.push(h('optgroup', { key: provider, label }, ...options))
332
+ }
333
+
334
+ const separator = manualText.indexOf('/')
335
+ const manualProvider = separator < 0 ? '' : manualText.slice(0, separator).trim()
336
+ const manualModel = separator < 0 ? '' : manualText.slice(separator + 1).trim()
337
+ const canAddManual = Boolean(manualProvider && manualModel)
338
+
339
+ function addManual() {
340
+ if (busy || saveRequest.current || !canAddManual) return
341
+ setManualModels((previous) => {
342
+ if (previous.some(({ provider, model }) =>
343
+ provider === manualProvider && model === manualModel,
344
+ )) return previous
345
+ return [...previous, { provider: manualProvider, model: manualModel }]
346
+ })
347
+ setManualText('')
348
+ }
349
+
350
+ function renderRoute({ key, label, hint }) {
351
+ const emptySelection = { provider: '', model: '' }
352
+ const current = draft?.routing?.[key] ?? emptySelection
353
+ const configured = server?.routing?.[key] ?? emptySelection
354
+ const options = new Map(modelsByValue)
355
+ options.set('', emptySelection)
356
+
357
+ const missingOptions = []
358
+ for (const selection of [current, configured]) {
359
+ if ((!selection.provider && !selection.model) || hasModel(selection)) continue
360
+ const value = modelValue(selection)
361
+ if (options.has(value)) continue
362
+ options.set(value, selection)
363
+ missingOptions.push(h('option', { key: value, value },
364
+ selection.provider + ' / ' + selection.model +
365
+ (catalog === null ? '' : t.missingModelSuffix(t.noLongerConfigured)),
366
+ ))
367
+ }
368
+
369
+ return h('label', { key, style: styles.row },
370
+ h('span', null,
371
+ h('span', { style: styles.label }, label),
372
+ h('span', { style: { ...styles.hint, display: 'block' } }, hint),
373
+ ),
374
+ h('select', {
375
+ style: styles.field,
376
+ 'aria-label': label,
377
+ value: current.provider || current.model ? modelValue(current) : '',
378
+ disabled: busy || !draft || groupOptions.length === 0,
379
+ onChange: (event) => {
380
+ const selection = options.get(event.target.value)
381
+ if (!selection) return
382
+ updateDraft((previous) => ({
383
+ ...previous,
384
+ routing: { ...previous.routing, [key]: selection },
385
+ }))
386
+ },
387
+ },
388
+ h('option', { value: '' }, '—'),
389
+ ...missingOptions,
390
+ ...groupOptions),
391
+ )
392
+ }
393
+
394
+ function fmt(number) {
395
+ if (!number) return '0'
396
+ if (number >= 1e6) return (number / 1e6).toFixed(2) + 'M'
397
+ if (number >= 1e3) return (number / 1e3).toFixed(1) + 'k'
398
+ return String(number)
399
+ }
400
+
401
+ function table(label, columns, rows) {
402
+ return h('table', { style: styles.table, 'aria-label': label },
403
+ h('thead', null, h('tr', null,
404
+ ...columns.map((column) =>
405
+ h('th', { key: column, scope: 'col', style: styles.th }, column),
406
+ ),
407
+ )),
408
+ h('tbody', null, ...rows),
409
+ )
410
+ }
411
+
412
+ const relay = server?.relay?.byProvider ?? {}
413
+ const relayUsageNames = Object.keys(relay)
414
+ const relayNames = Array.from(new Set([...relayUsageNames, ...Object.keys(serverBalances)]))
415
+ const relayRows = relayNames.map((name) => {
416
+ const row = hasOwn(relay, name) ? relay[name] : undefined
417
+ return h('tr', { key: name },
418
+ h('td', { style: styles.td }, name),
419
+ h('td', { style: styles.td }, String(row?.calls ?? 0)),
420
+ h('td', { style: styles.td }, fmt(row?.input)),
421
+ h('td', { style: styles.td }, fmt(row?.output)),
422
+ h('td', { style: styles.td },
423
+ h('input', {
424
+ type: 'number',
425
+ step: 'any',
426
+ 'aria-label': name + ' ' + t.balance,
427
+ style: { ...styles.field, maxWidth: 110, padding: '2px 6px' },
428
+ value: hasOwn(draftBalances, name) ? draftBalances[name] : '',
429
+ disabled: busy || !draft,
430
+ onChange: (event) => {
431
+ const { value, valueAsNumber, validity } = event.target
432
+ if (validity.badInput || (value !== '' && !Number.isFinite(valueAsNumber))) return
433
+ updateDraft((previous) => {
434
+ const balances = { ...previous.balances, [name]: valueAsNumber }
435
+ if (value === '') delete balances[name]
436
+ return { ...previous, balances }
437
+ })
438
+ },
439
+ }),
440
+ ),
441
+ )
442
+ })
443
+
444
+ const localTitle = t.localTitle
445
+ const localRows = (server?.local?.days ?? []).slice()
446
+ .sort((left, right) => right.date.localeCompare(left.date))
447
+ .slice(0, 7)
448
+ .map((row) => h('tr', { key: row.date },
449
+ h('td', { style: styles.td }, row.date),
450
+ h('td', { style: styles.td }, fmt(row.input)),
451
+ h('td', { style: styles.td }, fmt(row.output)),
452
+ ))
453
+
454
+ return h('div', { style: styles.wrap },
455
+ h('h2', { style: styles.title }, t.title),
456
+ h('div', { style: styles.muted }, t.lead),
457
+ h('div', { style: styles.badge, role: 'status' },
458
+ 'v1.0.0 · ' + (loading ? t.loading : catalog !== null && draft ? t.ready : t.notLoaded),
459
+ ),
460
+
461
+ h('div', { style: styles.section },
462
+ h('div', { style: styles.sectionTitle }, t.tasks),
463
+ ...routes.map(renderRoute),
464
+ catalogEmpty ? h('div', { style: { marginTop: 10 } },
465
+ h('div', { style: styles.muted }, t.emptyCatalog),
466
+ h('div', { style: styles.actions },
467
+ h('input', {
468
+ type: 'text',
469
+ placeholder: t.manualPlaceholder,
470
+ 'aria-label': t.manualPlaceholder,
471
+ style: styles.field,
472
+ value: manualText,
473
+ disabled: busy,
474
+ onChange: (event) => setManualText(event.target.value),
475
+ }),
476
+ h('button', {
477
+ type: 'button',
478
+ style: styles.button,
479
+ disabled: busy || !canAddManual,
480
+ onClick: addManual,
481
+ }, t.addManual),
482
+ ),
483
+ ) : null,
484
+ ),
485
+
486
+ h('div', { style: styles.actions },
487
+ h('button', {
488
+ type: 'button',
489
+ style: styles.button,
490
+ onClick: save,
491
+ disabled: busy || !draft,
492
+ }, saving ? t.saving : t.save),
493
+ dirty ? h('span', { style: { fontSize: 12, opacity: 0.7 } }, t.unsavedChanges) : null,
494
+ h('button', {
495
+ type: 'button',
496
+ style: styles.button,
497
+ disabled: busy || !draft || !server?.defaults,
498
+ onClick: () => {
499
+ if (server?.defaults) {
500
+ updateDraft((previous) => ({ ...previous, routing: server.defaults }))
501
+ }
502
+ },
503
+ }, t.restoreDefaults),
504
+ saved ? h('span', { style: styles.muted, role: 'status' }, t.saved) : null,
505
+ ),
506
+ loadError ? h('div', { style: styles.error, role: 'alert' }, loadError) : null,
507
+ saveError ? h('div', { style: styles.error, role: 'alert' }, saveError) : null,
508
+
509
+ h('div', { style: styles.section },
510
+ h('div', { style: styles.sectionTitle }, t.usageAndBalance),
511
+ table(t.routedUsage, [t.provider, t.calls, t.input, t.output, t.balance], relayRows),
512
+ server && relayUsageNames.length === 0
513
+ ? h('div', { style: styles.muted }, t.noRoutedUsage)
514
+ : null,
515
+ h('div', { style: { marginTop: 12 } },
516
+ h('div', { style: { ...styles.muted, marginBottom: 4 } }, localTitle),
517
+ table(localTitle, [t.date, t.input, t.output], localRows),
518
+ ),
519
+ h('div', { style: { ...styles.muted, marginTop: 8 } }, t.balanceNote),
520
+ ),
521
+ )
522
+ }
523
+
524
+ function SectionIcon() {
525
+ return h('svg', {
526
+ viewBox: '0 0 24 24', width: 20, height: 20, 'aria-hidden': true,
527
+ style: { display: 'block' },
528
+ },
529
+ h('path', {
530
+ d: 'M4 6h6v5H4zM14 6h6v5h-6zM4 13h6v5H4zM14 13h6v5h-6z',
531
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinejoin: 'round',
532
+ }),
533
+ )
534
+ }
535
+
536
+ return {
537
+ inject: ['slots', 'uiWorkspace'],
538
+ apply(ctx) {
539
+ ctx.slots.inject('settings.section.icon', () => ctx.slots.register({
540
+ name: 'settings.section.icon',
541
+ id: PANEL,
542
+ order: 45,
543
+ }, SectionIcon))
544
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
545
+ name: 'settings.section',
546
+ id: PANEL,
547
+ order: 45,
548
+ label: LABEL,
549
+ }, ModelRouting))
550
+
551
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
552
+ name: 'sidebar.panellist',
553
+ id: PANEL,
554
+ order: 35,
555
+ label: () => LABEL,
556
+ }, SectionIcon))
557
+ ctx.slots.inject('main', () => ctx.slots.register({
558
+ name: 'main',
559
+ key: PANEL,
560
+ }, ModelRouting))
561
+ },
562
+ }
563
+ },
564
+ })
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: dsh-model-routing
3
+ name: dsh-model-routing
4
+ config: {}
package/docs/DETAIL.md ADDED
@@ -0,0 +1,60 @@
1
+ # 模型分工 Model routing
2
+
3
+ ## 它做什么
4
+
5
+ 给五类工作各指定一个模型:
6
+
7
+ | 分类 | 适合的活 |
8
+ |---|---|
9
+ | 规划与文案 | 长文论证、写说明稿、审改文字 |
10
+ | 写代码 | 写脚本、改配置、生成图表的代码(只出内容,不改文件) |
11
+ | 出图 | 生成或改写图片、封面、插图(不写代码) |
12
+ | 看图审错 | 检查图纸、界面、版面,指出问题 |
13
+ | 决策与执行 | 唯一能改文件、跑脚本、做最终验证的那一类 |
14
+
15
+ 同一页还显示:中转方的调用次数与 token、本机(deepseek)最近 7 天的用量、以及一个手填的余额栏。
16
+
17
+ ## 模型列表是动态的
18
+
19
+ 下拉框的选项来自你在 DSH 里**已经配置好的提供方**,不是插件写死的名单:
20
+
21
+ ```
22
+ ~/.dsh/profiles/<profile>/cordis.patch.yml
23
+ └─ llm-pi-ai
24
+ └─ providers
25
+ └─ <providerId>: displayName / models[].id
26
+ ```
27
+
28
+ 所以换中转、加模型,只要在 DSH 设置里改一次,这里立刻能看到。
29
+ 一个提供方都没配时,五行会变灰,并提示去设置里添加;也可以用手动输入 `provider/model` 临时添加。
30
+
31
+ ## 存储位置
32
+
33
+ ```
34
+ ~/.dsh/model-routing.json 分工配置(routing + balances)
35
+ ~/.dsh/model-routing-usage.json 调用日志(可选;不记则"中转用量"为空)
36
+ ```
37
+
38
+ 本机用量读 `~/.dsh/storages/cost-meter/ledger.json`(需要 dsh-cost-meter 插件)。
39
+
40
+ ## 两个入口
41
+
42
+ - 左侧栏「模型分工」
43
+ - 设置 → 模型分工
44
+
45
+ 两处是同一个面板。
46
+
47
+ ## 局限
48
+
49
+ - **插件不调用模型。** 它只是一份"该用谁"的约定;真正发起调用的是 agent 或你自己的脚本。
50
+ - **余额只能手填**:中转站普遍没有公开的余额查询接口。
51
+ - **中转用量依赖外部记录**:没有脚本往 `model-routing-usage.json` 写,这一列就是空的。
52
+ - **模型列表靠解析 profile 配置**:DSH 大版本改动配置结构时,这里可能需要跟着改。
53
+
54
+ ## 卸载
55
+
56
+ ```bash
57
+ dsh plugin --profile <name> remove dsh-model-routing
58
+ ```
59
+
60
+ 配置文件保留,删掉 `~/.dsh/model-routing.json` 即彻底清空。
@@ -0,0 +1,75 @@
1
+ # 发布清单(dsh-model-routing)
2
+
3
+ > 查证时间 2026-12-03。规则来自 awesome-dsh-plugin 的贡献指南与 dshmarket 的 README。
4
+ > 市场规则会变,动手前以仓库里的 `contributing.md` 为准。
5
+
6
+ ## 结论:上架 = 一个仓库 + 一个 PR
7
+
8
+ ```
9
+ 插件列表的数据源 awesome-dsh-plugin 仓库的 data/plugins/*.yml
10
+ dshmarket(市场应用) 只是读这份列表,明确不直接收条目
11
+ 所以「上架」= 公开 GitHub 仓库 + 往 awesome-dsh-plugin 提一个 YAML PR
12
+ 合并后站点与市场一般 1 天内自动收录
13
+ ```
14
+
15
+ ## 硬门槛(CI 会查,逐条对)
16
+
17
+ | 项 | 现状 |
18
+ |---|---|
19
+ | 公开 GitHub 仓库 | ⬜ 待建(`sunner-ds/SUN`) |
20
+ | 仓库创建满 1 天 | ⬜ 建完要等到第二天 |
21
+ | 提交数 ≥ 10 | ⬜ 待补(现在还没初始化仓库) |
22
+ | `package.json` 声明 `dsh.bundle` | ✅ 已声明 |
23
+ | `cordis.patch.yml` 在默认分支 | ✅ 有 |
24
+ | 打 `dsh-plugin` topic | ⬜ 建仓库后点一下 |
25
+ | 中英双语展示元数据 | ✅ `locale/en.json` + `locale/zh.json` |
26
+ | MIT LICENSE / README / 图标 / 详情页 | ✅ 四项齐全 |
27
+ | 真实可用代码(占位仓库不收) | ✅ host + client 都能跑 |
28
+
29
+ ## 步骤
30
+
31
+ ### ① 建仓库并推送
32
+
33
+ ```bash
34
+ cd "D:\deep seek work\chajia\plugins\dsh-model-routing"
35
+ git init
36
+ git add .
37
+ git commit -m "feat: model routing panel for DSH"
38
+ # 再补到 10 个提交(CI 查提交数):可以按功能拆分提交,
39
+ # 例如 locale、docs、icon、client i18n、catalog 解析 各一个
40
+ git remote add origin https://github.com/sunner-ds/SUN.git
41
+ git push -u origin main
42
+ ```
43
+
44
+ **注意**:这台机器现在直连 GitHub 可能不通(之前的系统代理已关)。推之前先试 `git ls-remote`,不通就开代理或换 https + token。
45
+
46
+ ### ② 打 topic
47
+
48
+ GitHub 仓库页 → 右上 About 的齿轮 → Topics 填 `dsh-plugin` → 保存。
49
+
50
+ ### ③ (推荐)发 npm
51
+
52
+ 市场装包优先走 npm tarball,且会校验 `repository` 与仓库一致(防冒名)。
53
+
54
+ ```bash
55
+ # 本机 .npmrc 指向镜像时,必须显式指定官方源
56
+ pnpm publish --access public --no-git-checks --registry=https://registry.npmjs.org
57
+ ```
58
+
59
+ 包名 `dsh-model-routing` 先在 https://registry.npmjs.org/dsh-model-routing 确认没被占。
60
+
61
+ ### ④ 提 PR 到 awesome-dsh-plugin
62
+
63
+ 新增一个文件 `data/plugins/sunner-ds__SUN.yml`,内容见本目录 `market-entry.yml`。
64
+ 一个 PR 只加一个文件。
65
+
66
+ ### ⑤ 等收录
67
+
68
+ 合并后 `https://awesome-dsh-plugin.com/plugins.json` 重建,市场打开时实时拉取,一般 1 天内能看到。
69
+
70
+ ## 发布前最后一道自检
71
+
72
+ - [ ] 目录里没有真名、学号、手机号(`.gitignore` 已挡,但仓库是新的,再搜一次)
73
+ - [ ] 没有密钥(本插件不含 key,配置只存在用户本机 `~/.dsh/model-routing.json`)
74
+ - [ ] README 里「局限」那几条写的是真实行为
75
+ - [ ] 版本号 1.0.0,与 market-entry 里一致
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
2
+ <rect x="3" y="4" width="11" height="10" rx="1.5" fill="none" stroke="#2f6d8f" stroke-width="2"/>
3
+ <rect x="18" y="4" width="11" height="10" rx="1.5" fill="none" stroke="#2f6d8f" stroke-width="2"/>
4
+ <rect x="3" y="18" width="11" height="10" rx="1.5" fill="none" stroke="#2f6d8f" stroke-width="2"/>
5
+ <rect x="18" y="18" width="11" height="10" rx="1.5" fill="#2f6d8f"/>
6
+ </svg>
package/index.js ADDED
@@ -0,0 +1,376 @@
1
+ // 模型分工 · Host 侧:配置、用量、模型目录(从 DSH 配置里读 provider/model)
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+
6
+ const CONFIG_PATH = path.join(os.homedir(), '.dsh', 'model-routing.json')
7
+ const LEDGER_PATH = path.join(os.homedir(), '.dsh', 'storages', 'cost-meter', 'ledger.json')
8
+ const USAGE_PATH = path.join(os.homedir(), '.dsh', 'model-routing-usage.json')
9
+ const PROFILES_ROOT = path.join(os.homedir(), '.dsh', 'profiles')
10
+
11
+ const ROUTE_KEYS = ['planning', 'code', 'image', 'review', 'execute']
12
+
13
+ // 旧版把「代码」和「出图」合成一类,读配置时展开,升级不掉值
14
+ const LEGACY_ROUTES = { code_image: ['code', 'image'] }
15
+
16
+ const DEFAULT_ROUTING = {
17
+ planning: { provider: '', model: '' },
18
+ code: { provider: '', model: '' },
19
+ image: { provider: '', model: '' },
20
+ review: { provider: '', model: '' },
21
+ execute: { provider: '', model: '' },
22
+ }
23
+
24
+ function readJson(file, fallback) {
25
+ try {
26
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
27
+ } catch {
28
+ return fallback
29
+ }
30
+ }
31
+
32
+ /* ---------- 模型目录:从 profile 的 cordis.patch.yml 里解析 llm-pi-ai 的 providers ---------- */
33
+
34
+ // 内置提供方(不写在 patch 的 llm-pi-ai 里)从 allowedModels 里认出来
35
+ function parseAllowedModels(text) {
36
+ const pairs = []
37
+ const lines = text.split(/\r?\n/)
38
+ let provider = ''
39
+ for (const line of lines) {
40
+ const pm = line.match(/^\s*-\s*provider:\s*['"]?([A-Za-z0-9_.-]+)['"]?\s*$/)
41
+ if (pm) {
42
+ provider = pm[1]
43
+ continue
44
+ }
45
+ const mm = line.match(/^\s*model:\s*['"]?([A-Za-z0-9_.-]+)['"]?\s*$/)
46
+ if (mm && provider) {
47
+ pairs.push({ provider, model: mm[1] })
48
+ provider = '' // 一个 provider 只跟一个 model,避免把后面的 model 误挂过来
49
+ continue
50
+ }
51
+ // 遇到其它顶层插件或非列表配置,清空待配对的 provider
52
+ if (/^- id:/.test(line)) provider = ''
53
+ }
54
+ return pairs
55
+ }
56
+
57
+ function mergeAllowedModels(providers, allowed) {
58
+ const byId = new Map(providers.map((p) => [p.id, p]))
59
+ for (const { provider, model } of allowed) {
60
+ if (!byId.has(provider)) {
61
+ const created = { id: provider, displayName: provider, models: [] }
62
+ byId.set(provider, created)
63
+ providers.push(created)
64
+ }
65
+ const entry = byId.get(provider)
66
+ if (!entry.models.includes(model)) entry.models.push(model)
67
+ }
68
+ return providers
69
+ }
70
+
71
+
72
+ function listPatchFiles() {
73
+ const out = []
74
+ try {
75
+ for (const entry of fs.readdirSync(PROFILES_ROOT, { withFileTypes: true })) {
76
+ if (!entry.isDirectory()) continue
77
+ const file = path.join(PROFILES_ROOT, entry.name, 'cordis.patch.yml')
78
+ try {
79
+ const stat = fs.statSync(file)
80
+ out.push({ file, mtime: stat.mtimeMs, profile: entry.name })
81
+ } catch {
82
+ // 该 profile 没有 patch,跳过
83
+ }
84
+ }
85
+ } catch {
86
+ // profiles 根目录不存在
87
+ }
88
+ return out.sort((a, b) => b.mtime - a.mtime)
89
+ }
90
+
91
+ // 极简 YAML 片段解析:只认 llm-pi-ai 下的 providers → displayName / models[].id
92
+ function parseProvidersFromPatch(text) {
93
+ const lines = text.split(/\r?\n/)
94
+ const providers = []
95
+ let inPiAi = false
96
+ let current = null
97
+ let inModels = false
98
+
99
+ const indentOf = (line) => line.match(/^ */)[0].length
100
+
101
+ for (let i = 0; i < lines.length; i++) {
102
+ const line = lines[i]
103
+ if (!line.trim() || line.trim().startsWith('#')) continue
104
+
105
+ if (/^\s*-\s*id:\s*llm-pi-ai\s*$/.test(line)) {
106
+ inPiAi = true
107
+ continue
108
+ }
109
+ // 只有顶格的 "- id:" 才是「下一个插件」;模型项是缩进的 "- id: 模型名"
110
+ if (inPiAi && /^- id:/.test(line)) {
111
+ inPiAi = false
112
+ current = null
113
+ inModels = false
114
+ continue
115
+ }
116
+ if (!inPiAi) continue
117
+
118
+ const providerMatch = line.match(/^(\s+)([A-Za-z0-9_.-]+):\s*$/)
119
+ if (providerMatch && indentOf(line) === 6) {
120
+ current = { id: providerMatch[2], displayName: providerMatch[2], models: [] }
121
+ providers.push(current)
122
+ inModels = false
123
+ continue
124
+ }
125
+ if (!current) continue
126
+
127
+ const nameMatch = line.match(/^\s+displayName:\s*(.+?)\s*$/)
128
+ if (nameMatch) {
129
+ current.displayName = nameMatch[1].replace(/^['"]|['"]$/g, '')
130
+ continue
131
+ }
132
+ if (/^\s+models:\s*$/.test(line)) {
133
+ inModels = true
134
+ continue
135
+ }
136
+ if (inModels) {
137
+ const modelMatch = line.match(/^\s+-\s*id:\s*(.+?)\s*$/)
138
+ if (modelMatch) {
139
+ current.models.push(modelMatch[1].replace(/^['"]|['"]$/g, ''))
140
+ continue
141
+ }
142
+ if (/^\s+[A-Za-z]/.test(line) && !/^\s+-\s/.test(line) && indentOf(line) <= 8) {
143
+ inModels = false
144
+ }
145
+ }
146
+ }
147
+
148
+ return providers.filter((p) => p.models.length > 0)
149
+ }
150
+
151
+ function readCatalog() {
152
+ const files = listPatchFiles()
153
+ for (const item of files) {
154
+ let text = ''
155
+ try {
156
+ text = fs.readFileSync(item.file, 'utf8')
157
+ } catch {
158
+ continue
159
+ }
160
+ if (!text.includes('llm-pi-ai') && !text.includes('allowedModels')) continue
161
+ const providers = parseProvidersFromPatch(text)
162
+ const allowed = parseAllowedModels(text)
163
+ const merged = mergeAllowedModels(providers, allowed)
164
+ if (merged.length > 0) {
165
+ return { profile: item.profile, source: item.file, providers: merged }
166
+ }
167
+ }
168
+ return { profile: '', source: '', providers: [] }
169
+ }
170
+
171
+ /* ---------- 配置 ---------- */
172
+
173
+ function normalizeRouting(raw) {
174
+ const routing = {}
175
+ for (const key of ROUTE_KEYS) {
176
+ const row = raw && raw[key]
177
+ routing[key] =
178
+ row && typeof row.provider === 'string' && typeof row.model === 'string'
179
+ ? { provider: row.provider, model: row.model }
180
+ : { ...DEFAULT_ROUTING[key] }
181
+ }
182
+ return routing
183
+ }
184
+
185
+ function readConfig() {
186
+ const raw = readJson(CONFIG_PATH, null) || {}
187
+ const isV2 = raw && raw.version === 2
188
+ const defaultEntry = isV2 ? raw.default || {} : raw
189
+ const balances = (isV2 ? defaultEntry.balances : raw.balances) || {}
190
+ const workspaces = {}
191
+ if (isV2 && raw.workspaces && typeof raw.workspaces === 'object') {
192
+ for (const [key, entry] of Object.entries(raw.workspaces)) {
193
+ workspaces[key] = normalizeRouting(entry)
194
+ }
195
+ }
196
+ return { routing: normalizeRouting(defaultEntry), balances, workspaces }
197
+ }
198
+
199
+ function writeConfig(payload) {
200
+ fs.mkdirSync(path.dirname(CONFIG_PATH), { recursive: true })
201
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(payload, null, 2) + '\n', 'utf8')
202
+ }
203
+
204
+ /* ---------- 用量 ---------- */
205
+
206
+ function readCalls() {
207
+ const data = readJson(USAGE_PATH, { calls: [] })
208
+ const list = Array.isArray(data && data.calls) ? data.calls : []
209
+ const byProvider = {}
210
+ let total = { input: 0, output: 0, calls: 0 }
211
+ for (const c of list) {
212
+ const key = String(c.provider || 'unknown')
213
+ if (!byProvider[key]) byProvider[key] = { input: 0, output: 0, calls: 0, models: {} }
214
+ const inTok = Number(c.input) || 0
215
+ const outTok = Number(c.output) || 0
216
+ byProvider[key].input += inTok
217
+ byProvider[key].output += outTok
218
+ byProvider[key].calls += 1
219
+ const model = String(c.model || 'unknown')
220
+ byProvider[key].models[model] = (byProvider[key].models[model] || 0) + inTok + outTok
221
+ total = { input: total.input + inTok, output: total.output + outTok, calls: total.calls + 1 }
222
+ }
223
+ return { byProvider, total, recent: list.slice(-12).reverse() }
224
+ }
225
+
226
+ function localUsage() {
227
+ const ledger = readJson(LEDGER_PATH, null)
228
+ if (!ledger || typeof ledger !== 'object') return { days: [], total: { input: 0, output: 0 } }
229
+ const days = ledger.days && typeof ledger.days === 'object' ? ledger.days : {}
230
+ const rows = Object.keys(days)
231
+ .sort()
232
+ .slice(-7)
233
+ .map((k) => {
234
+ const d = days[k] || {}
235
+ return { date: k, input: Number(d.input) || 0, output: Number(d.output) || 0 }
236
+ })
237
+ const total = rows.reduce(
238
+ (a, r) => ({ input: a.input + r.input, output: a.output + r.output }),
239
+ { input: 0, output: 0 },
240
+ )
241
+ return { days: rows, total }
242
+ }
243
+
244
+ /* ---------- HTTP ---------- */
245
+
246
+ async function readBody(req) {
247
+ const chunks = []
248
+ for await (const chunk of req) chunks.push(chunk)
249
+ const text = Buffer.concat(chunks).toString('utf8')
250
+ if (!text) return null
251
+ try {
252
+ return JSON.parse(text)
253
+ } catch {
254
+ return null
255
+ }
256
+ }
257
+
258
+ function sendJson(res, status, payload) {
259
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
260
+ res.end(JSON.stringify(payload))
261
+ }
262
+
263
+ export function apply(ctx, config = {}) {
264
+ const base = typeof config.basePath === 'string' && config.basePath ? config.basePath : '/dsh-model-routing'
265
+
266
+ ctx.inject(['webServer'], (webCtx) => {
267
+ const disposers = []
268
+
269
+ disposers.push(
270
+ webCtx.webServer.register({
271
+ kind: 'exact',
272
+ path: `${base}/catalog`,
273
+ handler: async (req, res) => {
274
+ if (req.method !== 'GET') return sendJson(res, 405, { error: 'method not allowed' })
275
+ try {
276
+ const catalog = readCatalog()
277
+ return sendJson(res, 200, catalog)
278
+ } catch (err) {
279
+ return sendJson(res, 500, { error: String(err && err.message ? err.message : err) })
280
+ }
281
+ },
282
+ }),
283
+ )
284
+
285
+ disposers.push(
286
+ webCtx.webServer.register({
287
+ kind: 'exact',
288
+ path: `${base}/state`,
289
+ handler: async (req, res) => {
290
+ if (req.method !== 'GET') return sendJson(res, 405, { error: 'method not allowed' })
291
+ try {
292
+ const url = new URL(req.url || '/', 'http://localhost')
293
+ const workspace = url.searchParams.get('workspace') || ''
294
+ const { routing, balances, workspaces } = readConfig()
295
+ const entry = workspace && workspaces[workspace] ? workspaces[workspace] : routing
296
+ const effectiveBalances = workspace && workspaces[workspace] ? (readJson(CONFIG_PATH, {}) || {}).workspaces?.[workspace]?.balances || {} : balances
297
+ return sendJson(res, 200, {
298
+ workspace,
299
+ useDefault: !(workspace && workspaces[workspace]),
300
+ routing: entry,
301
+ defaults: DEFAULT_ROUTING,
302
+ balances: effectiveBalances,
303
+ savedWorkspaces: Object.keys(workspaces),
304
+ catalog: readCatalog(),
305
+ relay: readCalls(),
306
+ local: localUsage(),
307
+ configPath: CONFIG_PATH,
308
+ usagePath: USAGE_PATH,
309
+ })
310
+ } catch (err) {
311
+ return sendJson(res, 500, { error: String(err && err.message ? err.message : err) })
312
+ }
313
+ },
314
+ }),
315
+ )
316
+
317
+ disposers.push(
318
+ webCtx.webServer.register({
319
+ kind: 'exact',
320
+ path: `${base}/routing`,
321
+ handler: async (req, res) => {
322
+ if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' })
323
+ try {
324
+ const body = await readBody(req)
325
+ if (!body || typeof body !== 'object') return sendJson(res, 400, { error: 'invalid body' })
326
+ const raw = readJson(CONFIG_PATH, {}) || {}
327
+ const isV2 = raw && raw.version === 2
328
+ const routing = {}
329
+ for (const key of ROUTE_KEYS) {
330
+ const row = body.routing && body.routing[key]
331
+ if (!row || typeof row.provider !== 'string' || typeof row.model !== 'string') {
332
+ return sendJson(res, 400, { error: `missing route: ${key}` })
333
+ }
334
+ routing[key] = { provider: row.provider.slice(0, 120), model: row.model.slice(0, 120) }
335
+ }
336
+ const balances = {}
337
+ if (body.balances && typeof body.balances === 'object') {
338
+ for (const [k, v] of Object.entries(body.balances)) {
339
+ const num = Number(v)
340
+ if (Number.isFinite(num)) balances[k] = num
341
+ }
342
+ } else {
343
+ Object.assign(balances, (isV2 ? raw.default || {} : raw).balances || {})
344
+ }
345
+
346
+ const workspace = typeof body.workspace === 'string' ? body.workspace.slice(0, 400) : ''
347
+ const next = isV2 ? raw : { version: 2, default: { ...normalizeRouting(raw), balances: raw.balances || {} }, workspaces: {} }
348
+ next.version = 2
349
+ next.workspaces = next.workspaces && typeof next.workspaces === 'object' ? next.workspaces : {}
350
+ if (!next.default) next.default = { ...DEFAULT_ROUTING, balances: {} }
351
+
352
+ if (workspace) {
353
+ next.workspaces[workspace] = { ...routing, balances }
354
+ } else {
355
+ next.default = { ...routing, balances }
356
+ }
357
+ writeConfig(next)
358
+ return sendJson(res, 200, { ok: true, workspace, routing, balances })
359
+ } catch (err) {
360
+ return sendJson(res, 500, { error: String(err && err.message ? err.message : err) })
361
+ }
362
+ },
363
+ }),
364
+ )
365
+
366
+ return () => {
367
+ for (const dispose of disposers) {
368
+ try {
369
+ dispose()
370
+ } catch {
371
+ // 忽略卸载异常
372
+ }
373
+ }
374
+ }
375
+ })
376
+ }
package/locale/en.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "meta": {
3
+ "title": "Model routing",
4
+ "description": "Assign a model to each kind of work — planning, code and images, review, execution — and check usage and balance. The model list is read from the providers you already configured in DSH.",
5
+ "detail": "docs/DETAIL.md"
6
+ },
7
+ "panel": {
8
+ "title": "Model routing",
9
+ "lead": "Pick a model for each of the five kinds of work, and check usage and balance.",
10
+ "workspaceLabel": "Workspace",
11
+ "workspaceDefault": "Default (all workspaces)",
12
+ "save": "Save",
13
+ "reset": "Restore defaults",
14
+ "saving": "Saving…",
15
+ "saved": "Saved",
16
+ "loading": "Loading…",
17
+ "dirty": "Unsaved changes",
18
+ "emptyCatalog": "No model provider is configured in DSH yet. Add one in Settings → Models, or fill it in by hand.",
19
+ "manualPlaceholder": "provider/model",
20
+ "manualAdd": "Add by hand",
21
+ "usageTitle": "Usage and balance",
22
+ "noRelayUsage": "No routed model used yet",
23
+ "localTitle": "This machine (deepseek), last 7 days",
24
+ "balanceNote": "Relay providers expose no balance API, so balances are typed in by hand; usage comes from the local call log.",
25
+ "routes": {
26
+ "planning": {
27
+ "label": "Planning and writing",
28
+ "hint": "Long arguments, documentation, editing prose."
29
+ },
30
+ "review": {
31
+ "label": "Review",
32
+ "hint": "Inspect drawings, interfaces and layouts, and name the problems."
33
+ },
34
+ "execute": {
35
+ "label": "Execution",
36
+ "hint": "The only role that edits files, runs scripts and verifies the result."
37
+ },
38
+ "code": {
39
+ "label": "Code",
40
+ "hint": "Scripts, configuration changes, chart-generating code."
41
+ },
42
+ "image": {
43
+ "label": "Images",
44
+ "hint": "Generate or edit images, covers and illustrations; no code."
45
+ }
46
+ }
47
+ }
48
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "meta": {
3
+ "title": "模型分工",
4
+ "description": "给规划、写代码、出图、看图审错、决策执行五类工作各指定一个模型,并查看用量与余额。模型列表从你在 DSH 里已配置的提供方自动读取。",
5
+ "detail": "docs/DETAIL.md"
6
+ },
7
+ "panel": {
8
+ "title": "模型分工",
9
+ "lead": "为五类任务分别指定模型,并查看各家用量与余额。",
10
+ "workspaceLabel": "工作区",
11
+ "workspaceDefault": "默认(所有工作区)",
12
+ "save": "保存",
13
+ "reset": "恢复默认",
14
+ "saving": "保存中…",
15
+ "saved": "已保存",
16
+ "loading": "加载中…",
17
+ "dirty": "有未保存修改",
18
+ "emptyCatalog": "还没在 DSH 里配置模型提供方。请在设置 → 模型里添加,或手动填写。",
19
+ "manualPlaceholder": "provider/model",
20
+ "manualAdd": "手动添加",
21
+ "usageTitle": "用量与余额",
22
+ "noRelayUsage": "尚未使用分身模型",
23
+ "localTitle": "本机(deepseek)最近 7 天",
24
+ "balanceNote": "中转站不提供余额接口,余额由你手填;用量来自本机记录的调用日志。",
25
+ "routes": {
26
+ "planning": {
27
+ "label": "规划与文案",
28
+ "hint": "长文论证、写说明稿、审改文字。"
29
+ },
30
+ "review": {
31
+ "label": "看图审错",
32
+ "hint": "检查图纸、界面和版面,指出问题。"
33
+ },
34
+ "execute": {
35
+ "label": "决策与执行",
36
+ "hint": "唯一能改文件、运行脚本并做最终验证。"
37
+ },
38
+ "code": {
39
+ "label": "写代码",
40
+ "hint": "写脚本、改配置、生成图表的代码。"
41
+ },
42
+ "image": {
43
+ "label": "出图",
44
+ "hint": "生成或改写图片、封面、插图;不写代码。"
45
+ }
46
+ }
47
+ }
48
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "dsh-model-routing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.1.0",
4
+ "description": "Assign a model to each kind of work — planning, code and images, review, and execution — and keep an eye on usage and balance.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "dsh",
9
+ "dsh-plugin",
10
+ "model",
11
+ "routing",
12
+ "llm",
13
+ "settings"
14
+ ],
15
+ "exports": {
16
+ ".": "./index.js",
17
+ "./client": "./client.js",
18
+ "./locale/*.json": "./locale/*.json",
19
+ "./icon": "./icon.svg"
20
+ },
21
+ "files": [
22
+ "index.js",
23
+ "client.js",
24
+ "cordis.patch.yml",
25
+ "locale/*.json",
26
+ "docs",
27
+ "icon.svg",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "dsh": {
32
+ "bundle": {
33
+ "patch": "./cordis.patch.yml"
34
+ },
35
+ "client": {
36
+ "platform": "web",
37
+ "immediately": true,
38
+ "inject": [
39
+ "@deepseek-ai/dsh-client-runtime",
40
+ "@deepseek-ai/dsh-client-ui-settings"
41
+ ]
42
+ }
43
+ },
44
+ "author": "downer-dr",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/downer-dr/dsh-model-routing.git"
48
+ },
49
+ "homepage": "https://github.com/downer-dr/dsh-model-routing#readme",
50
+ "bugs": {
51
+ "url": "https://github.com/downer-dr/dsh-model-routing/issues"
52
+ }
6
53
  }