dsh-cliproxyapi-pro 1.9.0 → 1.10.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.en.md +24 -408
  3. package/README.md +24 -408
  4. package/lib/client.js +265 -27
  5. package/lib/host/accounts.js +178 -0
  6. package/lib/host/apply/agent-tool.js +406 -0
  7. package/lib/host/apply/commands.js +122 -0
  8. package/lib/host/apply/controller.js +121 -0
  9. package/lib/host/apply/http-routes.js +273 -0
  10. package/lib/host/apply/image-jobs.js +171 -0
  11. package/lib/host/apply/index.js +41 -0
  12. package/lib/host/apply/interpret.js +72 -0
  13. package/lib/host/apply/lifecycle.js +50 -0
  14. package/lib/host/apply/media-failures.js +68 -0
  15. package/lib/host/apply/media-service.js +202 -0
  16. package/lib/host/apply/quota-service.js +42 -0
  17. package/lib/host/apply/references.js +43 -0
  18. package/lib/host/apply/session-status.js +104 -0
  19. package/lib/host/apply/state.js +78 -0
  20. package/lib/host/apply/updates.js +55 -0
  21. package/lib/host/apply/video-command.js +152 -0
  22. package/lib/host/apply/video-edit.js +253 -0
  23. package/lib/host/apply/video-jobs.js +206 -0
  24. package/lib/host/apply-utils.js +39 -0
  25. package/lib/host/config.js +210 -0
  26. package/lib/host/controller.js +464 -0
  27. package/lib/host/discovery.js +301 -0
  28. package/lib/host/http-gate.js +144 -0
  29. package/lib/host/model-info.js +363 -0
  30. package/lib/host/model-names.js +152 -0
  31. package/lib/host/models.js +75 -0
  32. package/lib/host/mount-guard.js +56 -0
  33. package/lib/host/recommend.js +367 -0
  34. package/lib/host/routes.js +165 -0
  35. package/lib/host/runtime.js +471 -0
  36. package/lib/host/state-store.js +39 -0
  37. package/lib/host/status-text.js +93 -0
  38. package/lib/index.js +18 -4417
  39. package/lib/media/agent-tool.js +255 -0
  40. package/lib/media/choice.js +83 -0
  41. package/lib/media/classify.js +65 -0
  42. package/lib/media/codec/fit.js +76 -0
  43. package/lib/media/codec/jpeg.js +158 -0
  44. package/lib/media/codec/png.js +102 -0
  45. package/lib/media/commands/parsing.js +269 -0
  46. package/lib/media/constants.js +46 -0
  47. package/lib/media/diagnose.js +134 -0
  48. package/lib/media/images.js +165 -0
  49. package/lib/media/index.js +29 -0
  50. package/lib/media/interpret.js +126 -0
  51. package/lib/media/job-store.js +99 -0
  52. package/lib/media/mp4.js +44 -0
  53. package/lib/media/output-files.js +59 -0
  54. package/lib/media/session-store.js +293 -0
  55. package/lib/media/settings.js +255 -0
  56. package/lib/media/util.js +45 -0
  57. package/lib/media/video.js +326 -0
  58. package/lib/quota/auth-state.js +33 -0
  59. package/lib/quota/constants.js +86 -0
  60. package/lib/quota/controller.js +467 -0
  61. package/lib/quota/helpers.js +325 -0
  62. package/lib/quota/index.js +19 -0
  63. package/lib/quota/management.js +216 -0
  64. package/lib/quota/matching.js +143 -0
  65. package/lib/quota/parsers.js +352 -0
  66. package/lib/quota/probes/billing.js +80 -0
  67. package/lib/quota/probes/google.js +120 -0
  68. package/lib/quota/probes/oauth.js +27 -0
  69. package/lib/quota/probes/plugin.js +18 -0
  70. package/lib/updater/constants.js +23 -0
  71. package/lib/updater/errors.js +8 -0
  72. package/lib/updater/index.js +11 -0
  73. package/lib/updater/registry.js +83 -0
  74. package/lib/updater/settings.js +45 -0
  75. package/lib/updater/store.js +23 -0
  76. package/lib/updater/updater.js +148 -0
  77. package/lib/updater/verify.js +110 -0
  78. package/lib/updater/version.js +31 -0
  79. package/locale/en.json +1 -1
  80. package/locale/zh.json +1 -1
  81. package/package.json +6 -9
  82. package/lib/media.js +0 -2542
  83. package/lib/quota.js +0 -1748
  84. package/lib/updater.js +0 -443
