dsh-model-capability-sync 0.1.0 → 0.2.1

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.
@@ -11,7 +11,8 @@
11
11
  import type { RpcEnvelope } from '../types.ts'
12
12
  import type { LiveResponse, PreviewRequest, PreviewResponse } from '../types.ts'
13
13
  import { SyncSection } from './SyncSection.tsx'
14
- import type { SettingsDescriptor, SettingsPathOp, SyncSectionInjected } from './SyncSection.tsx'
14
+ import type { SyncSectionInjected } from './SyncSection.tsx'
15
+ import type { SettingsDescriptor, SettingsInjected, SettingsPathOp } from './shared.ts'
15
16
  import { en, zh } from './locale.ts'
16
17
 
17
18
  /** Copy namespace owned by this plugin. */
@@ -154,7 +155,22 @@ const SECTION_CSS = `
154
155
  max-height: 460px; overflow: auto; margin-bottom: 12px;
155
156
  border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px;
156
157
  }
157
- .cs-table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 12px; }
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%; }
158
174
  .cs-table th {
159
175
  position: sticky; top: 0; z-index: 1;
160
176
  text-align: left; font-weight: 500; color: var(--dsw-alias-label-secondary);
@@ -168,6 +184,20 @@ const SECTION_CSS = `
168
184
  .cs-table tr:last-child td { border-bottom: none; }
169
185
  .cs-row--changed td { background: var(--dsw-alias-bg-layer-2, transparent); }
170
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; }
171
201
  .cs-dim { color: var(--dsw-alias-label-tertiary); }
172
202
  .cs-change { white-space: nowrap; }
173
203
  .cs-from { color: var(--dsw-alias-label-tertiary); text-decoration: line-through; }
