dsh-agent-router 1.9.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.en.md +304 -0
- package/README.md +304 -0
- package/client.js +3061 -0
- package/cordis.patch.yml +20 -0
- package/docs/ARCHITECTURE_DIAGNOSIS_AND_PLAN.md +414 -0
- package/docs/DETAIL.ja.md +1 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/IMPLEMENTATION_PLAN.md +99 -0
- package/docs/ITERATION_PLAN_2026-11.md +377 -0
- package/docs/RELEASE.md +133 -0
- package/docs/RELEASE_CHECKLIST.md +88 -0
- package/docs/preview.svg +69 -0
- package/docs/preview.zh.svg +63 -0
- package/icon.svg +16 -0
- package/index.js +24 -0
- package/lib/classifier.js +405 -0
- package/lib/cli/discover.js +187 -0
- package/lib/cli/invoke.js +294 -0
- package/lib/cli/parsers.js +234 -0
- package/lib/cli/shared.js +145 -0
- package/lib/cli-runners.js +39 -0
- package/lib/config-limits.js +67 -0
- package/lib/config-normalize.js +147 -0
- package/lib/config-presets.js +89 -0
- package/lib/config-schema.js +347 -0
- package/lib/defaults.js +117 -0
- package/lib/diagnose-fallback.js +96 -0
- package/lib/error-classify.js +160 -0
- package/lib/eval-routing.js +96 -0
- package/lib/guardrails.js +70 -0
- package/lib/integrations.js +173 -0
- package/lib/job-runner.js +287 -0
- package/lib/ledger.js +360 -0
- package/lib/legacy-config.js +34 -0
- package/lib/model-capabilities.js +135 -0
- package/lib/model-score.js +65 -0
- package/lib/plugin.js +184 -0
- package/lib/profile-mount.js +524 -0
- package/lib/route-edit.js +82 -0
- package/lib/router/candidates.js +194 -0
- package/lib/router/catalog.js +121 -0
- package/lib/router/cli-select.js +84 -0
- package/lib/router/config-manager.js +122 -0
- package/lib/router/doctor.js +159 -0
- package/lib/router/local-models.js +126 -0
- package/lib/router/policy.js +61 -0
- package/lib/router/rpc.js +263 -0
- package/lib/router/system-prompt.js +29 -0
- package/lib/router/tools.js +1028 -0
- package/lib/router/util.js +99 -0
- package/lib/rpc-contract.js +46 -0
- package/lib/sessions.js +59 -0
- package/lib/task-queue.js +201 -0
- package/lib/tier-presets.js +595 -0
- package/lib/typert.host.js +79 -0
- package/lib/update-check.js +205 -0
- package/lib/worktree-lock.js +86 -0
- package/lib/worktree.js +268 -0
- package/locale/en.json +7 -0
- package/locale/ja.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +136 -0
- package/scripts/profile-maintenance.mjs +287 -0
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configurable difficulty tier metadata, layout presets, normalization, and
|
|
3
|
+
* helper lookups shared by the Host and the browser UI.
|
|
4
|
+
*
|
|
5
|
+
* Zero imports by design so `scripts/build-client.mjs` can inline this module
|
|
6
|
+
* verbatim into the committed `client.js` artifact.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-agent-router/lib/tier-presets
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export const TIER_ID_RE = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/
|
|
12
|
+
export const MAX_TIERS = 10
|
|
13
|
+
export const MAX_TIER_NAME = 40
|
|
14
|
+
export const DEFAULT_TIER_LAYOUT = 'default'
|
|
15
|
+
export const TIER_ROLES = Object.freeze(['normal', 'review'])
|
|
16
|
+
export const PREFER_BACKENDS = Object.freeze(['auto', 'dsh', 'cli', 'claude', 'codex', 'gemini', 'opencode', 'antigravity'])
|
|
17
|
+
export const TIER_CLI_BACKENDS = Object.freeze(['claude', 'codex', 'gemini', 'opencode', 'antigravity'])
|
|
18
|
+
|
|
19
|
+
const BAND_SCORE_KEY = Object.freeze({ light: 'T1', standard: 'T2', heavy: 'T3', review: 'T4' })
|
|
20
|
+
|
|
21
|
+
function round(value, digits = 2) {
|
|
22
|
+
const factor = 10 ** digits
|
|
23
|
+
return Math.round(value * factor) / factor
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function clone(value) {
|
|
27
|
+
if (Array.isArray(value)) return value.map(clone)
|
|
28
|
+
if (value && typeof value === 'object') {
|
|
29
|
+
const out = {}
|
|
30
|
+
for (const [k, v] of Object.entries(value)) out[k] = clone(v)
|
|
31
|
+
return out
|
|
32
|
+
}
|
|
33
|
+
return value
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function cleanText(value, limit = Infinity) {
|
|
37
|
+
if (typeof value !== 'string') return ''
|
|
38
|
+
const text = value.trim()
|
|
39
|
+
return text.length > limit ? text.slice(0, limit) : text
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Default four-tier skeleton. Route chains are attached by `lib/defaults.js`. */
|
|
43
|
+
export const DEFAULT_TIER_SKELETON = Object.freeze([
|
|
44
|
+
Object.freeze({
|
|
45
|
+
id: 'T1',
|
|
46
|
+
name: '轻量检索',
|
|
47
|
+
description: '搜索、总结、格式转换等小任务',
|
|
48
|
+
role: 'normal',
|
|
49
|
+
minScore: 0,
|
|
50
|
+
maxScore: 1.5,
|
|
51
|
+
}),
|
|
52
|
+
Object.freeze({
|
|
53
|
+
id: 'T2',
|
|
54
|
+
name: '标准开发',
|
|
55
|
+
description: '常规编码、单元测试、普通修复',
|
|
56
|
+
role: 'normal',
|
|
57
|
+
minScore: 1.5,
|
|
58
|
+
maxScore: 3,
|
|
59
|
+
}),
|
|
60
|
+
Object.freeze({
|
|
61
|
+
id: 'T3',
|
|
62
|
+
name: '复杂攻坚',
|
|
63
|
+
description: '架构设计、跨模块重构、疑难排错',
|
|
64
|
+
role: 'normal',
|
|
65
|
+
minScore: 3,
|
|
66
|
+
maxScore: null,
|
|
67
|
+
}),
|
|
68
|
+
Object.freeze({
|
|
69
|
+
id: 'T4',
|
|
70
|
+
name: '审查验收',
|
|
71
|
+
description: '代码审查、安全审计、交叉验证',
|
|
72
|
+
role: 'review',
|
|
73
|
+
minScore: null,
|
|
74
|
+
maxScore: null,
|
|
75
|
+
}),
|
|
76
|
+
])
|
|
77
|
+
|
|
78
|
+
/** Ready-made tier layouts offered to non-technical users. */
|
|
79
|
+
export const TIER_LAYOUT_PRESETS = Object.freeze({
|
|
80
|
+
default: Object.freeze({
|
|
81
|
+
label: '默认四档',
|
|
82
|
+
description: '轻量 / 标准 / 复杂 / 审查',
|
|
83
|
+
tiers: Object.freeze(DEFAULT_TIER_SKELETON.map(entry => ({ ...entry }))),
|
|
84
|
+
}),
|
|
85
|
+
compact: Object.freeze({
|
|
86
|
+
label: '精简三档',
|
|
87
|
+
description: '轻量 / 标准 / 审查',
|
|
88
|
+
tiers: Object.freeze([
|
|
89
|
+
{ id: 'T1', name: '快速处理', description: '搜索、总结、格式转换等小任务', role: 'normal', minScore: 0, maxScore: 2 },
|
|
90
|
+
{ id: 'T2', name: '标准开发', description: '常规编码、单测、普通修复与较复杂任务', role: 'normal', minScore: 2, maxScore: null },
|
|
91
|
+
{ id: 'T4', name: '审查验收', description: '代码审查、安全审计、交叉验证', role: 'review', minScore: null, maxScore: null },
|
|
92
|
+
]),
|
|
93
|
+
}),
|
|
94
|
+
fast: Object.freeze({
|
|
95
|
+
label: '极速两档',
|
|
96
|
+
description: '快速 / 深度(审查任务走最高档)',
|
|
97
|
+
tiers: Object.freeze([
|
|
98
|
+
{ id: 'T1', name: '快速处理', description: '日常小任务,优先低成本快速模型', role: 'normal', minScore: 0, maxScore: 2.5 },
|
|
99
|
+
{ id: 'T3', name: '深度攻坚', description: '复杂实现、架构设计、疑难排错', role: 'normal', minScore: 2.5, maxScore: null },
|
|
100
|
+
]),
|
|
101
|
+
}),
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
const SKELETON_BY_ID = Object.freeze(Object.fromEntries(DEFAULT_TIER_SKELETON.map(entry => [entry.id, entry])))
|
|
105
|
+
|
|
106
|
+
function coerceScore(value, fallback = null) {
|
|
107
|
+
if (value === null || value === undefined || value === '') return fallback
|
|
108
|
+
const n = Number(value)
|
|
109
|
+
if (!Number.isFinite(n) || n < 0) return fallback
|
|
110
|
+
return round(n)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function coerceMaxScore(value, minScore, fallback = null) {
|
|
114
|
+
// `undefined`/`''` mean "not provided" (v1 tier maps, partial overrides) and
|
|
115
|
+
// fall back to the inherited bound. `null` is an explicit "no upper limit"
|
|
116
|
+
// and must not be replaced by the inherited bound.
|
|
117
|
+
if (value === undefined || value === '') return fallback
|
|
118
|
+
if (value === null) return null
|
|
119
|
+
const n = Number(value)
|
|
120
|
+
if (!Number.isFinite(n) || n <= minScore) return fallback
|
|
121
|
+
return round(n)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Filter and normalize a DSH route array. Invalid entries are dropped.
|
|
126
|
+
* @param {unknown} list
|
|
127
|
+
* @param {Array<Record<string, any>>} [fallback]
|
|
128
|
+
*/
|
|
129
|
+
export function sanitizeDshRoutes(list, fallback = []) {
|
|
130
|
+
if (!Array.isArray(list)) return fallback.map(route => ({ ...route }))
|
|
131
|
+
const out = []
|
|
132
|
+
for (const item of list) {
|
|
133
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) continue
|
|
134
|
+
const provider = cleanText(item.provider)
|
|
135
|
+
const model = cleanText(item.model)
|
|
136
|
+
if (!provider || !model) continue
|
|
137
|
+
const route = { provider, model }
|
|
138
|
+
const effort = cleanText(item.reasoningEffort)
|
|
139
|
+
if (effort) route.reasoningEffort = effort
|
|
140
|
+
const note = cleanText(item.note)
|
|
141
|
+
if (note) route.note = note
|
|
142
|
+
out.push(route)
|
|
143
|
+
}
|
|
144
|
+
return out
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Filter and normalize a local CLI route array. Unknown backends are dropped.
|
|
149
|
+
* @param {unknown} list
|
|
150
|
+
* @param {Array<Record<string, any>>} [fallback]
|
|
151
|
+
*/
|
|
152
|
+
export function sanitizeCliRoutes(list, fallback = []) {
|
|
153
|
+
if (!Array.isArray(list)) return fallback.map(route => ({ ...route }))
|
|
154
|
+
const out = []
|
|
155
|
+
for (const item of list) {
|
|
156
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) continue
|
|
157
|
+
const backend = cleanText(item.backend)
|
|
158
|
+
if (!TIER_CLI_BACKENDS.includes(backend)) continue
|
|
159
|
+
const route = { backend }
|
|
160
|
+
const model = cleanText(item.model)
|
|
161
|
+
if (model) route.model = model
|
|
162
|
+
const effort = cleanText(item.effort)
|
|
163
|
+
if (effort) route.effort = effort
|
|
164
|
+
const note = cleanText(item.note)
|
|
165
|
+
if (note) route.note = note
|
|
166
|
+
out.push(route)
|
|
167
|
+
}
|
|
168
|
+
return out
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function entryName(entry, id) {
|
|
172
|
+
return cleanText(entry?.name, MAX_TIER_NAME) || cleanText(entry?.label, MAX_TIER_NAME) || id
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const KNOWN_TIER_KEYS = new Set([
|
|
176
|
+
'name', 'label', 'description', 'role', 'minScore', 'maxScore',
|
|
177
|
+
'preferBackend', 'escalateTo', 'dsh', 'cli',
|
|
178
|
+
])
|
|
179
|
+
const UNSAFE_OBJECT_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Keep forward-compatible fields that this build does not know about, so a
|
|
183
|
+
* newer config saved by a newer build is not silently downgraded. `label` is a
|
|
184
|
+
* v1 alias that is migrated into `name` and therefore not preserved.
|
|
185
|
+
* @param {unknown} raw
|
|
186
|
+
* @returns {Record<string, unknown>}
|
|
187
|
+
*/
|
|
188
|
+
function pickTierExtras(raw) {
|
|
189
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
|
|
190
|
+
const extras = {}
|
|
191
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
192
|
+
if (KNOWN_TIER_KEYS.has(key) || UNSAFE_OBJECT_KEYS.has(key)) continue
|
|
193
|
+
extras[key] = value
|
|
194
|
+
}
|
|
195
|
+
return extras
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function normalizeOne(id, raw, fallback, warnings) {
|
|
199
|
+
const base = (fallback && fallback[id]) || SKELETON_BY_ID[id] || {}
|
|
200
|
+
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
|
201
|
+
const extras = pickTierExtras(src)
|
|
202
|
+
const roleRaw = src.role === 'review' ? 'review' : (src.role === 'normal' ? 'normal' : base.role)
|
|
203
|
+
const role = roleRaw === 'review' ? 'review' : 'normal'
|
|
204
|
+
const name = entryName({ name: src.name ?? src.label ?? base.name }, id)
|
|
205
|
+
const description = cleanText(src.description ?? base.description, 160)
|
|
206
|
+
const minScore = role === 'review' ? null : coerceScore(src.minScore, coerceScore(base.minScore, 0))
|
|
207
|
+
const maxScore = role === 'review'
|
|
208
|
+
? null
|
|
209
|
+
: coerceMaxScore(src.maxScore, minScore, coerceMaxScore(base.maxScore, minScore, null))
|
|
210
|
+
const preferBackend = PREFER_BACKENDS.includes(src.preferBackend)
|
|
211
|
+
? src.preferBackend
|
|
212
|
+
: (PREFER_BACKENDS.includes(base.preferBackend) ? base.preferBackend : 'auto')
|
|
213
|
+
const dshRaw = src.dsh !== undefined ? src.dsh : base.dsh
|
|
214
|
+
const cliRaw = src.cli !== undefined ? src.cli : base.cli
|
|
215
|
+
const dsh = sanitizeDshRoutes(dshRaw, [])
|
|
216
|
+
const cli = sanitizeCliRoutes(cliRaw, [])
|
|
217
|
+
if (Array.isArray(dshRaw) && dsh.length < dshRaw.length) {
|
|
218
|
+
warnings.push(`档位「${name}」有 ${dshRaw.length - dsh.length} 条 DSH 路由缺少 provider/model,已忽略`)
|
|
219
|
+
}
|
|
220
|
+
if (Array.isArray(cliRaw) && cli.length < cliRaw.length) {
|
|
221
|
+
warnings.push(`档位「${name}」有 ${cliRaw.length - cli.length} 条 CLI 路由后端无效,已忽略`)
|
|
222
|
+
}
|
|
223
|
+
const escalateTo = src.escalateTo !== undefined ? src.escalateTo : base.escalateTo
|
|
224
|
+
return {
|
|
225
|
+
...extras,
|
|
226
|
+
name,
|
|
227
|
+
description,
|
|
228
|
+
role,
|
|
229
|
+
minScore,
|
|
230
|
+
maxScore,
|
|
231
|
+
preferBackend,
|
|
232
|
+
escalateTo: escalateTo === null ? null : (typeof escalateTo === 'string' ? escalateTo : undefined),
|
|
233
|
+
dsh,
|
|
234
|
+
cli,
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Sort tier entries by score: normal tiers ascending, review tiers last.
|
|
240
|
+
* @param {Record<string, any>} tiers
|
|
241
|
+
* @returns {Array<[string, any]>}
|
|
242
|
+
*/
|
|
243
|
+
export function sortTierEntries(tiers) {
|
|
244
|
+
const entries = Object.entries(tiers && typeof tiers === 'object' ? tiers : {})
|
|
245
|
+
.filter(([, entry]) => entry && typeof entry === 'object')
|
|
246
|
+
entries.sort((a, b) => {
|
|
247
|
+
const aReview = a[1].role === 'review'
|
|
248
|
+
const bReview = b[1].role === 'review'
|
|
249
|
+
if (aReview !== bReview) return aReview ? 1 : -1
|
|
250
|
+
if (aReview && bReview) return a[0].localeCompare(b[0])
|
|
251
|
+
const aMin = Number.isFinite(a[1].minScore) ? a[1].minScore : Number.POSITIVE_INFINITY
|
|
252
|
+
const bMin = Number.isFinite(b[1].minScore) ? b[1].minScore : Number.POSITIVE_INFINITY
|
|
253
|
+
if (aMin !== bMin) return aMin - bMin
|
|
254
|
+
return a[0].localeCompare(b[0])
|
|
255
|
+
})
|
|
256
|
+
return entries
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** @param {Record<string, any>} tiers */
|
|
260
|
+
export function sortedNormalTiers(tiers) {
|
|
261
|
+
return sortTierEntries(tiers).filter(([, entry]) => entry.role !== 'review')
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** @param {Record<string, any>} tiers */
|
|
265
|
+
export function tierCount(tiers) {
|
|
266
|
+
return Object.keys(tiers && typeof tiers === 'object' ? tiers : {}).length
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** @param {string} id @param {Record<string, any>} tiers */
|
|
270
|
+
export function isReviewTier(id, tiers) {
|
|
271
|
+
return tiers?.[id]?.role === 'review'
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Coarse capability band used by model scoring and CLI ordering.
|
|
276
|
+
* @param {string} id
|
|
277
|
+
* @param {Record<string, any>} tiers
|
|
278
|
+
* @returns {'light'|'standard'|'heavy'|'review'}
|
|
279
|
+
*/
|
|
280
|
+
export function tierBand(id, tiers) {
|
|
281
|
+
if (isReviewTier(id, tiers)) return 'review'
|
|
282
|
+
const normals = sortedNormalTiers(tiers)
|
|
283
|
+
const index = normals.findIndex(([tierId]) => tierId === id)
|
|
284
|
+
if (index < 0) return 'standard'
|
|
285
|
+
// A single normal tier is both the lowest and the highest tier; score the
|
|
286
|
+
// catch-all as balanced instead of arbitrarily picking the 'light' path.
|
|
287
|
+
if (normals.length === 1) return 'standard'
|
|
288
|
+
if (index === 0) return 'light'
|
|
289
|
+
if (index === normals.length - 1) return 'heavy'
|
|
290
|
+
return 'standard'
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Map an arbitrary tier id to the legacy T1-T4 key used by `model-score`.
|
|
295
|
+
* @param {string} id
|
|
296
|
+
* @param {Record<string, any>} tiers
|
|
297
|
+
*/
|
|
298
|
+
export function tierKeyForScoring(id, tiers) {
|
|
299
|
+
if (tiers && typeof tiers === 'object' && tiers[id]) return BAND_SCORE_KEY[tierBand(id, tiers)]
|
|
300
|
+
return BAND_SCORE_KEY[id] ? id : 'T2'
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Next normal tier by score order, or null at the top.
|
|
305
|
+
* @param {string} id
|
|
306
|
+
* @param {Record<string, any>} tiers
|
|
307
|
+
*/
|
|
308
|
+
export function nextNormalTier(id, tiers) {
|
|
309
|
+
const normals = sortedNormalTiers(tiers)
|
|
310
|
+
const index = normals.findIndex(([tierId]) => tierId === id)
|
|
311
|
+
if (index < 0) return null
|
|
312
|
+
return normals[index + 1]?.[0] ?? null
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Compute the score range for a normal tier placed after the current highest
|
|
317
|
+
* normal tier. When that tier is unbounded it must be narrowed to make room;
|
|
318
|
+
* the returned `narrowLastTo` tells the caller which upper bound to write.
|
|
319
|
+
* The caller is responsible for inserting the new tier.
|
|
320
|
+
* @param {Record<string, any>} tiers
|
|
321
|
+
* @param {string|null} [excludeId] tier being moved to the top
|
|
322
|
+
* @returns {{ minScore: number, lastId: string|null, narrowLastTo: number|null }}
|
|
323
|
+
*/
|
|
324
|
+
export function nextTopRange(tiers, excludeId = null) {
|
|
325
|
+
const others = { ...(tiers && typeof tiers === 'object' ? tiers : {}) }
|
|
326
|
+
if (excludeId) delete others[excludeId]
|
|
327
|
+
const normals = sortedNormalTiers(others)
|
|
328
|
+
const lastId = normals[normals.length - 1]?.[0] || null
|
|
329
|
+
const last = lastId ? others[lastId] : null
|
|
330
|
+
if (!last) return { minScore: 0, lastId: null, narrowLastTo: null }
|
|
331
|
+
if (Number.isFinite(last.maxScore)) {
|
|
332
|
+
return { minScore: last.maxScore, lastId, narrowLastTo: null }
|
|
333
|
+
}
|
|
334
|
+
const minScore = round((Number(last.minScore) || 0) + 1)
|
|
335
|
+
return { minScore, lastId, narrowLastTo: minScore }
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Resolve a tier reference by id or display name (case-insensitive).
|
|
340
|
+
* @param {unknown} ref
|
|
341
|
+
* @param {Record<string, any>} tiers
|
|
342
|
+
* @returns {string|null}
|
|
343
|
+
*/
|
|
344
|
+
export function resolveTierRef(ref, tiers) {
|
|
345
|
+
const key = cleanText(ref)
|
|
346
|
+
if (!key || !tiers || typeof tiers !== 'object') return null
|
|
347
|
+
if (tiers[key]) return key
|
|
348
|
+
const needle = key.toLowerCase()
|
|
349
|
+
for (const [id, entry] of Object.entries(tiers)) {
|
|
350
|
+
if (id.toLowerCase() === needle) return id
|
|
351
|
+
if (entryName(entry, id).toLowerCase() === needle) return id
|
|
352
|
+
}
|
|
353
|
+
return null
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function repairRanges(entries, warnings) {
|
|
357
|
+
const normals = sortedNormalTiers(entries)
|
|
358
|
+
for (let i = 1; i < normals.length; i += 1) {
|
|
359
|
+
const prev = normals[i - 1][1]
|
|
360
|
+
const current = normals[i][1]
|
|
361
|
+
if (prev.maxScore !== null && current.minScore >= prev.maxScore) continue
|
|
362
|
+
warnings.push(`档位「${prev.name}」与「${current.name}」的分数区间重叠,已自动收窄`)
|
|
363
|
+
// A bounded previous tier already has a usable boundary. An unbounded one
|
|
364
|
+
// must be narrowed here as well, otherwise it keeps swallowing the current
|
|
365
|
+
// tier's range and the overlap is never actually repaired.
|
|
366
|
+
const boundary = prev.maxScore !== null
|
|
367
|
+
? prev.maxScore
|
|
368
|
+
: (current.minScore > prev.minScore ? current.minScore : round(prev.minScore + 1))
|
|
369
|
+
prev.maxScore = boundary
|
|
370
|
+
current.minScore = boundary
|
|
371
|
+
if (current.maxScore !== null && current.maxScore <= boundary) current.maxScore = null
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function uniqueNames(entries, warnings) {
|
|
376
|
+
const seen = new Map()
|
|
377
|
+
for (const [id, entry] of sortTierEntries(entries)) {
|
|
378
|
+
const key = entry.name.toLowerCase()
|
|
379
|
+
if (!key) {
|
|
380
|
+
warnings.push(`档位 ${id} 的名称不能为空,已使用 id 代替`)
|
|
381
|
+
entry.name = id
|
|
382
|
+
continue
|
|
383
|
+
}
|
|
384
|
+
if (seen.has(key)) {
|
|
385
|
+
warnings.push(`档位名称重复:「${entry.name}」,已自动改为「${entry.name}(${id})」`)
|
|
386
|
+
entry.name = `${entry.name}(${id})`.slice(0, MAX_TIER_NAME)
|
|
387
|
+
}
|
|
388
|
+
seen.set(entry.name.toLowerCase(), id)
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function resolveEscalations(entries, warnings) {
|
|
393
|
+
const normals = sortedNormalTiers(entries)
|
|
394
|
+
for (const [id, entry] of sortTierEntries(entries)) {
|
|
395
|
+
if (entry.role === 'review') {
|
|
396
|
+
if (entry.escalateTo !== undefined && entry.escalateTo !== null) {
|
|
397
|
+
if (!entries[entry.escalateTo] || entry.escalateTo === id) {
|
|
398
|
+
warnings.push(`档位「${entry.name}」的升阶目标不存在,已清除`)
|
|
399
|
+
entry.escalateTo = null
|
|
400
|
+
}
|
|
401
|
+
} else {
|
|
402
|
+
entry.escalateTo = null
|
|
403
|
+
}
|
|
404
|
+
continue
|
|
405
|
+
}
|
|
406
|
+
const nextId = normals.findIndex(([tierId]) => tierId === id) >= 0
|
|
407
|
+
? nextNormalTier(id, entries)
|
|
408
|
+
: null
|
|
409
|
+
if (entry.escalateTo === undefined) {
|
|
410
|
+
entry.escalateTo = nextId
|
|
411
|
+
continue
|
|
412
|
+
}
|
|
413
|
+
if (entry.escalateTo === null) continue
|
|
414
|
+
if (!entries[entry.escalateTo] || entry.escalateTo === id) {
|
|
415
|
+
warnings.push(`档位「${entry.name}」的升阶目标不存在,已改为${nextId ? `「${entries[nextId].name}」` : '无'}`)
|
|
416
|
+
entry.escalateTo = nextId
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Normalize a tier map into the current schema.
|
|
423
|
+
*
|
|
424
|
+
* - `authoritative: true` uses exactly the supplied ids (removed tiers stay removed).
|
|
425
|
+
* - `authoritative: false` merges supplied overrides over `baseTiers` by id.
|
|
426
|
+
* - Invalid input falls back to `baseTiers`, then to the built-in skeleton.
|
|
427
|
+
*
|
|
428
|
+
* `issues` are blocking problems that cannot be repaired safely (for example a
|
|
429
|
+
* map without any normal tier). `warnings` describe problems that were already
|
|
430
|
+
* repaired automatically (overlaps, duplicate names, dropped routes, ...).
|
|
431
|
+
*
|
|
432
|
+
* @param {unknown} input
|
|
433
|
+
* @param {{ authoritative?: boolean, baseTiers?: Record<string, any> }} [options]
|
|
434
|
+
* @returns {{ tiers: Record<string, any>, issues: string[], warnings: string[] }}
|
|
435
|
+
*/
|
|
436
|
+
export function normalizeTierEntries(input, { authoritative = false, baseTiers = null } = {}) {
|
|
437
|
+
const issues = []
|
|
438
|
+
const warnings = []
|
|
439
|
+
const fallback = baseTiers && typeof baseTiers === 'object'
|
|
440
|
+
? baseTiers
|
|
441
|
+
: Object.fromEntries(DEFAULT_TIER_SKELETON.map(entry => [entry.id, { ...entry }]))
|
|
442
|
+
const source = input && typeof input === 'object' && !Array.isArray(input) ? input : null
|
|
443
|
+
|
|
444
|
+
let ids = []
|
|
445
|
+
if (!source) {
|
|
446
|
+
if (input !== undefined) warnings.push('档位配置无效,已恢复默认档位')
|
|
447
|
+
ids = Object.keys(fallback)
|
|
448
|
+
} else if (authoritative) {
|
|
449
|
+
ids = Object.keys(source)
|
|
450
|
+
} else {
|
|
451
|
+
ids = [...new Set([...Object.keys(fallback), ...Object.keys(source)])]
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if (ids.length === 0) {
|
|
455
|
+
warnings.push('档位配置为空,已使用默认档位')
|
|
456
|
+
ids = Object.keys(fallback)
|
|
457
|
+
}
|
|
458
|
+
if (ids.length > MAX_TIERS) {
|
|
459
|
+
warnings.push(`档位数量不能超过 ${MAX_TIERS} 个,多余的档位已忽略`)
|
|
460
|
+
ids = ids.slice(0, MAX_TIERS)
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const entries = {}
|
|
464
|
+
for (const id of ids) {
|
|
465
|
+
if (!TIER_ID_RE.test(id)) {
|
|
466
|
+
warnings.push(`档位 id「${id}」无效:需以字母开头,仅含字母、数字、- 或 _,已忽略`)
|
|
467
|
+
continue
|
|
468
|
+
}
|
|
469
|
+
const raw = source && Object.prototype.hasOwnProperty.call(source, id) ? source[id] : undefined
|
|
470
|
+
const base = fallback[id]
|
|
471
|
+
entries[id] = normalizeOne(id, raw ?? base ?? {}, fallback, warnings)
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
if (Object.keys(entries).length === 0) {
|
|
475
|
+
warnings.push('档位配置为空,已恢复默认档位')
|
|
476
|
+
for (const [id, entry] of Object.entries(fallback)) entries[id] = normalizeOne(id, entry, fallback, warnings)
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
uniqueNames(entries, warnings)
|
|
480
|
+
repairRanges(entries, warnings)
|
|
481
|
+
resolveEscalations(entries, warnings)
|
|
482
|
+
|
|
483
|
+
const normalCount = Object.values(entries).filter(entry => entry.role !== 'review').length
|
|
484
|
+
if (normalCount === 0) {
|
|
485
|
+
issues.push('至少需要保留一个普通(非审查)档位')
|
|
486
|
+
const replacement = Object.fromEntries(
|
|
487
|
+
Object.entries(fallback).map(([id, entry]) => [id, normalizeOne(id, entry, fallback, [])]),
|
|
488
|
+
)
|
|
489
|
+
uniqueNames(replacement, [])
|
|
490
|
+
repairRanges(replacement, [])
|
|
491
|
+
resolveEscalations(replacement, [])
|
|
492
|
+
return { tiers: replacement, issues, warnings }
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
return { tiers: entries, issues, warnings }
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Strict structural validation over an already-normalized tier map.
|
|
500
|
+
* @param {Record<string, any>} tiers
|
|
501
|
+
* @returns {string[]}
|
|
502
|
+
*/
|
|
503
|
+
export function validateTierEntries(tiers) {
|
|
504
|
+
const issues = []
|
|
505
|
+
if (!tiers || typeof tiers !== 'object' || Array.isArray(tiers)) {
|
|
506
|
+
return ['档位配置必须是对象(键为档位 id)']
|
|
507
|
+
}
|
|
508
|
+
const entries = Object.entries(tiers)
|
|
509
|
+
if (entries.length === 0) return ['至少需要保留一个普通档位']
|
|
510
|
+
if (entries.length > MAX_TIERS) issues.push(`档位数量不能超过 ${MAX_TIERS} 个`)
|
|
511
|
+
|
|
512
|
+
const names = new Set()
|
|
513
|
+
let normalCount = 0
|
|
514
|
+
for (const [id, entry] of entries) {
|
|
515
|
+
if (!TIER_ID_RE.test(id)) issues.push(`档位 id「${id}」无效`)
|
|
516
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
517
|
+
issues.push(`档位 ${id} 的配置无效`)
|
|
518
|
+
continue
|
|
519
|
+
}
|
|
520
|
+
const name = cleanText(entry.name, MAX_TIER_NAME)
|
|
521
|
+
if (!name) issues.push(`档位 ${id} 的名称不能为空`)
|
|
522
|
+
const nameKey = name.toLowerCase()
|
|
523
|
+
if (nameKey && names.has(nameKey)) issues.push(`档位名称重复:「${name}」`)
|
|
524
|
+
names.add(nameKey)
|
|
525
|
+
if (entry.role !== 'review') {
|
|
526
|
+
normalCount += 1
|
|
527
|
+
if (!Number.isFinite(entry.minScore) || entry.minScore < 0) {
|
|
528
|
+
issues.push(`档位「${name || id}」的分数下限无效`)
|
|
529
|
+
}
|
|
530
|
+
if (entry.maxScore !== null && (!Number.isFinite(entry.maxScore) || entry.maxScore <= entry.minScore)) {
|
|
531
|
+
issues.push(`档位「${name || id}」的分数上限必须大于下限`)
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
if (!PREFER_BACKENDS.includes(entry.preferBackend)) {
|
|
535
|
+
issues.push(`档位「${name || id}」的执行端倾向无效`)
|
|
536
|
+
}
|
|
537
|
+
if (entry.escalateTo !== null && entry.escalateTo !== undefined) {
|
|
538
|
+
if (!tiers[entry.escalateTo] || entry.escalateTo === id) {
|
|
539
|
+
issues.push(`档位「${name || id}」的升阶目标无效`)
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
if (!Array.isArray(entry.dsh) || !Array.isArray(entry.cli)) {
|
|
543
|
+
issues.push(`档位「${name || id}」的路由链格式无效`)
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (normalCount === 0) issues.push('至少需要保留一个普通(非审查)档位')
|
|
547
|
+
|
|
548
|
+
const normals = sortedNormalTiers(tiers)
|
|
549
|
+
for (let i = 1; i < normals.length; i += 1) {
|
|
550
|
+
const prev = normals[i - 1][1]
|
|
551
|
+
const current = normals[i][1]
|
|
552
|
+
if (prev.maxScore === null || current.minScore < prev.maxScore) {
|
|
553
|
+
issues.push(`档位「${prev.name}」与「${current.name}」的分数区间重叠`)
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
return issues
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Apply a layout preset while preserving routes for tiers with the same id.
|
|
561
|
+
* New ids clone the closest existing tier's routing chain.
|
|
562
|
+
* @param {Record<string, any>} tiers
|
|
563
|
+
* @param {'default'|'compact'|'fast'|string} key
|
|
564
|
+
* @returns {Record<string, any>}
|
|
565
|
+
*/
|
|
566
|
+
export function applyTierLayoutPreset(tiers, key) {
|
|
567
|
+
const preset = TIER_LAYOUT_PRESETS[key]
|
|
568
|
+
if (!preset) return clone(tiers || {})
|
|
569
|
+
const current = tiers && typeof tiers === 'object' ? tiers : {}
|
|
570
|
+
const currentEntries = sortTierEntries(current)
|
|
571
|
+
const fallbackSeed = currentEntries.find(([, entry]) => entry.role !== 'review')?.[1] || currentEntries[0]?.[1] || null
|
|
572
|
+
const next = {}
|
|
573
|
+
for (const meta of preset.tiers) {
|
|
574
|
+
const existing = current[meta.id]
|
|
575
|
+
const seed = existing || fallbackSeed
|
|
576
|
+
next[meta.id] = {
|
|
577
|
+
...(existing ? pickTierExtras(existing) : {}),
|
|
578
|
+
...meta,
|
|
579
|
+
...(seed ? {
|
|
580
|
+
preferBackend: seed.preferBackend,
|
|
581
|
+
dsh: clone(seed.dsh || []),
|
|
582
|
+
cli: clone(seed.cli || []),
|
|
583
|
+
} : { preferBackend: 'auto', dsh: [], cli: [] }),
|
|
584
|
+
escalateTo: undefined,
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
const normals = sortedNormalTiers(next)
|
|
588
|
+
normals.forEach(([id], index) => {
|
|
589
|
+
next[id].escalateTo = normals[index + 1]?.[0] ?? null
|
|
590
|
+
})
|
|
591
|
+
for (const entry of Object.values(next)) {
|
|
592
|
+
if (entry.role === 'review') entry.escalateTo = null
|
|
593
|
+
}
|
|
594
|
+
return next
|
|
595
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build-time Typert RPC contract for dsh-agent-router.
|
|
3
|
+
* Keep free of bare package imports so link-installed bundles load directly.
|
|
4
|
+
* @module dsh-agent-router/typert
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { RPC_ENDPOINTS } from './rpc-contract.js'
|
|
8
|
+
|
|
9
|
+
const PACKAGE = 'dsh-agent-router'
|
|
10
|
+
const ARGS_SYMBOL = PACKAGE + '/typert#EndpointArgs'
|
|
11
|
+
const RESULT_SYMBOL = PACKAGE + '/typert#JsonResult'
|
|
12
|
+
|
|
13
|
+
function isPlainObject(value) {
|
|
14
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
|
|
15
|
+
const proto = Object.getPrototypeOf(value)
|
|
16
|
+
return proto === null || proto === Object.prototype
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function assertMarshalable(value, seen) {
|
|
20
|
+
const marker = seen || new Set()
|
|
21
|
+
if (value === null || typeof value !== 'object') return value
|
|
22
|
+
if (marker.has(value)) throw new TypeError('cyclic RPC result')
|
|
23
|
+
marker.add(value)
|
|
24
|
+
try {
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
for (let i = 0; i < value.length; i += 1) assertMarshalable(value[i], marker)
|
|
27
|
+
return value
|
|
28
|
+
}
|
|
29
|
+
for (const key of Reflect.ownKeys(value)) assertMarshalable(value[key], marker)
|
|
30
|
+
return value
|
|
31
|
+
} finally {
|
|
32
|
+
marker.delete(value)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function argsCodec() {
|
|
37
|
+
return {
|
|
38
|
+
mode: 'strict',
|
|
39
|
+
typeSymbol: ARGS_SYMBOL,
|
|
40
|
+
create: () => ({
|
|
41
|
+
parse(value) {
|
|
42
|
+
if (!isPlainObject(value)) throw new TypeError(PACKAGE + ': endpoint args must be a plain object')
|
|
43
|
+
return value
|
|
44
|
+
},
|
|
45
|
+
}),
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function resultCodec() {
|
|
50
|
+
return {
|
|
51
|
+
mode: 'strict',
|
|
52
|
+
typeSymbol: RESULT_SYMBOL,
|
|
53
|
+
create: () => ({ parse: (value) => assertMarshalable(value) }),
|
|
54
|
+
encode: (value) => assertMarshalable(value),
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function buildInvocation(packageName, endpoint) {
|
|
59
|
+
return {
|
|
60
|
+
id: packageName + '#' + packageName + '/' + endpoint,
|
|
61
|
+
service: packageName,
|
|
62
|
+
namespace: packageName,
|
|
63
|
+
method: endpoint,
|
|
64
|
+
invocation: { kind: 'direct' },
|
|
65
|
+
parameters: [{ name: 'args', wire: 'args', source: 'json', codec: argsCodec() }],
|
|
66
|
+
result: resultCodec(),
|
|
67
|
+
sourceLocation: { file: 'lib/typert.host.js', line: 1, column: 1 },
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const TYPERT = {
|
|
72
|
+
package: PACKAGE,
|
|
73
|
+
face: 'host',
|
|
74
|
+
schemas: [],
|
|
75
|
+
invocations: RPC_ENDPOINTS.map((name) => buildInvocation(PACKAGE, name)),
|
|
76
|
+
model: { services: [], events: [], objects: [] },
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export default TYPERT
|