@@ -0,0 +1,363 @@
1
+ // Optional online model facts from public catalogs: models.dev (lines, release
2
+ // dates, status, limits, prices) and OpenRouter (capability index, end dates).
3
+ //
4
+ // Download only: plain GETs of public JSON, no key, account, address or model
5
+ // list is ever sent. A compact index is cached in `model-info.json` next to the
6
+ // account state and refreshed at most daily; without it recommendations fall
7
+ // back to the catalog's own facts. Switched by the global `onlineModelInfo`.
8
+
9
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
10
+ import { dirname } from "node:path";
11
+ import { matchKeys } from "./model-names.js";
12
+
13
+ export const MODEL_INFO_SOURCES = {
14
+ modelsDev: { url: "https://models.dev/api.json", maxBytes: 32 * 1024 * 1024 },
15
+ openRouter: { url: "https://openrouter.ai/api/v1/models", maxBytes: 16 * 1024 * 1024 },
16
+ };
17
+ export const MODEL_INFO_TTL_MS = 24 * 60 * 60 * 1000;
18
+ export const MODEL_INFO_RETRY_MS = 60 * 60 * 1000;
19
+ export const MODEL_INFO_TIMEOUT_MS = 30_000;
20
+ export const MODEL_INFO_CACHE_VERSION = 1;
21
+ const MAX_ENTRIES = 20_000;
22
+
23
+ const text = (value, max = 80) => (typeof value === "string" && value.trim() !== "" ? value.trim().slice(0, max) : undefined);
24
+ const count = (value) => (typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined);
25
+ const amount = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
26
+ const day = (value) => (typeof value === "string" && /^\d{4}-\d{2}(-\d{2})?/.test(value) ? value.slice(0, 10) : undefined);
27
+
28
+ function compact(entry) {
29
+ return Object.fromEntries(Object.entries(entry).filter(([, v]) => v !== undefined));
30
+ }
31
+
32
+ /**
33
+ * models.dev `api.json` → `[{ id, rank, family, released, status, context, output, costOutput }]`.
34
+ * `rank` 0 = the model's canonical provider, 1 = another first-party
35
+ * provider, 2 = a reseller; the best rank wins a duplicate id.
36
+ */
37
+ export function parseModelsDev(payload) {
38
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) throw new Error("models.dev: not an object");
39
+ const providers = Object.entries(payload).filter(([, p]) => typeof p?.models === "object" && p.models !== null);
40
+ const firstParty = new Set();
41
+ for (const [, provider] of providers) {
42
+ for (const model of Object.values(provider.models)) {
43
+ const canonical = text(model?.canonical_model_id, 200);
44
+ if (canonical?.includes("/")) firstParty.add(canonical.split("/")[0]);
45
+ }
46
+ }
47
+ const out = [];
48
+ for (const [providerId, provider] of providers) {
49
+ for (const [id, model] of Object.entries(provider.models)) {
50
+ if (typeof model !== "object" || model === null || out.length >= MAX_ENTRIES) continue;
51
+ const canonical = text(model.canonical_model_id, 200);
52
+ out.push(compact({
53
+ id: text(model.id, 200) ?? id,
54
+ rank: canonical?.startsWith(`${providerId}/`) ? 0 : firstParty.has(providerId) ? 1 : 2,
55
+ family: text(model.family),
56
+ released: day(model.release_date),
57
+ status: text(model.status, 20),
58
+ context: count(model.limit?.context),
59
+ output: count(model.limit?.output),
60
+ costOutput: amount(model.cost?.output),
61
+ }));
62
+ }
63
+ }
64
+ if (out.length === 0) throw new Error("models.dev: no models");
65
+ // Resellers repeat first-party models; keep one entry per spelling (best rank first).
66
+ const best = new Map();
67
+ for (const entry of out) {
68
+ const key = matchKeys(entry.id)?.exact ?? `id:${entry.id}`;
69
+ const held = best.get(key);
70
+ if (held === undefined || entry.rank < held.rank) best.set(key, entry);
71
+ }
72
+ return [...best.values()];
73
+ }
74
+
75
+ /** OpenRouter `/api/v1/models` → `[{ id, rank, released, expires, context, intelligence }]`. */
76
+ export function parseOpenRouter(payload) {
77
+ if (!Array.isArray(payload?.data)) throw new Error("openrouter: no data array");
78
+ const out = [];
79
+ for (const model of payload.data) {
80
+ const id = text(model?.id, 200);
81
+ // `:batch`, `:free`... are billing variants of the same model.
82
+ if (id === undefined || id.includes(":") || out.length >= MAX_ENTRIES) continue;
83
+ const created = count(model.created);
84
+ out.push(compact({
85
+ id,
86
+ rank: 0,
87
+ released: created === undefined ? undefined : new Date(created * 1000).toISOString().slice(0, 10),
88
+ expires: day(model.expiration_date),
89
+ context: count(model.context_length),
90
+ intelligence: amount(model.benchmarks?.artificial_analysis?.intelligence_index),
91
+ }));
92
+ }
93
+ if (out.length === 0) throw new Error("openrouter: no models");
94
+ return out;
95
+ }
96
+
97
+ /** Exact and loose lookup maps over one source's entries. */
98
+ export function buildIndex(entries = []) {
99
+ const exact = new Map();
100
+ const loose = new Map();
101
+ for (const entry of entries) {
102
+ const keys = matchKeys(entry.id);
103
+ if (keys === undefined) continue;
104
+ const rank = Number.isInteger(entry.rank) ? entry.rank : 2;
105
+ const held = exact.get(keys.exact);
106
+ if (held === undefined || rank < held.rank) exact.set(keys.exact, { entry, rank });
107
+ // A loose key prefers the plain model over its variants, then the better source rank.
108
+ const score = (keys.hasVariant ? 10 : 0) + rank;
109
+ const looseHeld = loose.get(keys.loose);
110
+ if (looseHeld === undefined || score < looseHeld.score) loose.set(keys.loose, { entry, score });
111
+ }
112
+ return { exact, loose };
113
+ }
114
+
115
+ function find(index, texts) {
116
+ const parsed = texts.map((value) => matchKeys(value)).filter(Boolean);
117
+ for (const keys of parsed) {
118
+ const hit = index.exact.get(keys.exact);
119
+ if (hit !== undefined) return { entry: hit.entry, exact: true };
120
+ }
121
+ for (const keys of parsed) {
122
+ const hit = index.loose.get(keys.loose);
123
+ if (hit !== undefined) return { entry: hit.entry, exact: false };
124
+ }
125
+ return undefined;
126
+ }
127
+
128
+ /**
129
+ * Facts about one catalog model from both sources, or undefined.
130
+ * `exact` is true when the id matched without dropping variant words, the
131
+ * only case in which limits may be used for the model itself.
132
+ */
133
+ export function lookupModel(indexes, model) {
134
+ const texts = [model.id, ...(typeof model.name === "string" ? [model.name] : [])];
135
+ const md = indexes.modelsDev === undefined ? undefined : find(indexes.modelsDev, texts);
136
+ const or = indexes.openRouter === undefined ? undefined : find(indexes.openRouter, texts);
137
+ if (md === undefined && or === undefined) return undefined;
138
+ const a = md?.entry ?? {};
139
+ const b = or?.entry ?? {};
140
+ return compact({
141
+ family: a.family,
142
+ released: a.released ?? b.released,
143
+ status: a.status,
144
+ expires: b.expires,
145
+ context: a.context ?? b.context,
146
+ output: a.output,
147
+ costOutput: a.costOutput,
148
+ intelligence: b.intelligence,
149
+ exact: md !== undefined ? md.exact : or.exact,
150
+ });
151
+ }
152
+
153
+ /** Upper bound for an output limit taken from online info (channels often cap lower). */
154
+ export const ONLINE_MAX_TOKENS_CAP = 128_000;
155
+
156
+ /**
157
+ * Fill limits the CPA catalog left out from an exact online match. Catalog
158
+ * values always win; the filled fields are listed in `onlineLimits`.
159
+ */
160
+ export function withOnlineLimits(model, info) {
161
+ if (info?.exact !== true) return model;
162
+ const filled = [];
163
+ const next = { ...model };
164
+ if (next.contextWindow === undefined && info.context !== undefined) {
165
+ next.contextWindow = Math.min(info.context, 10_000_000);
166
+ filled.push("contextWindow");
167
+ }
168
+ if (next.maxTokens === undefined && info.output !== undefined) {
169
+ next.maxTokens = Math.min(info.output, ONLINE_MAX_TOKENS_CAP, next.contextWindow ?? Infinity);
170
+ filled.push("maxTokens");
171
+ }
172
+ return filled.length === 0 ? model : { ...next, onlineLimits: filled };
173
+ }
174
+
175
+ export async function fetchSource(fetchImpl, source, options = {}) {
176
+ const signal = AbortSignal.timeout(options.timeoutMs ?? MODEL_INFO_TIMEOUT_MS);
177
+ const response = await fetchImpl(source.url, {
178
+ method: "GET",
179
+ headers: { Accept: "application/json", ...(options.etag ? { "If-None-Match": options.etag } : {}) },
180
+ signal: options.signal === undefined ? signal : AbortSignal.any([options.signal, signal]),
181
+ });
182
+ if (response.status === 304) return { notModified: true };
183
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
184
+ const declared = Number(response.headers?.get?.("content-length"));
185
+ if (Number.isFinite(declared) && declared > source.maxBytes) throw new Error("response too large");
186
+ const body = await response.text();
187
+ if (Buffer.byteLength(body) > source.maxBytes) throw new Error("response too large");
188
+ let json;
189
+ try {
190
+ json = JSON.parse(body);
191
+ } catch {
192
+ throw new Error("not valid JSON");
193
+ }
194
+ return { json, etag: text(response.headers?.get?.("etag"), 200) };
195
+ }
196
+
197
+ export function loadModelInfoCache(path) {
198
+ try {
199
+ const raw = JSON.parse(readFileSync(path, "utf8"));
200
+ if (raw?.version !== MODEL_INFO_CACHE_VERSION || typeof raw.sources !== "object" || raw.sources === null) return { sources: {} };
201
+ const sources = {};
202
+ for (const name of Object.keys(MODEL_INFO_SOURCES)) {
203
+ const s = raw.sources[name];
204
+ if (typeof s !== "object" || s === null) continue;
205
+ sources[name] = {
206
+ ...(Number.isFinite(s.fetchedAt) ? { fetchedAt: s.fetchedAt } : {}),
207
+ ...(Number.isFinite(s.attemptedAt) ? { attemptedAt: s.attemptedAt } : {}),
208
+ ...(typeof s.etag === "string" ? { etag: s.etag } : {}),
209
+ ...(typeof s.error === "string" ? { error: s.error.slice(0, 200) } : {}),
210
+ models: Array.isArray(s.models) ? s.models.filter((m) => typeof m?.id === "string").slice(0, MAX_ENTRIES) : [],
211
+ };
212
+ }
213
+ return { sources };
214
+ } catch {
215
+ return { sources: {} };
216
+ }
217
+ }
218
+
219
+ export function saveModelInfoCache(path, cache) {
220
+ try {
221
+ mkdirSync(dirname(path), { recursive: true });
222
+ const tmp = `${path}.${Date.now().toString(36)}.tmp`;
223
+ writeFileSync(tmp, JSON.stringify({ version: MODEL_INFO_CACHE_VERSION, sources: cache.sources }), "utf8");
224
+ renameSync(tmp, path);
225
+ } catch {}
226
+ }
227
+
228
+ const PARSERS = { modelsDev: parseModelsDev, openRouter: parseOpenRouter };
229
+
230
+ /**
231
+ * The online model-info service of one activation.
232
+ * @param options.cachePath - `model-info.json`.
233
+ * @param options.enabled - `() => boolean`, the global `onlineModelInfo`.
234
+ * @param options.fetch / options.now - injectable for tests.
235
+ * @param options.onChange - called after new data arrived.
236
+ */
237
+ export function createModelInfo(options) {
238
+ // Resolved per request so a proxy plugin's patched global fetch applies.
239
+ const fetchImpl = options.fetch ?? ((...args) => globalThis.fetch(...args));
240
+ const now = options.now ?? Date.now;
241
+ const controller = new AbortController();
242
+ let cache = loadModelInfoCache(options.cachePath);
243
+ let indexes = {};
244
+ const rebuild = () => {
245
+ indexes = Object.fromEntries(
246
+ Object.entries(cache.sources).filter(([, s]) => s.models.length > 0).map(([name, s]) => [name, buildIndex(s.models)])
247
+ );
248
+ };
249
+ rebuild();
250
+ let running;
251
+ let lookups = new WeakMap();
252
+
253
+ const enabled = () => {
254
+ try {
255
+ return options.enabled?.() !== false;
256
+ } catch {
257
+ return true;
258
+ }
259
+ };
260
+
261
+ const due = (source, force) => {
262
+ if (force) return true;
263
+ const t = now();
264
+ if (source?.fetchedAt !== undefined && t - source.fetchedAt < MODEL_INFO_TTL_MS) return false;
265
+ return source?.attemptedAt === undefined || t - source.attemptedAt >= MODEL_INFO_RETRY_MS;
266
+ };
267
+
268
+ const runRefresh = async (force) => {
269
+ let changed = false;
270
+ for (const [name, source] of Object.entries(MODEL_INFO_SOURCES)) {
271
+ const previous = cache.sources[name];
272
+ if (!due(previous, force) || controller.signal.aborted) continue;
273
+ const attemptedAt = now();
274
+ try {
275
+ const result = await fetchSource(fetchImpl, source, { etag: previous?.models.length ? previous.etag : undefined, signal: controller.signal });
276
+ if (result.notModified) {
277
+ const { error: _stale, ...kept } = previous;
278
+ cache.sources[name] = { ...kept, fetchedAt: attemptedAt, attemptedAt };
279
+ } else {
280
+ cache.sources[name] = {
281
+ fetchedAt: attemptedAt,
282
+ attemptedAt,
283
+ ...(result.etag === undefined ? {} : { etag: result.etag }),
284
+ models: PARSERS[name](result.json),
285
+ };
286
+ changed = true;
287
+ }
288
+ } catch (error) {
289
+ if (controller.signal.aborted) return changed;
290
+ const message = error instanceof Error ? error.message : String(error);
291
+ cache.sources[name] = { ...(previous ?? { models: [] }), attemptedAt, error: message.slice(0, 200) };
292
+ options.logger?.warn?.(`dsh-cliproxyapi: online model info from ${source.url} unavailable (${message}); recommendations use the catalog`);
293
+ }
294
+ saveModelInfoCache(options.cachePath, cache);
295
+ }
296
+ if (changed) {
297
+ rebuild();
298
+ lookups = new WeakMap();
299
+ }
300
+ return changed;
301
+ };
302
+
303
+ const service = {
304
+ /** Fetch the sources that are due (all with `force`); no-op while switched off. */
305
+ refresh({ force = false } = {}) {
306
+ if (!enabled() || controller.signal.aborted) return Promise.resolve(false);
307
+ if (running !== undefined) return running;
308
+ running = runRefresh(force)
309
+ .then((changed) => {
310
+ if (changed) options.onChange?.();
311
+ return changed;
312
+ })
313
+ .finally(() => {
314
+ running = undefined;
315
+ });
316
+ return running;
317
+ },
318
+
319
+ /** Resolve once some data is available, a first download finished, or after `timeoutMs`. */
320
+ async ready(timeoutMs = 4000) {
321
+ if (!enabled() || Object.keys(indexes).length > 0) return;
322
+ const pending = running ?? service.refresh();
323
+ let timer;
324
+ await Promise.race([pending.catch(() => {}), new Promise((resolve) => { timer = setTimeout(resolve, timeoutMs); })]);
325
+ clearTimeout(timer);
326
+ },
327
+
328
+ /** Online facts for one model (memoized per model object), or undefined while switched off. */
329
+ lookup(model) {
330
+ if (!enabled() || model === null || typeof model !== "object") return undefined;
331
+ if (lookups.has(model)) return lookups.get(model);
332
+ const info = lookupModel(indexes, model);
333
+ lookups.set(model, info);
334
+ return info;
335
+ },
336
+
337
+ status() {
338
+ const on = enabled();
339
+ const sources = {};
340
+ for (const name of Object.keys(MODEL_INFO_SOURCES)) {
341
+ const s = cache.sources[name];
342
+ sources[name] = {
343
+ models: s?.models.length ?? 0,
344
+ ...(s?.fetchedAt === undefined ? {} : { fetchedAt: new Date(s.fetchedAt).toISOString() }),
345
+ // A successful download replaces the record, so a kept error is the latest attempt's.
346
+ ...(s?.error === undefined ? {} : { error: s.error }),
347
+ };
348
+ }
349
+ const anyData = Object.values(sources).some((s) => s.models > 0);
350
+ const anyError = Object.values(sources).some((s) => s.error !== undefined);
351
+ return {
352
+ enabled: on,
353
+ state: !on ? "off" : running !== undefined ? "loading" : anyError && !anyData ? "error" : anyData ? (anyError ? "partial" : "ready") : "idle",
354
+ sources,
355
+ };
356
+ },
357
+
358
+ dispose() {
359
+ controller.abort(new Error("dsh-cliproxyapi disposed"));
360
+ },
361
+ };
362
+ return service;
363
+ }
@@ -0,0 +1,152 @@
1
+ // Model id tokenization shared by recommendations and online model-info matching.
2
+ //
3
+ // An id such as `devin/claude-opus-4-6-thinking` reads as: an optional vendor
4
+ // prefix (`devin/`), product-line words (`claude`, `opus`), a version run
5
+ // (`4-6`) and variant words (`thinking`). The words are vocabulary, never model
6
+ // ids, so no catalog id is hard-coded here.
7
+
8
+ /** Words that select a variant of a model, not a different product line. */
9
+ export const VARIANT_WORDS = new Set([
10
+ "thinking", "reasoning", "non", "nonreasoning", "fast", "slow", "preview", "latest", "exp",
11
+ "experimental", "high", "medium", "low", "minimal", "batch", "highspeed", "free", "beta", "alpha",
12
+ "online", "1m", "long", "context",
13
+ ]);
14
+
15
+ /** Words that carry no identity (packaging words and vendor names in opaque ids). */
16
+ export const GENERIC_WORDS = new Set([
17
+ "model", "models", "private", "chat", "the", "google", "anthropic", "openai", "xai", "meta",
18
+ ]);
19
+
20
+ /** Words that mark a lighter tier; used only when no capability data is available. */
21
+ export const LIGHT_WORDS = new Set(["mini", "nano", "lite", "flash", "haiku", "small", "tiny", "air", "lightning"]);
22
+
23
+ /** Lowercase id without vendor prefix (`devin/`) or OpenRouter variant suffix (`:batch`). */
24
+ export function bareId(id) {
25
+ const lower = String(id ?? "").trim().toLowerCase();
26
+ const slash = lower.lastIndexOf("/");
27
+ return (slash >= 0 ? lower.slice(slash + 1) : lower).replace(/:.*$/, "");
28
+ }
29
+
30
+ /** Whether an id carries a vendor prefix such as `devin/`. */
31
+ export function isPrefixed(id) {
32
+ return String(id ?? "").includes("/");
33
+ }
34
+
35
+ function tokens(text) {
36
+ return String(text ?? "")
37
+ .toLowerCase()
38
+ .replace(/\([^)]*\)/g, " ")
39
+ .split(/[^a-z0-9]+/)
40
+ .filter(Boolean);
41
+ }
42
+
43
+ /**
44
+ * Parse one id or display name.
45
+ * @returns `{ words, variants, extras, version }`: line words in order,
46
+ * variant words, other digit-bearing tokens (`120b`) and the version as
47
+ * numbers (dates such as `20250514` or `0309` end it).
48
+ */
49
+ export function parseName(text) {
50
+ const words = [];
51
+ const variants = [];
52
+ const extras = [];
53
+ let version;
54
+ let inRun = false;
55
+ for (const token of tokens(text)) {
56
+ if (/^\d+$/.test(token)) {
57
+ if (version === undefined) {
58
+ version = [];
59
+ inRun = true;
60
+ }
61
+ if (inRun) {
62
+ if (token.length >= 4) inRun = false;
63
+ else version.push(Number(token));
64
+ }
65
+ continue;
66
+ }
67
+ inRun = false;
68
+ if (VARIANT_WORDS.has(token)) {
69
+ variants.push(token);
70
+ continue;
71
+ }
72
+ const alnum = token.match(/^([a-z]+)(\d+)$/);
73
+ if (alnum !== null) {
74
+ // `k3`, `v4`, `o3`: the letters name the line, the digits start the version.
75
+ if (!GENERIC_WORDS.has(alnum[1])) words.push(alnum[1]);
76
+ if (version === undefined) {
77
+ version = [Number(alnum[2])];
78
+ inRun = true;
79
+ }
80
+ continue;
81
+ }
82
+ if (/\d/.test(token)) {
83
+ extras.push(token);
84
+ continue;
85
+ }
86
+ if (!GENERIC_WORDS.has(token)) words.push(token);
87
+ }
88
+ return { words, variants, extras, version: trimVersion(version) };
89
+ }
90
+
91
+ function trimVersion(version) {
92
+ if (version === undefined || version.length === 0) return undefined;
93
+ const out = [...version];
94
+ while (out.length > 1 && out[out.length - 1] === 0) out.pop();
95
+ return out;
96
+ }
97
+
98
+ /**
99
+ * The product line of a model: its line words from the id, or from the
100
+ * display name when the id is opaque (`model_private_12`).
101
+ * @returns `{ key, label, parsed }` or undefined when neither names a line.
102
+ */
103
+ export function modelLine(model) {
104
+ for (const text of [bareId(model.id), model.name]) {
105
+ const line = lineFromText(text);
106
+ if (line !== undefined) return line;
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ /**
112
+ * The line of one id, display name or online family name (`claude-fable`).
113
+ * Single letters split off a version (`k` of `kimi-k3`, `v` of `deepseek-v4`)
114
+ * only count when nothing else names the line (`o` of `o3`).
115
+ */
116
+ export function lineFromText(text) {
117
+ if (typeof text !== "string" || text.trim() === "") return undefined;
118
+ const parsed = parseName(text);
119
+ const unique = [...new Set(parsed.words)];
120
+ const named = unique.filter((word) => word.length > 1);
121
+ const words = named.length > 0 ? named : unique;
122
+ if (words.length === 0) return undefined;
123
+ return { key: [...words].sort().join("-"), label: words.join("-"), parsed };
124
+ }
125
+
126
+ /**
127
+ * Lookup keys for matching an id against online catalogs: `exact` keeps
128
+ * variant words (`claude-opus-4-6-1m`), `loose` drops them. Word order and
129
+ * version separators are ignored (`claude-5-fable` = `claude-fable-5`,
130
+ * `5.2` = `5-2`); version order is kept (`gpt-5.4` ≠ `gpt-4.5`).
131
+ */
132
+ export function matchKeys(text) {
133
+ const parsed = parseName(bareId(text));
134
+ if (parsed.words.length === 0) return undefined;
135
+ const base = [...new Set([...parsed.words, ...parsed.extras])].sort();
136
+ const version = (parsed.version ?? []).join(".");
137
+ const loose = `${base.join("-")}|${version}`;
138
+ const exact = parsed.variants.length === 0 ? loose : `${[...new Set([...base, ...parsed.variants])].sort().join("-")}|${version}`;
139
+ return { exact, loose, hasVariant: parsed.variants.length > 0 };
140
+ }
141
+
142
+ /** Compare version arrays, newest first (missing parts count as 0). */
143
+ export function compareVersionsDesc(a, b) {
144
+ const left = a ?? [];
145
+ const right = b ?? [];
146
+ const length = Math.max(left.length, right.length);
147
+ for (let i = 0; i < length; i += 1) {
148
+ const diff = (right[i] ?? 0) - (left[i] ?? 0);
149
+ if (diff !== 0) return diff;
150
+ }
151
+ return 0;
152
+ }
@@ -0,0 +1,75 @@
1
+ // Chat model filtering, families and version ordering (recommendations: recommend.js).
2
+
3
+ export function splitPrefixes(csv) {
4
+ if (typeof csv !== "string" || csv.trim() === "") return [];
5
+ return csv
6
+ .split(",")
7
+ .map((s) => s.trim().toLowerCase())
8
+ .filter(Boolean);
9
+ }
10
+
11
+ export function filterModels(models, config) {
12
+ const includes = splitPrefixes(config.includePrefix);
13
+ const excludes = splitPrefixes(config.excludePrefix);
14
+ const selectedSet =
15
+ Array.isArray(config.selectedModels) && config.selectedModels.length > 0
16
+ ? new Set(config.selectedModels)
17
+ : null;
18
+
19
+ return models.filter((m) => {
20
+ if (selectedSet !== null && !selectedSet.has(m.id)) {
21
+ return false;
22
+ }
23
+ const idLower = m.id.toLowerCase();
24
+ if (includes.length > 0 && !includes.some((p) => idLower.startsWith(p) || idLower.includes(p))) {
25
+ return false;
26
+ }
27
+ if (excludes.length > 0 && excludes.some((p) => idLower.startsWith(p) || idLower.includes(p))) {
28
+ return false;
29
+ }
30
+ return true;
31
+ });
32
+ }
33
+
34
+ /** Vendor families recognized by name; others are named by their leading text. */
35
+ export const KNOWN_FAMILY = /^(gpt-oss|gemini|claude|gpt|grok|deepseek|qwen|glm|kimi|minimax|mistral|llama|swe|o(?=\d))/;
36
+
37
+ export function modelFamily(model) {
38
+ // "Inkling (Devin)": a parenthesized channel note is not part of the family.
39
+ const label = String(model.name ?? model.id).replace(/\s*\([^)]*\)/g, "").trim().toLowerCase() || String(model.id).toLowerCase();
40
+ const known = label.match(KNOWN_FAMILY)?.[1];
41
+ if (known !== undefined) return known;
42
+ return label.split(/[\s_/-]*\d/, 1)[0]?.replace(/[\s_/-]+$/, "") || label;
43
+ }
44
+
45
+ export function modelVersion(model) {
46
+ const labels = [model.name, model.id];
47
+ for (const label of labels) {
48
+ if (label === undefined) continue;
49
+ const match = label.match(/(?:^|[^\d])(\d+(?:[.-]\d+)*)/);
50
+ if (match?.[1] !== undefined) return match[1].split(/[.-]/).map(Number);
51
+ }
52
+ return [];
53
+ }
54
+
55
+ export function compareVersionDescending(left, right) {
56
+ const a = modelVersion(left);
57
+ const b = modelVersion(right);
58
+ const length = Math.max(a.length, b.length);
59
+ for (let i = 0; i < length; i += 1) {
60
+ const diff = (b[i] ?? 0) - (a[i] ?? 0);
61
+ if (diff !== 0) return diff;
62
+ }
63
+ return 0;
64
+ }
65
+
66
+ export function sortModelsNewestFirst(models) {
67
+ const groups = new Map();
68
+ for (const model of models) {
69
+ const family = modelFamily(model);
70
+ const group = groups.get(family);
71
+ if (group === undefined) groups.set(family, [model]);
72
+ else group.push(model);
73
+ }
74
+ return [...groups.values()].flatMap((group) => [...group].sort(compareVersionDescending));
75
+ }
@@ -0,0 +1,56 @@
1
+ // Mount-once coordination across overlapping plugin HMR generations.
2
+
3
+
4
+
5
+ export const MOUNTED = Symbol.for("dsh-web.mounted-plugins");
6
+ export const WAITERS = Symbol.for("dsh-web.mounted-plugins.waiters");
7
+
8
+ export function mountedSet() {
9
+ const existing = globalThis[MOUNTED];
10
+ if (existing instanceof Set) return existing;
11
+ const created = new Set();
12
+ globalThis[MOUNTED] = created;
13
+ return created;
14
+ }
15
+
16
+ export function mountWaiters() {
17
+ return (globalThis[WAITERS] ??= new Map());
18
+ }
19
+
20
+ export function mountOnce(packageName, fn) {
21
+ const mount = (...args) => {
22
+ const mounted = mountedSet();
23
+ const ctx = args[0];
24
+ if (mounted.has(packageName)) {
25
+ const waiters = mountWaiters();
26
+ const queue = waiters.get(packageName) ?? [];
27
+ let alive = true;
28
+ const pending = {
29
+ run: () => {
30
+ if (alive) mount(...args);
31
+ },
32
+ };
33
+ ctx?.effect?.(() => () => {
34
+ alive = false;
35
+ const idx = queue.indexOf(pending);
36
+ if (idx >= 0) queue.splice(idx, 1);
37
+ });
38
+ queue.push(pending);
39
+ waiters.set(packageName, queue);
40
+ return;
41
+ }
42
+ mounted.add(packageName);
43
+ ctx?.effect?.(() => () => {
44
+ mounted.delete(packageName);
45
+ const waiters = mountWaiters();
46
+ const queue = waiters.get(packageName);
47
+ if (queue === undefined) return;
48
+ waiters.delete(packageName);
49
+ for (const waiter of queue.splice(0)) {
50
+ queueMicrotask(() => waiter.run());
51
+ }
52
+ });
53
+ return fn(...args);
54
+ };
55
+ return mount;
56
+ }