dsh-model-capability-sync 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Browser half: one settings section plus the host RPC call it needs.
3
+ *
4
+ * The section is a `settings.section` slot of its own, so no shell edit is
5
+ * required. Configuration reads and writes go through the official settings
6
+ * remote (`remote.settings`), which is the same surface the shell's own Models
7
+ * page uses; the only custom channel is the catalog lookup, which must run
8
+ * host-side to avoid a cross-origin download.
9
+ * @module dsh-model-capability-sync/client
10
+ */
11
+ import type { RpcEnvelope } from '../types.ts'
12
+ import type { LiveResponse, PreviewRequest, PreviewResponse } from '../types.ts'
13
+ import { SyncSection } from './SyncSection.tsx'
14
+ import type { SyncSectionInjected } from './SyncSection.tsx'
15
+ import type { SettingsDescriptor, SettingsInjected, SettingsPathOp } from './shared.ts'
16
+ import { en, zh } from './locale.ts'
17
+
18
+ /** Copy namespace owned by this plugin. */
19
+ const NS = 'settings.capability-sync'
20
+ /** Own host RPC channel. */
21
+ const CHANNEL = '/model-capability-sync'
22
+
23
+ /** The slice of the browser context this plugin uses. */
24
+ interface ClientContext {
25
+ effect(callback: () => (() => void) | void, label?: string): void
26
+ get(service: string): unknown
27
+ locale: {
28
+ register(ns: string, dictionaries: { zh: unknown; en: unknown }): () => void
29
+ bind(ns: string): (key: string, params?: Record<string, unknown>) => string
30
+ }
31
+ slots: {
32
+ inject(name: string, callback: () => () => void): void
33
+ register(options: Record<string, unknown>, component: unknown): () => void
34
+ }
35
+ }
36
+
37
+ /** The connection face carrying `rpc.call`. */
38
+ interface ConnectionFace {
39
+ rpc: { call(channel: string, endpoint: string, payload: unknown): Promise<unknown> }
40
+ }
41
+
42
+ /** The remote face carrying the settings namespace. */
43
+ interface RemoteFace {
44
+ settings: {
45
+ describe(): Promise<unknown>
46
+ mutate(ns: string, ops: SettingsPathOp[], expectedRevision?: number): Promise<unknown>
47
+ }
48
+ }
49
+
50
+ /** The document `settings.describe` answers with, once its envelope is opened. */
51
+ interface SettingsDocument {
52
+ writable?: boolean
53
+ namespaces?: SettingsDescriptor[]
54
+ }
55
+
56
+ /** A refusal as the Remote namespace states it. */
57
+ interface Refusal {
58
+ /** Machine-readable reason; `settings/conflict` is the one callers act on. */
59
+ code?: string
60
+ /** Human message for the page. */
61
+ message: string
62
+ }
63
+
64
+ /**
65
+ * Read the refusal out of a Remote answer envelope.
66
+ * @param answer - whatever the Remote namespace resolved with.
67
+ * @returns the refusal when the answer carries one, otherwise undefined.
68
+ */
69
+ function refusalOf(answer: unknown): Refusal | undefined {
70
+ if (typeof answer !== 'object' || answer === null) return undefined
71
+ const envelope = answer as { ok?: unknown; error?: { code?: unknown; message?: unknown } }
72
+ if (envelope.ok !== false) return undefined
73
+ return {
74
+ ...typeof envelope.error?.code === 'string' ? { code: envelope.error.code } : {},
75
+ message: typeof envelope.error?.message === 'string' ? envelope.error.message : 'settings request refused',
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Open a Remote answer envelope.
81
+ *
82
+ * Every `remote.settings` method answers `{ok: true, value}` or
83
+ * `{ok: false, error}`; a few surfaces hand back the bare value instead, so
84
+ * both shapes are accepted rather than guessed at one. A refusal keeps its
85
+ * `code`, so the section can tell a stale revision apart from a real failure.
86
+ * @param answer - whatever the Remote namespace resolved with.
87
+ * @returns the value the answer carries.
88
+ * @throws the refusal, carrying `code` when the answer had one.
89
+ */
90
+ function unwrap(answer: unknown): unknown {
91
+ const refusal = refusalOf(answer)
92
+ if (refusal !== undefined) {
93
+ throw Object.assign(new Error(refusal.message), refusal.code === undefined ? {} : { code: refusal.code })
94
+ }
95
+ if (typeof answer === 'object' && answer !== null && 'ok' in answer && 'value' in answer) {
96
+ return (answer as { value: unknown }).value
97
+ }
98
+ return answer
99
+ }
100
+
101
+ /**
102
+ * The namespace views a describe answer carries.
103
+ * @param answer - the `settings.describe` answer, enveloped or bare.
104
+ * @returns every served namespace view.
105
+ * @throws when the answer holds no namespace list.
106
+ */
107
+ function namespacesOf(answer: unknown): SettingsDescriptor[] {
108
+ const document = unwrap(answer) as SettingsDocument | SettingsDescriptor[] | undefined
109
+ if (Array.isArray(document)) return document
110
+ const namespaces = document?.namespaces
111
+ if (!Array.isArray(namespaces)) throw new Error('settings.describe returned no namespace list')
112
+ return namespaces
113
+ }
114
+
115
+ /** Required services (cordis fiber inject). */
116
+ export const inject = ['slots', 'locale', 'connection', 'remote', 'remote.settings']
117
+
118
+ /** Section styles, riding the shell's `--dsw-alias-*` tokens for both themes. */
119
+ const SECTION_CSS = `
120
+ .cs-field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 12px; }
121
+ .cs-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 12px; }
122
+ .cs-select {
123
+ box-sizing: border-box; padding: 6px 10px; border-radius: 8px;
124
+ border: 1px solid var(--dsw-alias-border-l2);
125
+ background: var(--dsw-alias-bg-layer-1);
126
+ color: var(--dsw-alias-label-primary);
127
+ font: inherit; font-size: 13px;
128
+ }
129
+ .cs-button {
130
+ padding: 6px 12px; border-radius: 6px; font: inherit; font-size: 13px;
131
+ border: 1px solid var(--dsw-alias-border-l2);
132
+ background: transparent; color: var(--dsw-alias-label-primary);
133
+ cursor: pointer;
134
+ }
135
+ .cs-button:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }
136
+ .cs-button:disabled { opacity: 0.4; cursor: default; }
137
+ .cs-button--primary {
138
+ border-color: transparent;
139
+ background: var(--dsw-alias-button-primary-fill);
140
+ color: var(--dsw-alias-label-primary-foreground);
141
+ }
142
+ .cs-button--primary:hover:not(:disabled) { background: var(--dsw-alias-button-primary-hover); }
143
+ .cs-hint { font-size: 12px; color: var(--dsw-alias-label-tertiary); line-height: 18px; }
144
+ .cs-error { color: var(--dsw-alias-state-error-primary); font-size: 12px; }
145
+ .cs-warn { color: var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary)); font-size: 12px; line-height: 18px; }
146
+ .cs-input {
147
+ box-sizing: border-box; padding: 6px 10px; border-radius: 8px; min-width: 200px;
148
+ border: 1px solid var(--dsw-alias-border-l2);
149
+ background: var(--dsw-alias-bg-layer-1);
150
+ color: var(--dsw-alias-label-primary);
151
+ font: inherit; font-size: 13px;
152
+ }
153
+ .cs-target { font-size: 13px; color: var(--dsw-alias-label-primary); line-height: 30px; }
154
+ .cs-table-wrap {
155
+ max-height: 460px; overflow: auto; margin-bottom: 12px;
156
+ border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px;
157
+ }
158
+ /* Fit the columns to the panel: ids and names wrap rather than push the table
159
+ wider than the space it has. Scrolling horizontally stays possible as a last
160
+ resort for a very narrow window, it just is not the normal state. */
161
+ .cs-table {
162
+ width: 100%; border-collapse: separate; border-spacing: 0; font-size: 12px;
163
+ table-layout: fixed;
164
+ }
165
+ .cs-table col.cs-col-check { width: 28px; }
166
+ .cs-table col.cs-col-id { width: 17%; }
167
+ .cs-table col.cs-col-name { width: 17%; }
168
+ .cs-table col.cs-col-match { width: 19%; }
169
+ .cs-table col.cs-col-context { width: 9%; }
170
+ .cs-table col.cs-col-output { width: 9%; }
171
+ .cs-table col.cs-col-image { width: 8%; }
172
+ .cs-table col.cs-col-live { width: 7%; }
173
+ .cs-table col.cs-col-reasoning { width: 14%; }
174
+ .cs-table th {
175
+ position: sticky; top: 0; z-index: 1;
176
+ text-align: left; font-weight: 500; color: var(--dsw-alias-label-secondary);
177
+ background: var(--dsw-alias-bg-layer-1);
178
+ padding: 6px 8px; border-bottom: 1px solid var(--dsw-alias-border-l2); white-space: nowrap;
179
+ }
180
+ .cs-table td {
181
+ padding: 6px 8px; border-bottom: 1px solid var(--dsw-alias-border-l2);
182
+ color: var(--dsw-alias-label-primary); vertical-align: top;
183
+ }
184
+ .cs-table tr:last-child td { border-bottom: none; }
185
+ .cs-row--changed td { background: var(--dsw-alias-bg-layer-2, transparent); }
186
+ .cs-id { font-variant-numeric: tabular-nums; word-break: break-all; }
187
+ /* Cells that hold a control keep the row compact and the table inside the panel. */
188
+ .cs-cell { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
189
+ .cs-input--cell, .cs-select--cell {
190
+ width: 100%; min-width: 0; padding: 2px 4px; font-size: 12px; line-height: 18px;
191
+ border-radius: 4px;
192
+ }
193
+ .cs-input--cell { text-align: right; font-variant-numeric: tabular-nums; }
194
+ .cs-select--cell { padding-right: 2px; }
195
+ /* A value the user typed is marked, so it is clear it did not come from the catalog. */
196
+ .cs-input--typed, .cs-select--typed {
197
+ border-color: var(--dsw-alias-brand-primary);
198
+ color: var(--dsw-alias-brand-primary);
199
+ }
200
+ .cs-change--block { display: block; white-space: normal; }
201
+ .cs-dim { color: var(--dsw-alias-label-tertiary); }
202
+ .cs-change { white-space: nowrap; }
203
+ .cs-from { color: var(--dsw-alias-label-tertiary); text-decoration: line-through; }
204
+ .cs-badge {
205
+ display: inline-block; padding: 0 6px; border-radius: 9px; font-size: 11px; line-height: 18px;
206
+ border: 1px solid var(--dsw-alias-border-l2); color: var(--dsw-alias-label-secondary);
207
+ }
208
+ .cs-badge--image { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }
209
+ .cs-unmatched { margin: 8px 0 0; padding-left: 18px; color: var(--dsw-alias-label-tertiary); font-size: 12px; }
210
+ `
211
+
212
+ /**
213
+ * Register the copy dictionary, the section styles, and the section itself.
214
+ * @param ctx - browser root context.
215
+ */
216
+ export function apply(ctx: ClientContext): void {
217
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'model-capability-sync: copy dictionaries')
218
+
219
+ if (typeof document !== 'undefined') {
220
+ ctx.effect(() => {
221
+ const element = document.createElement('style')
222
+ element.textContent = SECTION_CSS
223
+ document.head.append(element)
224
+ return () => { element.remove() }
225
+ }, 'model-capability-sync: section styles')
226
+ }
227
+
228
+ const connection = ctx.get('connection') as ConnectionFace
229
+ const remote = ctx.get('remote') as RemoteFace
230
+ const t = ctx.locale.bind(NS)
231
+
232
+ const settingsInjected = (): SettingsInjected => ({
233
+ describeSettings: async () => namespacesOf(await remote.settings.describe()),
234
+ mutateSettings: async (ns, ops, expectedRevision) => {
235
+ const view = unwrap(await remote.settings.mutate(ns, ops, expectedRevision)) as SettingsDescriptor | undefined
236
+ if (view === undefined) throw new Error('settings.mutate returned no namespace view')
237
+ return view
238
+ },
239
+ })
240
+
241
+ const injected = (): SyncSectionInjected => ({
242
+ ...settingsInjected(),
243
+ preview: request =>
244
+ connection.rpc.call(CHANNEL, 'preview', request) as Promise<RpcEnvelope<PreviewResponse>>,
245
+ live: request =>
246
+ connection.rpc.call(CHANNEL, 'live', request) as Promise<RpcEnvelope<LiveResponse>>,
247
+ })
248
+
249
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
250
+ name: 'settings.section',
251
+ id: 'model-capability-sync',
252
+ order: 16,
253
+ label: () => t('nav'),
254
+ locale: NS,
255
+ inject: injected,
256
+ }, SyncSection))
257
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Browser-half entry: the module loader imports this file and calls its
3
+ * `apply` once the injected services exist.
4
+ * @module dsh-model-capability-sync/client
5
+ */
6
+ export { apply, inject } from './apply.ts'
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Copy dictionaries for the capability-sync section. Chinese first (the dsh
3
+ * web convention); English mirrors it key for key.
4
+ */
5
+
6
+ export const zh = {
7
+ nav: '模型能力同步',
8
+ loading: '正在读取配置…',
9
+ intro: '从 models.dev 查询已配置模型的能力(上下文窗口、输出上限、是否支持图片、推理档位),并写入所选供应商的配置。本页只写配置,不发送任何推理请求。',
10
+ writeTarget: '写入位置',
11
+ sourceNative: '原生配置',
12
+ sourcePlugin: '插件配置',
13
+ nameLlmPiAi: 'pi-ai 适配器',
14
+ nameLlmDeepseek: 'DeepSeek 官方',
15
+ nameLlmDeepseekAccount: 'DeepSeek 账号',
16
+ nameLlmNewapi: 'NewAPI',
17
+ provider: '供应商',
18
+ modelCount: '共 {count} 个模型',
19
+ willSort: '写入时按「前缀分组 + 名称」排序',
20
+ sortMode: '排序',
21
+ sortByPrefix: '按模型前缀排序(分组)',
22
+ sortByRedirected: '按重定向后【来源】名称排序',
23
+ search: '搜索模型 ID 或目录 ID',
24
+ onlyChanged: '只看有变化的',
25
+ changeSummary: '将修改 {rows} 行 · {fields} 个字段',
26
+ noChanges: '没有需要写入的变化(目录值与你现有配置一致)。',
27
+ filteredEmpty: '没有符合筛选条件的模型。',
28
+ fieldEmpty: '未设置',
29
+ conflictReload: '配置已被其他改动更新,已重新读取最新值;请确认后再点一次「应用」。',
30
+ analyze: '分析能力',
31
+ analyzing: '正在匹配…',
32
+ refreshCatalog: '重新下载目录',
33
+ apply: '应用',
34
+ applying: '正在写入…',
35
+ applied: '已写入 {count} 个模型',
36
+ overwrite: '覆盖已有值',
37
+ overwriteHint: '不勾选时只填空白字段,你手填过的值不会被改写。',
38
+ selectAll: '全选',
39
+ colModel: '模型 ID',
40
+ colName: '名称',
41
+ colMatch: '匹配',
42
+ colContext: '上下文',
43
+ colOutput: '输出',
44
+ colImage: '图片',
45
+ colLive: '当前生效',
46
+ colLiveHint: '由真正接管这条路由的适配器上报,也就是聊天请求实际看到的值。若它与「图片」列不一致,说明配置被另一个插件抢占了路由。',
47
+ liveError: '无法读取',
48
+ liveSummary: '当前生效:{image} 个支持图片,{text} 个纯文本。若与「图片」列不一致,说明这条路由由别的插件接管,写入本配置不会生效。',
49
+ colReasoning: '推理档位',
50
+ imageYes: '支持',
51
+ imageNo: '纯文本',
52
+ unmatched: '未匹配',
53
+ unmatchedHint: '其中 {count} 个模型在 models.dev 里找不到,能力参数可以在上表里手动填。',
54
+ editHint: '上下文 / 输出 / 图片可以直接在表格里改:目录没收录的模型也能手动填,蓝色表示是你手填的值。',
55
+ notListed: '目录未收录',
56
+ noModels: '该供应商下还没有模型。',
57
+ noTarget: '没有找到可写的配置条目(需要已启用的 llm-pi-ai 供应商配置)。',
58
+ loadFailed: '加载失败',
59
+ retry: '重试',
60
+ viaAlias: '别名',
61
+ viaName: '按名称',
62
+ viaNameSuffix: '名称去变体',
63
+ viaExact: '精确',
64
+ viaFolded: '忽略大小写',
65
+ viaBasename: '去前缀',
66
+ viaSuffix: '去变体后缀',
67
+ viaPrefix: '前缀匹配',
68
+ viaVendor: '去供应商前缀',
69
+ viaSpelling: '空格转横线',
70
+ catalogInfo: '目录:{models} 个模型 · {time}',
71
+ catalogStale: '在线目录下载失败,正在使用本机缓存({time})。数据可能不是最新,字段含义不变。',
72
+ nothingSelected: '没有选中任何模型。',
73
+ redirectNoChanges: '这些名称已带来源前缀,无需改动。',
74
+ reorder: '重排',
75
+ reordering: '重排中...',
76
+ reordered: '已按 {mode} 重排目录',
77
+ redirectApply: '写入名称',
78
+ redirectApplying: '正在写入…',
79
+ redirectApplied: '已改写 {count} 个名称',
80
+ } as const
81
+
82
+ export type SyncKey = keyof typeof zh
83
+
84
+ export const en: Record<SyncKey, string> = {
85
+ nav: 'Model capabilities',
86
+ loading: 'Reading configuration…',
87
+ intro: 'Look up capabilities (context window, output cap, image input, reasoning efforts) for the models already configured here, then write them into the selected provider. This page only writes configuration; it never sends a model request.',
88
+ writeTarget: 'Write to',
89
+ sourceNative: 'Built in',
90
+ sourcePlugin: 'Plugin',
91
+ nameLlmPiAi: 'pi-ai adapter',
92
+ nameLlmDeepseek: 'DeepSeek official',
93
+ nameLlmDeepseekAccount: 'DeepSeek account',
94
+ nameLlmNewapi: 'NewAPI',
95
+ provider: 'Provider',
96
+ modelCount: '{count} models',
97
+ willSort: 'Written sorted by vendor prefix, then name',
98
+ sortMode: 'Order',
99
+ sortByPrefix: 'Sort by model prefix (grouped)',
100
+ sortByRedirected: 'Sort by redirected name 【source】',
101
+ search: 'Search model id or catalog id',
102
+ onlyChanged: 'Only rows that change',
103
+ changeSummary: 'Will change {rows} rows · {fields} fields',
104
+ noChanges: 'Nothing to write: the catalog agrees with your configuration.',
105
+ filteredEmpty: 'No model matches the filter.',
106
+ fieldEmpty: 'unset',
107
+ conflictReload: 'The configuration changed elsewhere; the latest values were reloaded. Check them, then press Apply again.',
108
+ analyze: 'Analyze',
109
+ analyzing: 'Matching…',
110
+ refreshCatalog: 'Re-download catalog',
111
+ apply: 'Apply',
112
+ applying: 'Writing…',
113
+ applied: 'Wrote {count} models',
114
+ overwrite: 'Overwrite existing values',
115
+ overwriteHint: 'Unchecked: only blank fields are filled, so values you typed are preserved.',
116
+ selectAll: 'Select all',
117
+ colModel: 'Model id',
118
+ colName: 'Name',
119
+ colMatch: 'Match',
120
+ colContext: 'Context',
121
+ colOutput: 'Output',
122
+ colImage: 'Image',
123
+ colLive: 'In effect',
124
+ colLiveHint: 'Reported by the adapter that actually serves this route — what a chat request sees. A value that disagrees with the Image column means another plugin owns the route.',
125
+ liveError: 'unreadable',
126
+ liveSummary: 'In effect: {image} image-capable, {text} text-only. If this disagrees with the Image column, another plugin serves the route and writing this entry changes nothing.',
127
+ colReasoning: 'Reasoning',
128
+ imageYes: 'yes',
129
+ imageNo: 'text only',
130
+ unmatched: 'unmatched',
131
+ unmatchedHint: '{count} of these are not in models.dev; type their capability values in the table above.',
132
+ editHint: 'Context, output and image can be edited right in the table — including models the catalog never listed. A blue value is one you typed.',
133
+ notListed: 'not listed',
134
+ noModels: 'This provider has no models yet.',
135
+ noTarget: 'No writable configuration entry found (an enabled llm-pi-ai provider is required).',
136
+ loadFailed: 'Load failed',
137
+ retry: 'Retry',
138
+ viaAlias: 'alias',
139
+ viaName: 'by name',
140
+ viaNameSuffix: 'name + variant',
141
+ viaExact: 'exact',
142
+ viaFolded: 'case-folded',
143
+ viaBasename: 'basename',
144
+ viaSuffix: 'suffix',
145
+ viaPrefix: 'prefix match',
146
+ viaVendor: 'vendor prefix',
147
+ viaSpelling: 'gap as dash',
148
+ catalogInfo: 'Catalog: {models} models · {time}',
149
+ catalogStale: 'The online catalog download failed; using the local copy from {time}. The facts still mean the same thing, they may just be older.',
150
+ nothingSelected: 'Nothing selected.',
151
+ redirectNoChanges: 'These names already carry a source prefix; nothing to change.',
152
+ reorder: 'Reorder',
153
+ reordering: 'Reordering…',
154
+ reordered: 'Reordered by {mode}',
155
+ redirectApply: 'Write names',
156
+ redirectApplying: 'Writing…',
157
+ redirectApplied: 'Rewrote {count} names',
158
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Name redirection: automatically prepend each gateway model's source prefix.
3
+ *
4
+ * A gateway namespaces its upstream by a path prefix (`qoder/qfmodel`,
5
+ * `qoder-cn/qfmodel`, `antigravity/gemini-3.8-flash`) and keeps the upstream's
6
+ * own label as the name. Two sources that offer the same model therefore look
7
+ * identical in the model picker — both read "Qwen3.8-Flash" — and the only
8
+ * clue to which source serves the answer is buried in an id nobody sees while
9
+ * chatting.
10
+ *
11
+ * The rule here is applied to ALL models automatically:
12
+ * - Models with a source prefix (e.g. `qoder/`) get 【vendor】 prepended
13
+ * - Models without a prefix get 【other】 prepended
14
+ *
15
+ * The rule is deliberately mechanical: take the first path segment of the id
16
+ * (or use 'other' if none), strip anything of that shape already on the name
17
+ * (leading 【prefix】, a prefix/ at the front, or a trailing 【prefix】 from
18
+ * before the redesign), then prepend 【prefix】 followed by a space. So the
19
+ * prefix ends up in exactly one place, at the front, in one spelling.
20
+ * Re-running the rule is a no-op, so reapplying never stacks prefixes.
21
+ *
22
+ * This module is pure: no settings access, no React. The section renders the
23
+ * plan and writes it through the official settings service.
24
+ * @module dsh-model-capability-sync/rename
25
+ */
26
+ import type { ModelDraft } from './shared.ts'
27
+ import { textOf } from './shared.ts'
28
+
29
+ /** One model and the name redirect that applies to it. */
30
+ export interface NameRow {
31
+ /** The gateway model id exactly as configured. */
32
+ id: string
33
+ /** The source prefix (the first path segment), or `''` when the id has none. */
34
+ prefix: string
35
+ /** What the picker shows today: the stored name, or the id when it is blank. */
36
+ before: string
37
+ /** What the picker would show after the redirect. */
38
+ after: string
39
+ /** True when applying would actually rewrite the stored name. */
40
+ changed: boolean
41
+ }
42
+
43
+ /**
44
+ * The source prefix of one gateway id.
45
+ *
46
+ * Only the first path segment counts: a gateway may nest further
47
+ * (`qoder/gj/qwen3.8`), but the thing that distinguishes sources is the
48
+ * outermost one.
49
+ * @param id - the gateway model id exactly as configured.
50
+ * @returns the prefix, or `''` when the id has no usable prefix.
51
+ */
52
+ export function sourcePrefixOf(id: string): string {
53
+ const slash = id.indexOf('/')
54
+ if (slash <= 0) return ''
55
+ return id.slice(0, slash)
56
+ }
57
+
58
+ /**
59
+ * The part of an id after its prefix — the fallback label when a model has no
60
+ * name of its own.
61
+ * @param id - the gateway model id exactly as configured.
62
+ * @returns the remainder after the first slash, or the whole id without one.
63
+ */
64
+ function bareIdOf(id: string): string {
65
+ const slash = id.indexOf('/')
66
+ if (slash === -1) return id
67
+ const rest = id.slice(slash + 1)
68
+ return rest === '' ? id : rest
69
+ }
70
+
71
+ /**
72
+ * Compute the redirected name for one model.
73
+ *
74
+ * All models get a prefix annotation: one extracted from the id (e.g. `qoder/` → `【qoder】`),
75
+ * or `【other】` when the id has no path segment. The prefix uses full-width brackets
76
+ * because a model label is already dense with ASCII, and parentheses would read as
77
+ * part of the upstream's own name. Placing it at the front makes it immediately
78
+ * visible as the source, improving clarity.
79
+ * @param id - the gateway model id exactly as configured.
80
+ * @param name - the stored display name; the empty string when it is unset.
81
+ * @returns the prefix, both labels, and whether the write changes anything.
82
+ */
83
+ export function redirectName(id: string, name: string): Omit<NameRow, 'id'> {
84
+ let prefix = sourcePrefixOf(id)
85
+ if (prefix === '') prefix = 'other' // No source prefix in id → use 【other】
86
+
87
+ const before = name !== '' ? name : id
88
+ const prefix_bracket = `【${prefix}】`
89
+ const prefix_space = `${prefix_bracket} `
90
+
91
+ // If already has the exact prefix at the beginning, no change needed (idempotent).
92
+ if (before.startsWith(prefix_space)) {
93
+ return { prefix, before, after: before, changed: false }
94
+ }
95
+
96
+ // Strip any existing bracket annotation (both leading and trailing).
97
+ // This handles both our 【prefix】 (new prefix-at-start), the old rule's suffix
98
+ // 【prefix】 (at the end), legacy ( ) and user-added [ ] gracefully.
99
+ let stripped = before
100
+
101
+ // Strip any leading bracket annotation (【】, (), [])
102
+ const leadingAnnotations = /^【[^】]*】\s*|\s*\([^)]*\)\s*|\s*\[[^\]]*\]\s*/
103
+ stripped = stripped.replace(leadingAnnotations, '')
104
+
105
+ // Strip any trailing bracket annotation
106
+ const trailingAnnotations = /\s*【[^】]*】\s*|\s*\([^)]*\)\s*|\s*\[[^\]]*\]\s*$/
107
+ while (trailingAnnotations.test(stripped)) {
108
+ stripped = stripped.replace(trailingAnnotations, '')
109
+ }
110
+
111
+ // Strip leading prefix if present (user might have put "qoder/ModelName")
112
+ const originalPrefix = sourcePrefixOf(id)
113
+ if (originalPrefix !== '') {
114
+ const lead = `${originalPrefix}/`
115
+ if (stripped.startsWith(lead)) {
116
+ stripped = stripped.slice(lead.length)
117
+ }
118
+ }
119
+
120
+ const base = stripped.trimEnd() !== '' ? stripped.trimEnd() : bareIdOf(id)
121
+ const after = `${prefix_space}${base}`
122
+ return { prefix, before, after, changed: after !== before }
123
+ }
124
+
125
+ /**
126
+ * Build the redirect plan for one provider's models.
127
+ * @param models - the stored entries, in display order.
128
+ * @returns one row per entry, in the same order.
129
+ */
130
+ export function planNames(models: readonly ModelDraft[]): NameRow[] {
131
+ return models.map((model) => {
132
+ const id = textOf(model, 'id')
133
+ return { id, ...redirectName(id, textOf(model, 'name')) }
134
+ })
135
+ }
136
+
137
+ /**
138
+ * Apply a redirect plan to the stored entries.
139
+ *
140
+ * Only selected ids are touched, and only when the redirect actually changes
141
+ * the name, so a stale plan cannot rewrite a label the user just edited.
142
+ * @param models - the stored entries, in stored order.
143
+ * @param selected - ids to rewrite.
144
+ * @returns the new entries plus how many were rewritten.
145
+ */
146
+ export function renameModels(models: readonly ModelDraft[], selected: ReadonlySet<string>): { next: ModelDraft[]; written: number } {
147
+ let written = 0
148
+ const next = models.map((model) => {
149
+ const id = textOf(model, 'id')
150
+ if (!selected.has(id)) return model
151
+ const { after, changed } = redirectName(id, textOf(model, 'name'))
152
+ if (!changed) return model
153
+ written += 1
154
+ return { ...model, name: after }
155
+ })
156
+ return { next, written }
157
+ }