dsh-model-routing 0.0.0-stage → 1.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/LICENSE +21 -0
- package/README.md +94 -2
- package/client.js +564 -0
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +60 -0
- package/docs/PUBLISH.md +75 -0
- package/icon.svg +6 -0
- package/index.js +566 -0
- package/locale/en.json +48 -0
- package/locale/zh.json +48 -0
- package/package.json +50 -3
package/index.js
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
// 模型分工 · Host 侧:配置、用量、模型目录(从 DSH 配置里读 provider/model)
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { createRequire } from 'node:module'
|
|
6
|
+
|
|
7
|
+
const req = createRequire(import.meta.url)
|
|
8
|
+
let defineTool
|
|
9
|
+
try {
|
|
10
|
+
const m = req('@deepseek-ai/dsh-tools')
|
|
11
|
+
if (typeof m.defineTool === 'function') defineTool = m.defineTool
|
|
12
|
+
} catch {
|
|
13
|
+
// 兼容未安装工具定义模块的环境
|
|
14
|
+
}
|
|
15
|
+
if (!defineTool) defineTool = (x) => x
|
|
16
|
+
|
|
17
|
+
export const inject = ['tools']
|
|
18
|
+
|
|
19
|
+
const CONFIG_PATH = path.join(os.homedir(), '.dsh', 'model-routing.json')
|
|
20
|
+
const LEDGER_PATH = path.join(os.homedir(), '.dsh', 'storages', 'cost-meter', 'ledger.json')
|
|
21
|
+
const USAGE_PATH = path.join(os.homedir(), '.dsh', 'model-routing-usage.json')
|
|
22
|
+
const PROFILES_ROOT = path.join(os.homedir(), '.dsh', 'profiles')
|
|
23
|
+
|
|
24
|
+
const ROUTE_KEYS = ['planning', 'code', 'image', 'review', 'execute']
|
|
25
|
+
|
|
26
|
+
const ROUTE_LABELS = {
|
|
27
|
+
planning: '规划与文案',
|
|
28
|
+
code: '写代码',
|
|
29
|
+
image: '出图',
|
|
30
|
+
review: '看图审错',
|
|
31
|
+
execute: '决策与执行',
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// 旧版把「代码」和「出图」合成一类,读配置时展开,升级不掉值
|
|
35
|
+
const LEGACY_ROUTES = { code_image: ['code', 'image'] }
|
|
36
|
+
|
|
37
|
+
const DEFAULT_ROUTING = {
|
|
38
|
+
planning: { provider: '', model: '' },
|
|
39
|
+
code: { provider: '', model: '' },
|
|
40
|
+
image: { provider: '', model: '' },
|
|
41
|
+
review: { provider: '', model: '' },
|
|
42
|
+
execute: { provider: '', model: '' },
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function readJson(file, fallback) {
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
48
|
+
} catch {
|
|
49
|
+
return fallback
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/* ---------- 模型目录:从 profile 的 cordis.patch.yml 里解析 llm-pi-ai 的 providers ---------- */
|
|
54
|
+
|
|
55
|
+
// 内置提供方(不写在 patch 的 llm-pi-ai 里)从 allowedModels 里认出来
|
|
56
|
+
function parseAllowedModels(text) {
|
|
57
|
+
const pairs = []
|
|
58
|
+
const lines = text.split(/\r?\n/)
|
|
59
|
+
let provider = ''
|
|
60
|
+
for (const line of lines) {
|
|
61
|
+
const pm = line.match(/^\s*-\s*provider:\s*['"]?([A-Za-z0-9_.-]+)['"]?\s*$/)
|
|
62
|
+
if (pm) {
|
|
63
|
+
provider = pm[1]
|
|
64
|
+
continue
|
|
65
|
+
}
|
|
66
|
+
const mm = line.match(/^\s*model:\s*['"]?([A-Za-z0-9_.-]+)['"]?\s*$/)
|
|
67
|
+
if (mm && provider) {
|
|
68
|
+
pairs.push({ provider, model: mm[1] })
|
|
69
|
+
provider = '' // 一个 provider 只跟一个 model,避免把后面的 model 误挂过来
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
// 遇到其它顶层插件或非列表配置,清空待配对的 provider
|
|
73
|
+
if (/^- id:/.test(line)) provider = ''
|
|
74
|
+
}
|
|
75
|
+
return pairs
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function mergeAllowedModels(providers, allowed) {
|
|
79
|
+
const byId = new Map(providers.map((p) => [p.id, p]))
|
|
80
|
+
for (const { provider, model } of allowed) {
|
|
81
|
+
if (!byId.has(provider)) {
|
|
82
|
+
const created = { id: provider, displayName: provider, models: [] }
|
|
83
|
+
byId.set(provider, created)
|
|
84
|
+
providers.push(created)
|
|
85
|
+
}
|
|
86
|
+
const entry = byId.get(provider)
|
|
87
|
+
if (!entry.models.includes(model)) entry.models.push(model)
|
|
88
|
+
}
|
|
89
|
+
return providers
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
function listPatchFiles() {
|
|
94
|
+
const out = []
|
|
95
|
+
try {
|
|
96
|
+
for (const entry of fs.readdirSync(PROFILES_ROOT, { withFileTypes: true })) {
|
|
97
|
+
if (!entry.isDirectory()) continue
|
|
98
|
+
const file = path.join(PROFILES_ROOT, entry.name, 'cordis.patch.yml')
|
|
99
|
+
try {
|
|
100
|
+
const stat = fs.statSync(file)
|
|
101
|
+
out.push({ file, mtime: stat.mtimeMs, profile: entry.name })
|
|
102
|
+
} catch {
|
|
103
|
+
// 该 profile 没有 patch,跳过
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
} catch {
|
|
107
|
+
// profiles 根目录不存在
|
|
108
|
+
}
|
|
109
|
+
return out.sort((a, b) => b.mtime - a.mtime)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// 极简 YAML 片段解析:认 providers 下的两种写法
|
|
113
|
+
// 写法 A(DSH 自己的 patch 用这种):
|
|
114
|
+
// providers:
|
|
115
|
+
// uuapi-gpt:
|
|
116
|
+
// displayName: UUAPI GPT
|
|
117
|
+
// models:
|
|
118
|
+
// - id: gpt-6.2-sol
|
|
119
|
+
// 写法 B(有些版本 / 手写配置用这种):
|
|
120
|
+
// providers:
|
|
121
|
+
// - id: uuapi-gpt
|
|
122
|
+
// displayName: UUAPI GPT
|
|
123
|
+
// models:
|
|
124
|
+
// - gpt-6.2-sol
|
|
125
|
+
// 缩进不写死:以 providers: 之后第一行的缩进为准。
|
|
126
|
+
function parseProvidersFromPatch(text) {
|
|
127
|
+
const lines = text.split(/\r?\n/)
|
|
128
|
+
const providers = []
|
|
129
|
+
const indentOf = (line) => line.match(/^ */)[0].length
|
|
130
|
+
|
|
131
|
+
let i = 0
|
|
132
|
+
while (i < lines.length) {
|
|
133
|
+
if (!/^\s*providers:\s*$/.test(lines[i])) {
|
|
134
|
+
i++
|
|
135
|
+
continue
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const providersIndent = indentOf(lines[i])
|
|
139
|
+
let childIndent = -1
|
|
140
|
+
let current = null
|
|
141
|
+
let inModels = false
|
|
142
|
+
let modelIndent = -1
|
|
143
|
+
i++
|
|
144
|
+
|
|
145
|
+
for (; i < lines.length; i++) {
|
|
146
|
+
const raw = lines[i]
|
|
147
|
+
if (!raw.trim() || raw.trim().startsWith('#')) continue
|
|
148
|
+
const indent = indentOf(raw)
|
|
149
|
+
|
|
150
|
+
if (indent <= providersIndent) break
|
|
151
|
+
if (childIndent < 0) childIndent = indent
|
|
152
|
+
if (indent < childIndent) break
|
|
153
|
+
|
|
154
|
+
const listForm = raw.match(/^\s*-\s*id:\s*['"]?([A-Za-z0-9_.-]+)['"]?\s*$/)
|
|
155
|
+
const mapForm = indent === childIndent ? raw.match(/^\s*([A-Za-z0-9_.-]+):\s*$/) : null
|
|
156
|
+
if (listForm || mapForm) {
|
|
157
|
+
const id = (listForm ? listForm[1] : mapForm[1]).trim()
|
|
158
|
+
if (!providers.some((x) => x.id === id)) {
|
|
159
|
+
current = { id, displayName: id, models: [] }
|
|
160
|
+
providers.push(current)
|
|
161
|
+
} else {
|
|
162
|
+
current = providers.find((x) => x.id === id)
|
|
163
|
+
}
|
|
164
|
+
inModels = false
|
|
165
|
+
continue
|
|
166
|
+
}
|
|
167
|
+
if (!current) continue
|
|
168
|
+
|
|
169
|
+
const nameMatch = raw.match(/^\s*displayName:\s*(.+?)\s*$/)
|
|
170
|
+
if (nameMatch) {
|
|
171
|
+
current.displayName = nameMatch[1].replace(/^['"]|['"]$/g, '')
|
|
172
|
+
continue
|
|
173
|
+
}
|
|
174
|
+
if (/^\s*models:\s*$/.test(raw)) {
|
|
175
|
+
inModels = true
|
|
176
|
+
modelIndent = indent
|
|
177
|
+
continue
|
|
178
|
+
}
|
|
179
|
+
if (inModels) {
|
|
180
|
+
if (indent <= modelIndent) {
|
|
181
|
+
inModels = false
|
|
182
|
+
continue
|
|
183
|
+
}
|
|
184
|
+
const idForm = raw.match(/^\s*-\s*id:\s*['"]?([A-Za-z0-9_.:/ -]+?)['"]?\s*$/)
|
|
185
|
+
const plainForm = raw.match(/^\s*-\s*['"]?([A-Za-z0-9_.:/ -]+?)['"]?\s*$/)
|
|
186
|
+
const hit = idForm || plainForm
|
|
187
|
+
if (hit) {
|
|
188
|
+
const model = hit[1].trim()
|
|
189
|
+
if (model && !current.models.includes(model)) current.models.push(model)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return providers.filter((p) => p.models.length > 0)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function readCatalog() {
|
|
199
|
+
const files = listPatchFiles()
|
|
200
|
+
const tried = []
|
|
201
|
+
for (const item of files) {
|
|
202
|
+
let text = ''
|
|
203
|
+
try {
|
|
204
|
+
text = fs.readFileSync(item.file, 'utf8')
|
|
205
|
+
} catch (err) {
|
|
206
|
+
tried.push({ file: item.file, ok: false, why: String(err && err.message) })
|
|
207
|
+
continue
|
|
208
|
+
}
|
|
209
|
+
if (!text.includes('llm-pi-ai') && !text.includes('allowedModels') && !text.includes('providers:')) {
|
|
210
|
+
tried.push({ file: item.file, ok: false, why: '没有 providers / allowedModels' })
|
|
211
|
+
continue
|
|
212
|
+
}
|
|
213
|
+
const providers = parseProvidersFromPatch(text)
|
|
214
|
+
const allowed = parseAllowedModels(text)
|
|
215
|
+
const merged = mergeAllowedModels(providers, allowed)
|
|
216
|
+
tried.push({ file: item.file, ok: merged.length > 0, why: '' })
|
|
217
|
+
if (merged.length > 0) {
|
|
218
|
+
return { profile: item.profile, source: item.file, providers: merged, tried }
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { profile: '', source: '', providers: [], tried }
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/* ---------- 配置 ---------- */
|
|
225
|
+
|
|
226
|
+
function normalizeRouting(raw) {
|
|
227
|
+
const routing = {}
|
|
228
|
+
for (const key of ROUTE_KEYS) {
|
|
229
|
+
const row = raw && raw[key]
|
|
230
|
+
routing[key] =
|
|
231
|
+
row && typeof row.provider === 'string' && typeof row.model === 'string'
|
|
232
|
+
? { provider: row.provider, model: row.model }
|
|
233
|
+
: { ...DEFAULT_ROUTING[key] }
|
|
234
|
+
}
|
|
235
|
+
return routing
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function readConfig() {
|
|
239
|
+
const raw = readJson(CONFIG_PATH, null) || {}
|
|
240
|
+
const isV2 = raw && raw.version === 2
|
|
241
|
+
const defaultEntry = isV2 ? raw.default || {} : raw
|
|
242
|
+
const balances = (isV2 ? defaultEntry.balances : raw.balances) || {}
|
|
243
|
+
const workspaces = {}
|
|
244
|
+
if (isV2 && raw.workspaces && typeof raw.workspaces === 'object') {
|
|
245
|
+
for (const [key, entry] of Object.entries(raw.workspaces)) {
|
|
246
|
+
workspaces[key] = normalizeRouting(entry)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return { routing: normalizeRouting(defaultEntry), balances, workspaces }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function writeConfig(payload) {
|
|
253
|
+
fs.mkdirSync(path.dirname(CONFIG_PATH), { recursive: true })
|
|
254
|
+
fs.writeFileSync(CONFIG_PATH, JSON.stringify(payload, null, 2) + '\n', 'utf8')
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/* ---------- 系统提示与工具 ---------- */
|
|
258
|
+
|
|
259
|
+
// 两个 agent 接口共用默认路由,工具参数只接收任务类型。
|
|
260
|
+
function readCurrentRouting() {
|
|
261
|
+
return readConfig().routing
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function isConfigured(row) {
|
|
265
|
+
return Boolean(row && row.provider.trim() && row.model.trim())
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function toPromptLine(value) {
|
|
269
|
+
return value.replace(/[\r\n\v\f\u0085\u2028\u2029]+/g, ' ').trim()
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function clipPromptValue(value, limit) {
|
|
273
|
+
return value.length > limit ? `${value.slice(0, limit - 1)}…` : value
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function buildRoutingPrompt() {
|
|
277
|
+
const routing = readCurrentRouting()
|
|
278
|
+
const keys = ROUTE_KEYS.filter((key) => isConfigured(routing[key]))
|
|
279
|
+
if (!keys.length) return ''
|
|
280
|
+
|
|
281
|
+
const header = '【模型分工】按任务选模型,不要一律用默认模型:'
|
|
282
|
+
const footer = '用 subagent 时把 provider/model 传进去;当前任务不属于这五类就用默认模型。'
|
|
283
|
+
const rows = keys.map((key) => ({
|
|
284
|
+
prefix: `- ${ROUTE_LABELS[key]} → `,
|
|
285
|
+
provider: toPromptLine(routing[key].provider),
|
|
286
|
+
model: toPromptLine(routing[key].model),
|
|
287
|
+
}))
|
|
288
|
+
const lines = rows.map(({ prefix, provider, model }) => `${prefix}${provider}/${model}`)
|
|
289
|
+
const fullText = [header, ...lines, footer].join('\n')
|
|
290
|
+
if (fullText.length <= 1000) return fullText
|
|
291
|
+
|
|
292
|
+
const shortFooter = `${footer}带省略号的条目用 routing_for 查询完整值。`
|
|
293
|
+
const fixedLength = header.length + shortFooter.length + rows.length + 1
|
|
294
|
+
const lineLimit = Math.floor((1000 - fixedLength) / rows.length)
|
|
295
|
+
const shortLines = rows.map(({ prefix, provider, model }) => {
|
|
296
|
+
const budget = lineLimit - prefix.length - 1
|
|
297
|
+
const providerLimit = Math.min(provider.length, Math.max(Math.floor(budget / 2), budget - model.length))
|
|
298
|
+
const modelLimit = budget - providerLimit
|
|
299
|
+
return `${prefix}${clipPromptValue(provider, providerLimit)}/${clipPromptValue(model, modelLimit)}`
|
|
300
|
+
})
|
|
301
|
+
return [header, ...shortLines, shortFooter].join('\n')
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function routingResult(routing, task) {
|
|
305
|
+
if (!ROUTE_KEYS.includes(task)) return { ok: 0, error: 'unknown_task', task: task.slice(0, 120) }
|
|
306
|
+
const row = routing[task]
|
|
307
|
+
if (!isConfigured(row)) return { ok: 0, error: 'not_configured', task }
|
|
308
|
+
return { ok: 1, task, provider: row.provider, model: row.model }
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function routingToolText(args) {
|
|
312
|
+
const task = typeof args?.task === 'string' ? args.task : ''
|
|
313
|
+
const routing = readCurrentRouting()
|
|
314
|
+
// 每类占一个数组项,整个列表仍序列化成单行 JSON。
|
|
315
|
+
const result = task === 'list'
|
|
316
|
+
? { ok: 1, task, routes: ROUTE_KEYS.map((key) => routingResult(routing, key)) }
|
|
317
|
+
: routingResult(routing, task)
|
|
318
|
+
return JSON.stringify(result).replace(/[\u0085\u2028\u2029]/g, (char) => {
|
|
319
|
+
return `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`
|
|
320
|
+
})
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/* ---------- 用量 ---------- */
|
|
324
|
+
|
|
325
|
+
function readCalls() {
|
|
326
|
+
const data = readJson(USAGE_PATH, { calls: [] })
|
|
327
|
+
const list = Array.isArray(data && data.calls) ? data.calls : []
|
|
328
|
+
const byProvider = {}
|
|
329
|
+
let total = { input: 0, output: 0, calls: 0 }
|
|
330
|
+
for (const c of list) {
|
|
331
|
+
const key = String(c.provider || 'unknown')
|
|
332
|
+
if (!byProvider[key]) byProvider[key] = { input: 0, output: 0, calls: 0, models: {} }
|
|
333
|
+
const inTok = Number(c.input) || 0
|
|
334
|
+
const outTok = Number(c.output) || 0
|
|
335
|
+
byProvider[key].input += inTok
|
|
336
|
+
byProvider[key].output += outTok
|
|
337
|
+
byProvider[key].calls += 1
|
|
338
|
+
const model = String(c.model || 'unknown')
|
|
339
|
+
byProvider[key].models[model] = (byProvider[key].models[model] || 0) + inTok + outTok
|
|
340
|
+
total = { input: total.input + inTok, output: total.output + outTok, calls: total.calls + 1 }
|
|
341
|
+
}
|
|
342
|
+
return { byProvider, total, recent: list.slice(-12).reverse() }
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function localUsage() {
|
|
346
|
+
const ledger = readJson(LEDGER_PATH, null)
|
|
347
|
+
if (!ledger || typeof ledger !== 'object') return { days: [], total: { input: 0, output: 0 } }
|
|
348
|
+
const days = ledger.days && typeof ledger.days === 'object' ? ledger.days : {}
|
|
349
|
+
const rows = Object.keys(days)
|
|
350
|
+
.sort()
|
|
351
|
+
.slice(-7)
|
|
352
|
+
.map((k) => {
|
|
353
|
+
const d = days[k] || {}
|
|
354
|
+
return { date: k, input: Number(d.input) || 0, output: Number(d.output) || 0 }
|
|
355
|
+
})
|
|
356
|
+
const total = rows.reduce(
|
|
357
|
+
(a, r) => ({ input: a.input + r.input, output: a.output + r.output }),
|
|
358
|
+
{ input: 0, output: 0 },
|
|
359
|
+
)
|
|
360
|
+
return { days: rows, total }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/* ---------- HTTP ---------- */
|
|
364
|
+
|
|
365
|
+
async function readBody(req) {
|
|
366
|
+
const chunks = []
|
|
367
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
368
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
369
|
+
if (!text) return null
|
|
370
|
+
try {
|
|
371
|
+
return JSON.parse(text)
|
|
372
|
+
} catch {
|
|
373
|
+
return null
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function sendJson(res, status, payload) {
|
|
378
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
379
|
+
res.end(JSON.stringify(payload))
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export function apply(ctx, config = {}) {
|
|
383
|
+
const base = typeof config.basePath === 'string' && config.basePath ? config.basePath : '/dsh-model-routing'
|
|
384
|
+
let refreshPrompt
|
|
385
|
+
|
|
386
|
+
if (config.injectPrompt !== false) {
|
|
387
|
+
ctx.inject(['systemPrompt'], (promptCtx) => {
|
|
388
|
+
const systemPrompt = promptCtx.systemPrompt
|
|
389
|
+
if (!systemPrompt) return
|
|
390
|
+
|
|
391
|
+
let disposeSection
|
|
392
|
+
const syncSection = () => {
|
|
393
|
+
const routing = readCurrentRouting()
|
|
394
|
+
const hasRoutes = ROUTE_KEYS.some((key) => isConfigured(routing[key]))
|
|
395
|
+
|
|
396
|
+
if (hasRoutes && !disposeSection) {
|
|
397
|
+
disposeSection = systemPrompt.section({
|
|
398
|
+
name: 'dsh-model-routing',
|
|
399
|
+
order: 60,
|
|
400
|
+
text: buildRoutingPrompt,
|
|
401
|
+
})
|
|
402
|
+
} else if (!hasRoutes && disposeSection) {
|
|
403
|
+
disposeSection()
|
|
404
|
+
disposeSection = undefined
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// 保存后立即同步注册状态,也检测插件外部对配置文件的修改。
|
|
409
|
+
syncSection()
|
|
410
|
+
fs.watchFile(CONFIG_PATH, { persistent: false, interval: 250 }, syncSection)
|
|
411
|
+
refreshPrompt = syncSection
|
|
412
|
+
|
|
413
|
+
return () => {
|
|
414
|
+
refreshPrompt = undefined
|
|
415
|
+
fs.unwatchFile(CONFIG_PATH, syncSection)
|
|
416
|
+
if (disposeSection) disposeSection()
|
|
417
|
+
}
|
|
418
|
+
})
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
ctx.inject(['tools'], (toolsCtx) => {
|
|
422
|
+
if (!toolsCtx.tools) return
|
|
423
|
+
|
|
424
|
+
const dispose = toolsCtx.tools.register(defineTool({
|
|
425
|
+
name: 'routing_for',
|
|
426
|
+
description: '任务确实需要交给别的模型时(如写代码、出图、审图),先查该任务的路由,再把返回的 provider/model 传给 subagent。小事直接处理,避免过度分工。',
|
|
427
|
+
parameters: {
|
|
428
|
+
task: { type: 'string', description: '任务类型:planning | code | image | review | execute | list。list 查询全部五类。' },
|
|
429
|
+
},
|
|
430
|
+
output: {
|
|
431
|
+
schema: {
|
|
432
|
+
type: 'object',
|
|
433
|
+
additionalProperties: false,
|
|
434
|
+
properties: { text: { type: 'string', required: true } },
|
|
435
|
+
},
|
|
436
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
437
|
+
},
|
|
438
|
+
async execute(args) {
|
|
439
|
+
return { text: routingToolText(args) }
|
|
440
|
+
},
|
|
441
|
+
}))
|
|
442
|
+
|
|
443
|
+
if (typeof dispose === 'function') return dispose
|
|
444
|
+
})
|
|
445
|
+
|
|
446
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
447
|
+
const disposers = []
|
|
448
|
+
|
|
449
|
+
disposers.push(
|
|
450
|
+
webCtx.webServer.register({
|
|
451
|
+
kind: 'exact',
|
|
452
|
+
path: `${base}/catalog`,
|
|
453
|
+
handler: async (req, res) => {
|
|
454
|
+
if (req.method !== 'GET') return sendJson(res, 405, { error: 'method not allowed' })
|
|
455
|
+
try {
|
|
456
|
+
const catalog = readCatalog()
|
|
457
|
+
return sendJson(res, 200, catalog)
|
|
458
|
+
} catch (err) {
|
|
459
|
+
return sendJson(res, 500, { error: String(err && err.message ? err.message : err) })
|
|
460
|
+
}
|
|
461
|
+
},
|
|
462
|
+
}),
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
disposers.push(
|
|
466
|
+
webCtx.webServer.register({
|
|
467
|
+
kind: 'exact',
|
|
468
|
+
path: `${base}/state`,
|
|
469
|
+
handler: async (req, res) => {
|
|
470
|
+
if (req.method !== 'GET') return sendJson(res, 405, { error: 'method not allowed' })
|
|
471
|
+
try {
|
|
472
|
+
const url = new URL(req.url || '/', 'http://localhost')
|
|
473
|
+
const workspace = url.searchParams.get('workspace') || ''
|
|
474
|
+
const { routing, balances, workspaces } = readConfig()
|
|
475
|
+
const entry = workspace && workspaces[workspace] ? workspaces[workspace] : routing
|
|
476
|
+
const effectiveBalances = workspace && workspaces[workspace] ? (readJson(CONFIG_PATH, {}) || {}).workspaces?.[workspace]?.balances || {} : balances
|
|
477
|
+
return sendJson(res, 200, {
|
|
478
|
+
workspace,
|
|
479
|
+
useDefault: !(workspace && workspaces[workspace]),
|
|
480
|
+
routing: entry,
|
|
481
|
+
defaults: DEFAULT_ROUTING,
|
|
482
|
+
balances: effectiveBalances,
|
|
483
|
+
savedWorkspaces: Object.keys(workspaces),
|
|
484
|
+
catalog: readCatalog(),
|
|
485
|
+
relay: readCalls(),
|
|
486
|
+
local: localUsage(),
|
|
487
|
+
configPath: CONFIG_PATH,
|
|
488
|
+
usagePath: USAGE_PATH,
|
|
489
|
+
})
|
|
490
|
+
} catch (err) {
|
|
491
|
+
return sendJson(res, 500, { error: String(err && err.message ? err.message : err) })
|
|
492
|
+
}
|
|
493
|
+
},
|
|
494
|
+
}),
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
disposers.push(
|
|
498
|
+
webCtx.webServer.register({
|
|
499
|
+
kind: 'exact',
|
|
500
|
+
path: `${base}/routing`,
|
|
501
|
+
handler: async (req, res) => {
|
|
502
|
+
if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' })
|
|
503
|
+
try {
|
|
504
|
+
const body = await readBody(req)
|
|
505
|
+
if (!body || typeof body !== 'object') return sendJson(res, 400, { error: 'invalid body' })
|
|
506
|
+
const raw = readJson(CONFIG_PATH, {}) || {}
|
|
507
|
+
const isV2 = raw && raw.version === 2
|
|
508
|
+
const routing = {}
|
|
509
|
+
for (const key of ROUTE_KEYS) {
|
|
510
|
+
const row = body.routing && body.routing[key]
|
|
511
|
+
if (!row || typeof row.provider !== 'string' || typeof row.model !== 'string') {
|
|
512
|
+
return sendJson(res, 400, { error: `missing route: ${key}` })
|
|
513
|
+
}
|
|
514
|
+
routing[key] = { provider: row.provider.slice(0, 120), model: row.model.slice(0, 120) }
|
|
515
|
+
}
|
|
516
|
+
const balances = {}
|
|
517
|
+
if (body.balances && typeof body.balances === 'object') {
|
|
518
|
+
for (const [k, v] of Object.entries(body.balances)) {
|
|
519
|
+
const num = Number(v)
|
|
520
|
+
if (Number.isFinite(num)) balances[k] = num
|
|
521
|
+
}
|
|
522
|
+
} else {
|
|
523
|
+
Object.assign(balances, (isV2 ? raw.default || {} : raw).balances || {})
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const workspace = typeof body.workspace === 'string' ? body.workspace.slice(0, 400) : ''
|
|
527
|
+
const next = isV2 ? raw : { version: 2, default: { ...normalizeRouting(raw), balances: raw.balances || {} }, workspaces: {} }
|
|
528
|
+
next.version = 2
|
|
529
|
+
next.workspaces = next.workspaces && typeof next.workspaces === 'object' ? next.workspaces : {}
|
|
530
|
+
if (!next.default) next.default = { ...DEFAULT_ROUTING, balances: {} }
|
|
531
|
+
|
|
532
|
+
if (workspace) {
|
|
533
|
+
next.workspaces[workspace] = { ...routing, balances }
|
|
534
|
+
} else {
|
|
535
|
+
next.default = { ...routing, balances }
|
|
536
|
+
}
|
|
537
|
+
writeConfig(next)
|
|
538
|
+
if (!workspace && refreshPrompt) {
|
|
539
|
+
try {
|
|
540
|
+
refreshPrompt()
|
|
541
|
+
} catch {
|
|
542
|
+
// 提示段同步失败时仍返回实际的保存结果
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return sendJson(res, 200, { ok: true, workspace, routing, balances })
|
|
546
|
+
} catch (err) {
|
|
547
|
+
return sendJson(res, 500, { error: String(err && err.message ? err.message : err) })
|
|
548
|
+
}
|
|
549
|
+
},
|
|
550
|
+
}),
|
|
551
|
+
)
|
|
552
|
+
|
|
553
|
+
return () => {
|
|
554
|
+
for (const dispose of disposers) {
|
|
555
|
+
try {
|
|
556
|
+
dispose()
|
|
557
|
+
} catch {
|
|
558
|
+
// 忽略卸载异常
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
})
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
export { readCatalog, parseProvidersFromPatch }
|
|
566
|
+
``
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Model routing",
|
|
4
|
+
"description": "Assign a model to five kinds of work. The routing is injected into the system prompt and queryable through the routing_for tool, so agents actually follow it.",
|
|
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": "给五类工作各指定一个模型;这份分工会写进系统提示,并可用 routing_for 工具查询,让 agent 真的照着派活。",
|
|
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
|
+
}
|