@@ -199,11 +229,7 @@ export function apply(ctx: ClientContext): void {
199
229
  const remote = ctx.get('remote') as RemoteFace
200
230
  const t = ctx.locale.bind(NS)
201
231
 
202
- const injected = (): SyncSectionInjected => ({
203
- preview: request =>
204
- connection.rpc.call(CHANNEL, 'preview', request) as Promise<RpcEnvelope<PreviewResponse>>,
205
- live: request =>
206
- connection.rpc.call(CHANNEL, 'live', request) as Promise<RpcEnvelope<LiveResponse>>,
232
+ const settingsInjected = (): SettingsInjected => ({
207
233
  describeSettings: async () => namespacesOf(await remote.settings.describe()),
208
234
  mutateSettings: async (ns, ops, expectedRevision) => {
209
235
  const view = unwrap(await remote.settings.mutate(ns, ops, expectedRevision)) as SettingsDescriptor | undefined
@@ -212,6 +238,14 @@ export function apply(ctx: ClientContext): void {
212
238
  },
213
239
  })
214
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
+
215
249
  ctx.slots.inject('settings.section', () => ctx.slots.register({
216
250
  name: 'settings.section',
217
251
  id: 'model-capability-sync',
@@ -17,6 +17,9 @@ export const zh = {
17
17
  provider: '供应商',
18
18
  modelCount: '共 {count} 个模型',
19
19
  willSort: '写入时按「前缀分组 + 名称」排序',
20
+ sortMode: '排序',
21
+ sortByPrefix: '按模型前缀排序(分组)',
22
+ sortByRedirected: '按重定向后【来源】名称排序',
20
23
  search: '搜索模型 ID 或目录 ID',
21
24
  onlyChanged: '只看有变化的',
22
25
  changeSummary: '将修改 {rows} 行 · {fields} 个字段',
@@ -34,6 +37,7 @@ export const zh = {
34
37
  overwriteHint: '不勾选时只填空白字段,你手填过的值不会被改写。',
35
38
  selectAll: '全选',
36
39
  colModel: '模型 ID',
40
+ colName: '名称',
37
41
  colMatch: '匹配',
38
42
  colContext: '上下文',
39
43
  colOutput: '输出',
@@ -46,20 +50,33 @@ export const zh = {
46
50
  imageYes: '支持',
47
51
  imageNo: '纯文本',
48
52
  unmatched: '未匹配',
49
- unmatchedHint: '这些模型在 models.dev 里找不到,保持原样。可在别名表里手动指定。',
53
+ unmatchedHint: '其中 {count} 个模型在 models.dev 里找不到,能力参数可以在上表里手动填。',
54
+ editHint: '上下文 / 输出 / 图片可以直接在表格里改:目录没收录的模型也能手动填,蓝色表示是你手填的值。',
55
+ notListed: '目录未收录',
50
56
  noModels: '该供应商下还没有模型。',
51
57
  noTarget: '没有找到可写的配置条目(需要已启用的 llm-pi-ai 供应商配置)。',
52
58
  loadFailed: '加载失败',
53
59
  retry: '重试',
54
60
  viaAlias: '别名',
61
+ viaName: '按名称',
62
+ viaNameSuffix: '名称去变体',
55
63
  viaExact: '精确',
56
64
  viaFolded: '忽略大小写',
57
65
  viaBasename: '去前缀',
58
66
  viaSuffix: '去变体后缀',
67
+ viaPrefix: '前缀匹配',
68
+ viaVendor: '去供应商前缀',
69
+ viaSpelling: '空格转横线',
59
70
  catalogInfo: '目录:{models} 个模型 · {time}',
60
71
  catalogStale: '在线目录下载失败,正在使用本机缓存({time})。数据可能不是最新,字段含义不变。',
61
72
  nothingSelected: '没有选中任何模型。',
62
- done: '完成。',
73
+ redirectNoChanges: '这些名称已带来源前缀,无需改动。',
74
+ reorder: '重排',
75
+ reordering: '重排中...',
76
+ reordered: '已按 {mode} 重排目录',
77
+ redirectApply: '写入名称',
78
+ redirectApplying: '正在写入…',
79
+ redirectApplied: '已改写 {count} 个名称',
63
80
  } as const
64
81
 
65
82
  export type SyncKey = keyof typeof zh
@@ -78,6 +95,9 @@ export const en: Record<SyncKey, string> = {
78
95
  provider: 'Provider',
79
96
  modelCount: '{count} models',
80
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】',
81
101
  search: 'Search model id or catalog id',
82
102
  onlyChanged: 'Only rows that change',
83
103
  changeSummary: 'Will change {rows} rows · {fields} fields',
@@ -95,6 +115,7 @@ export const en: Record<SyncKey, string> = {
95
115
  overwriteHint: 'Unchecked: only blank fields are filled, so values you typed are preserved.',
96
116
  selectAll: 'Select all',
97
117
  colModel: 'Model id',
118
+ colName: 'Name',
98
119
  colMatch: 'Match',
99
120
  colContext: 'Context',
100
121
  colOutput: 'Output',
@@ -107,18 +128,31 @@ export const en: Record<SyncKey, string> = {
107
128
  imageYes: 'yes',
108
129
  imageNo: 'text only',
109
130
  unmatched: 'unmatched',
110
- unmatchedHint: 'These ids are absent from models.dev and stay untouched. Add an alias to map them by hand.',
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',
111
134
  noModels: 'This provider has no models yet.',
112
135
  noTarget: 'No writable configuration entry found (an enabled llm-pi-ai provider is required).',
113
136
  loadFailed: 'Load failed',
114
137
  retry: 'Retry',
115
138
  viaAlias: 'alias',
139
+ viaName: 'by name',
140
+ viaNameSuffix: 'name + variant',
116
141
  viaExact: 'exact',
117
142
  viaFolded: 'case-folded',
118
143
  viaBasename: 'basename',
119
144
  viaSuffix: 'suffix',
145
+ viaPrefix: 'prefix match',
146
+ viaVendor: 'vendor prefix',
147
+ viaSpelling: 'gap as dash',
120
148
  catalogInfo: 'Catalog: {models} models · {time}',
121
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.',
122
150
  nothingSelected: 'Nothing selected.',
123
- done: 'Done.',
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',
124
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
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Settings shapes and provider-entry helpers shared by the plugin's two
3
+ * settings sections: capability sync and name redirect.
4
+ *
5
+ * The browser half only sees `settings.describe` / `settings.mutate`, and that
6
+ * document is structurally open — these helpers keep every unknown field alive
7
+ * instead of narrowing the entry to the fields this plugin understands.
8
+ * @module dsh-model-capability-sync/client/shared
9
+ */
10
+ import type { CapabilityFields } from '../types.ts'
11
+ import type { SortMode } from '../sort.ts'
12
+ import { sortByModelId } from '../sort.ts'
13
+
14
+ /** One settings descriptor as the remote reports it (only the fields used here). */
15
+ export interface SettingsDescriptor {
16
+ ns: string
17
+ revision: number
18
+ value: Record<string, unknown>
19
+ }
20
+
21
+ /** One ordered form edit understood by `settings.mutate`. */
22
+ export interface SettingsPathOp {
23
+ op: 'set' | 'unset'
24
+ path: string[]
25
+ value?: unknown
26
+ }
27
+
28
+ /** The settings surface both sections read and write through. */
29
+ export interface SettingsInjected {
30
+ describeSettings(): Promise<SettingsDescriptor[]>
31
+ mutateSettings(ns: string, ops: SettingsPathOp[], expectedRevision?: number): Promise<SettingsDescriptor>
32
+ }
33
+
34
+ /** A model entry as the provider stores it: structurally open, so unknown fields survive. */
35
+ export type ModelDraft = Record<string, unknown>
36
+
37
+ /** The official adapter this plugin fills capabilities into. */
38
+ export const TARGET_DEFAULT = 'llm-pi-ai'
39
+
40
+ /**
41
+ * How a writable settings namespace reads to a person.
42
+ *
43
+ * A namespace id is an internal identity, so the page names the thing it
44
+ * configures instead. Provenance is a table, not a guess: the client cannot
45
+ * see which package owns a namespace (`settings.describe` reports only
46
+ * `ns/revision/value/base/user`), and inferring "official" from an `llm-`
47
+ * prefix would eventually mislabel a third-party plugin. A namespace this
48
+ * table does not know is shown as a plugin, with its id.
49
+ */
50
+ export const TARGET_DIRECTORY: Record<string, { native: boolean; nameKey: string }> = {
51
+ 'llm-pi-ai': { native: true, nameKey: 'nameLlmPiAi' },
52
+ 'llm-deepseek': { native: true, nameKey: 'nameLlmDeepseek' },
53
+ 'llm-deepseek-account': { native: true, nameKey: 'nameLlmDeepseekAccount' },
54
+ 'llm-newapi': { native: false, nameKey: 'nameLlmNewapi' },
55
+ }
56
+
57
+ /** The bound translate function the shell hands to a section. */
58
+ export type Translate = (key: string, params?: Record<string, unknown>) => string
59
+
60
+ /**
61
+ * Render one namespace as provenance plus a name.
62
+ * @param ns - the settings namespace id.
63
+ * @param t - the bound translate function.
64
+ * @returns copy such as `原生配置 · pi-ai`, never a bare namespace id.
65
+ */
66
+ export function targetLabelOf(ns: string, t: Translate): string {
67
+ const known = TARGET_DIRECTORY[ns]
68
+ if (known === undefined) return `${t('sourcePlugin')} · ${ns}`
69
+ return `${known.native ? t('sourceNative') : t('sourcePlugin')} · ${t(known.nameKey)}`
70
+ }
71
+
72
+ /** The provider dict inside one descriptor's live value. */
73
+ export function providersOf(descriptor: SettingsDescriptor | undefined): Record<string, Record<string, unknown>> {
74
+ const providers = descriptor?.value?.providers
75
+ return typeof providers === 'object' && providers !== null
76
+ ? providers as Record<string, Record<string, unknown>>
77
+ : {}
78
+ }
79
+
80
+ /** The models array of one provider profile. */
81
+ export function modelsOf(provider: Record<string, unknown> | undefined): ModelDraft[] {
82
+ const models = provider?.models
83
+ return Array.isArray(models) ? models.filter((entry): entry is ModelDraft => typeof entry === 'object' && entry !== null) : []
84
+ }
85
+
86
+ /** The models of one provider profile, in display order. */
87
+ export function sortedModelsOf(provider: Record<string, unknown> | undefined, mode: SortMode = 'prefix'): ModelDraft[] {
88
+ return sortByModelId(
89
+ modelsOf(provider),
90
+ model => textOf(model, 'id'),
91
+ model => textOf(model, 'name'),
92
+ mode,
93
+ )
94
+ }
95
+
96
+ /** Read a string field, or the empty string. */
97
+ export function textOf(model: ModelDraft, key: string): string {
98
+ const value = model[key]
99
+ return typeof value === 'string' ? value : ''
100
+ }
101
+
102
+ /**
103
+ * Decide whether a stored field counts as "the user has not said anything".
104
+ *
105
+ * The configuration schema fills defaults for absent fields (`input` reads as
106
+ * `[]`), and those defaults are not user intent, so they count as blank.
107
+ * @param value - the stored value.
108
+ * @returns true when filling the field loses no user intent.
109
+ */
110
+ export function isBlank(value: unknown): boolean {
111
+ if (value === undefined || value === null || value === '') return true
112
+ if (Array.isArray(value)) return value.length === 0
113
+ if (typeof value === 'object') return Object.keys(value as Record<string, unknown>).length === 0
114
+ return false
115
+ }
116
+
117
+ /**
118
+ * Replace one provider's model list inside a descriptor, keeping everything
119
+ * else it carries.
120
+ *
121
+ * A write updates the configuration, so the descriptor the page holds must
122
+ * follow: otherwise the next rebuild from that descriptor (a sort-mode switch,
123
+ * a provider switch, a conflict reload) hands back the pre-write models and the
124
+ * names that were just applied disappear. This is the pure half of that update,
125
+ * separated so it can be tested without a running settings service.
126
+ *
127
+ * Only `providers[key].models` moves. Other providers, and other fields of this
128
+ * provider and its models, are carried over untouched.
129
+ * @param descriptor - the descriptor as the page held it.
130
+ * @param providerKey - which provider was written.
131
+ * @param models - the list that was written.
132
+ * @param revision - the revision the service answered with, when it gave one.
133
+ * @returns a new descriptor; the input is not mutated.
134
+ */
135
+ export function withWrittenModels(
136
+ descriptor: SettingsDescriptor,
137
+ providerKey: string,
138
+ models: readonly ModelDraft[],
139
+ revision: number | undefined,
140
+ ): SettingsDescriptor {
141
+ const providers = providersOf(descriptor)
142
+ const provider = providers[providerKey]
143
+ const nextProviders = provider === undefined
144
+ ? providers
145
+ : { ...providers, [providerKey]: { ...provider, models: [...models] } }
146
+ return {
147
+ ...descriptor,
148
+ ...revision === undefined ? {} : { revision },
149
+ value: { ...descriptor.value, providers: nextProviders },
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Read a hand-typed token count: `128K`, `1M`, `128000`, `1,000,000`.
155
+ *
156
+ * The cells show the short form (`1M`), so the same short form has to be
157
+ * accepted back: a field you can see you can also type. Anything that is not a
158
+ * number with an optional K/M suffix returns undefined, which the caller reads
159
+ * as "no manual value" rather than as zero.
160
+ * @param text - what the cell holds.
161
+ * @returns the count, or undefined when the text is not a count.
162
+ */
163
+ export function parseTokenCount(text: string): number | undefined {
164
+ const trimmed = text.trim().replace(/[,_\s]/g, '')
165
+ if (trimmed === '') return undefined
166
+ const match = /^([0-9]+(?:\.[0-9]+)?)([kKmM])?$/.exec(trimmed)
167
+ if (match === null) return undefined
168
+ const amount = Number(match[1])
169
+ if (!Number.isFinite(amount) || amount <= 0) return undefined
170
+ const suffix = match[2]?.toLowerCase()
171
+ if (suffix === 'k') return Math.round(amount * 1000)
172
+ if (suffix === 'm') return Math.round(amount * 1_000_000)
173
+ return Math.round(amount)
174
+ }
175
+
176
+ /**
177
+ * Overlay hand-typed fields on the ones the catalog gave.
178
+ *
179
+ * The page shows numbers a person can change, because the catalog is not
180
+ * always right and sometimes has nothing at all: a rate-limited proxy route
181
+ * may need a smaller window than the upstream model advertises, and a model
182
+ * the catalog never heard of gets its whole entry typed by hand. Manual values
183
+ * therefore win, and they are applied even when "overwrite" is off — that
184
+ * switch governs catalog values replacing what the user already stored, not
185
+ * values the user just typed.
186
+ * @param base - catalog fields, when there were any.
187
+ * @param manual - fields typed in the table.
188
+ * @returns the fields a write would use.
189
+ */
190
+ export function mergeFields(
191
+ base: CapabilityFields | undefined,
192
+ manual: CapabilityFields | undefined,
193
+ ): CapabilityFields | undefined {
194
+ if (base === undefined) return manual
195
+ if (manual === undefined) return base
196
+ return { ...base, ...manual }
197
+ }
package/src/index.ts CHANGED
@@ -38,14 +38,15 @@ interface Registrar {
38
38
  }
39
39
 
40
40
  /** Resolve one id against the catalog into a preview row. */
41
- function previewOne(catalog: Catalog, id: string, aliases: Readonly<Record<string, string>>): PreviewRow {
42
- const match = matchModel(catalog, id, aliases)
43
- if (match === undefined) return { id, reason: 'not in the models.dev catalog' }
41
+ function previewOne(catalog: Catalog, id: string, aliases: Readonly<Record<string, string>>, name = ''): PreviewRow {
42
+ const named = name === '' ? {} : { name }
43
+ const match = matchModel(catalog, id, aliases, name)
44
+ if (match === undefined) return { id, ...named, reason: 'not in the models.dev catalog' }
44
45
  const entry = catalog.byId.get(match.modelId)?.find(candidate => candidate.provider === match.provider)
45
- if (entry === undefined) return { id, match, reason: 'catalog entry vanished between match and read' }
46
+ if (entry === undefined) return { id, ...named, match, reason: 'catalog entry vanished between match and read' }
46
47
  const fields = capabilitiesOf(entry)
47
- if (Object.keys(fields).length === 0) return { id, match, reason: 'catalog entry states no capability facts' }
48
- return { id, match, fields }
48
+ if (Object.keys(fields).length === 0) return { id, ...named, match, reason: 'catalog entry states no capability facts' }
49
+ return { id, ...named, match, fields }
49
50
  }
50
51
 
51
52
  /** Serve one `preview` request. */
@@ -53,11 +54,12 @@ async function preview(request: PreviewRequest, signal: AbortSignal): Promise<Pr
53
54
  const ids = Array.isArray(request.ids) ? request.ids.filter(id => typeof id === 'string' && id.length > 0) : []
54
55
  const catalog = await loadCatalog({ refresh: request.refresh === true, proxyUrl: request.proxyUrl }, signal)
55
56
  const aliases = request.aliases ?? {}
57
+ const names = request.names ?? {}
56
58
  return {
57
59
  fetchedAt: catalog.fetchedAt,
58
60
  catalogModels: catalog.modelCount,
59
61
  ...catalog.stale === true ? { stale: true } : {},
60
- rows: ids.map(id => previewOne(catalog, id, aliases)),
62
+ rows: ids.map(id => previewOne(catalog, id, aliases, typeof names[id] === 'string' ? names[id] : '')),
61
63
  }
62
64
  }
63
65
 
package/src/mapping.ts CHANGED
@@ -54,7 +54,9 @@ function reasoningOf(entry: CatalogEntry): Record<string, string> | false | unde
54
54
  * Read every capability the catalog states for one entry.
55
55
  *
56
56
  * The catalog's display name is deliberately not returned: this plugin fills
57
- * facts, it never renames a model entry.
57
+ * facts, it never renames a model entry. Renaming has its own section, and the
58
+ * two must stay separable — a fill that also renamed would make the redirect
59
+ * undoable.
58
60
  * @param entry - the matched catalog entry.
59
61
  * @returns only the fields the catalog actually declares.
60
62
  */