dsh-cliproxyapi-pro 1.9.0 → 1.9.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.en.md +23 -407
  3. package/README.md +23 -407
  4. package/lib/client.js +46 -20
  5. package/lib/host/accounts.js +176 -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 +105 -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 +34 -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 +205 -0
  26. package/lib/host/controller.js +435 -0
  27. package/lib/host/discovery.js +295 -0
  28. package/lib/host/http-gate.js +144 -0
  29. package/lib/host/models.js +102 -0
  30. package/lib/host/mount-guard.js +56 -0
  31. package/lib/host/routes.js +165 -0
  32. package/lib/host/runtime.js +445 -0
  33. package/lib/host/state-store.js +39 -0
  34. package/lib/host/status-text.js +93 -0
  35. package/lib/index.js +17 -4417
  36. package/lib/media/agent-tool.js +255 -0
  37. package/lib/media/choice.js +83 -0
  38. package/lib/media/classify.js +65 -0
  39. package/lib/media/codec/fit.js +76 -0
  40. package/lib/media/codec/jpeg.js +158 -0
  41. package/lib/media/codec/png.js +102 -0
  42. package/lib/media/commands/parsing.js +269 -0
  43. package/lib/media/constants.js +46 -0
  44. package/lib/media/diagnose.js +134 -0
  45. package/lib/media/images.js +165 -0
  46. package/lib/media/index.js +29 -0
  47. package/lib/media/interpret.js +126 -0
  48. package/lib/media/job-store.js +99 -0
  49. package/lib/media/mp4.js +44 -0
  50. package/lib/media/output-files.js +59 -0
  51. package/lib/media/session-store.js +293 -0
  52. package/lib/media/settings.js +255 -0
  53. package/lib/media/util.js +45 -0
  54. package/lib/media/video.js +326 -0
  55. package/lib/quota/auth-state.js +33 -0
  56. package/lib/quota/constants.js +86 -0
  57. package/lib/quota/controller.js +467 -0
  58. package/lib/quota/helpers.js +325 -0
  59. package/lib/quota/index.js +19 -0
  60. package/lib/quota/management.js +216 -0
  61. package/lib/quota/matching.js +143 -0
  62. package/lib/quota/parsers.js +352 -0
  63. package/lib/quota/probes/billing.js +80 -0
  64. package/lib/quota/probes/google.js +120 -0
  65. package/lib/quota/probes/oauth.js +27 -0
  66. package/lib/quota/probes/plugin.js +18 -0
  67. package/lib/updater/constants.js +23 -0
  68. package/lib/updater/errors.js +8 -0
  69. package/lib/updater/index.js +11 -0
  70. package/lib/updater/registry.js +83 -0
  71. package/lib/updater/settings.js +45 -0
  72. package/lib/updater/store.js +23 -0
  73. package/lib/updater/updater.js +148 -0
  74. package/lib/updater/verify.js +110 -0
  75. package/lib/updater/version.js +31 -0
  76. package/locale/en.json +1 -1
  77. package/locale/zh.json +1 -1
  78. package/package.json +6 -9
  79. package/lib/media.js +0 -2542
  80. package/lib/quota.js +0 -1748
  81. package/lib/updater.js +0 -443
@@ -0,0 +1,295 @@
1
+ // CPA candidate probing, bounded catalog parsing and plain-listing enrichment.
2
+
3
+ import { detectMediaKind } from "../media/index.js";
4
+ import { DEFAULT_PROBE_TIMEOUT_MS, LOCAL_CANDIDATES, MAX_CATALOG_BYTES, REASONING_LEVELS } from "./config.js";
5
+
6
+ export function positiveInteger(value) {
7
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
8
+ }
9
+
10
+ export function firstPositiveInteger(source, fields) {
11
+ for (const field of fields) {
12
+ const value = positiveInteger(source[field]);
13
+ if (value !== undefined) return value;
14
+ }
15
+ return undefined;
16
+ }
17
+
18
+ export function stringArray(value) {
19
+ if (!Array.isArray(value)) return [];
20
+ return [
21
+ ...new Set(
22
+ value
23
+ .filter((item) => typeof item === "string")
24
+ .map((item) => item.trim())
25
+ .filter(Boolean)
26
+ ),
27
+ ];
28
+ }
29
+
30
+ export function catalogArray(payload) {
31
+ if (typeof payload !== "object" || payload === null) return undefined;
32
+ if (Array.isArray(payload.models)) return payload.models;
33
+ if (Array.isArray(payload.data)) return payload.data;
34
+ return undefined;
35
+ }
36
+
37
+ export function rawReasoningEfforts(value) {
38
+ if (!Array.isArray(value)) return [];
39
+ return value
40
+ .map((item) =>
41
+ typeof item === "string"
42
+ ? item
43
+ : typeof item === "object" && item !== null && typeof item.effort === "string"
44
+ ? item.effort
45
+ : ""
46
+ )
47
+ .map((raw) => raw.trim().toLowerCase())
48
+ .filter(Boolean);
49
+ }
50
+
51
+ export function parseReasoningLevels(value) {
52
+ const levels = [];
53
+ for (const normalized of rawReasoningEfforts(value)) {
54
+ const mapped =
55
+ normalized === "none" ? "off" : normalized === "ultra" ? "max" : normalized;
56
+ if (REASONING_LEVELS.includes(mapped) && !levels.includes(mapped)) {
57
+ levels.push(mapped);
58
+ }
59
+ }
60
+ return levels;
61
+ }
62
+
63
+ /**
64
+ * Wire spellings that differ from the DSH level name: a catalog offering only
65
+ * `ultra` sends `ultra` for DSH `max`; one also offering `max` keeps `max`.
66
+ */
67
+ export function parseReasoningWire(value) {
68
+ const raw = new Set(rawReasoningEfforts(value));
69
+ return raw.has("ultra") && !raw.has("max") ? { max: "ultra" } : {};
70
+ }
71
+
72
+ export function normalizeCpaRoot(raw) {
73
+ const trimmed = String(raw ?? "").trim();
74
+ if (trimmed === "") throw new Error("empty CPA baseURL");
75
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
76
+ const url = new URL(withScheme);
77
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
78
+ throw new Error(`unsupported protocol ${url.protocol}`);
79
+ }
80
+ url.search = "";
81
+ url.hash = "";
82
+ let path = url.pathname.replace(/\/+$/, "");
83
+ path = path.replace(/\/(?:v1(?:\/messages|\/chat\/completions|\/responses)?|backend-api)$/i, "");
84
+ url.pathname = path === "" ? "/" : `${path}/`;
85
+ return url.toString().replace(/\/$/, "");
86
+ }
87
+
88
+ /**
89
+ * Probe order: the configured URL, then (only with `autoDiscover`, the
90
+ * default) the account's existing route, `CLIPROXYAPI_BASE_URL` and the local
91
+ * ports. Accounts with an explicit URL never fall back to another server, so
92
+ * one account can't silently mirror another.
93
+ */
94
+ export function discoveryCandidates(options) {
95
+ const raw =
96
+ options.autoDiscover === false
97
+ ? [options.baseURL]
98
+ : [options.baseURL, options.fallbackBaseURL, options.environmentBaseURL, ...LOCAL_CANDIDATES];
99
+ const result = [];
100
+ for (const candidate of raw) {
101
+ if (candidate === undefined || String(candidate).trim() === "") continue;
102
+ try {
103
+ const normalized = normalizeCpaRoot(candidate);
104
+ if (!result.includes(normalized)) result.push(normalized);
105
+ } catch {
106
+ if (candidate === options.baseURL && String(options.baseURL).trim() !== "") {
107
+ throw new Error(`dsh-cliproxyapi: invalid baseURL "${candidate}"`);
108
+ }
109
+ }
110
+ }
111
+ return result;
112
+ }
113
+
114
+ export function parseCatalog(payload) {
115
+ const catalog = catalogArray(payload);
116
+ if (catalog === undefined) {
117
+ throw new Error("response does not contain a models or data array");
118
+ }
119
+ const models = new Map();
120
+ for (const item of catalog) {
121
+ if (typeof item !== "object" || item === null) continue;
122
+ if (String(item.visibility ?? "").toLowerCase() === "hide") continue;
123
+ const rawId = item.slug ?? item.id;
124
+ const id = typeof rawId === "string" ? rawId.trim() : "";
125
+ if (id === "" || models.has(id)) continue;
126
+ const inputModalities = stringArray(item.input_modalities ?? item.inputModalities).map((v) =>
127
+ v.toLowerCase()
128
+ );
129
+ const outputModalities = stringArray(
130
+ item.supportedOutputModalities ?? item.output_modalities ?? item.outputModalities
131
+ ).map((v) => v.toLowerCase());
132
+ const catalogType = typeof item.type === "string" && item.type.trim() !== "" ? item.type.trim() : undefined;
133
+ const rawLevels = item.supported_reasoning_levels ?? item.reasoning_levels;
134
+ const levels = parseReasoningLevels(rawLevels);
135
+ const reasoningWire = parseReasoningWire(rawLevels);
136
+ const contextWindow = firstPositiveInteger(item, [
137
+ "context_window",
138
+ "max_context_window",
139
+ "context_length",
140
+ "contextWindow",
141
+ ]);
142
+ const maxTokens = firstPositiveInteger(item, [
143
+ "max_output_tokens",
144
+ "max_tokens",
145
+ "maxTokens",
146
+ ]);
147
+ const rawName = item.display_name ?? item.name;
148
+ models.set(id, {
149
+ id,
150
+ ...(typeof rawName === "string" && rawName.trim() !== "" ? { name: rawName.trim() } : {}),
151
+ ...(typeof item.owned_by === "string" && item.owned_by.trim() !== ""
152
+ ? { ownedBy: item.owned_by.trim() }
153
+ : {}),
154
+ ...(typeof item.provider === "string" && item.provider.trim() !== ""
155
+ ? { provider: item.provider.trim() }
156
+ : {}),
157
+ ...(contextWindow === undefined ? {} : { contextWindow }),
158
+ ...(maxTokens === undefined ? {} : { maxTokens }),
159
+ inputModalities: inputModalities.length > 0 ? inputModalities : ["text"],
160
+ ...(outputModalities.length === 0 ? {} : { outputModalities }),
161
+ ...(catalogType === undefined ? {} : { catalogType }),
162
+ reasoning: item.reasoning === true || levels.some((level) => level !== "off"),
163
+ reasoningLevels: levels,
164
+ ...(Object.keys(reasoningWire).length === 0 ? {} : { reasoningWire }),
165
+ // chat | image | video, before user overrides (see lib/media/classify.js).
166
+ detectedKind: detectMediaKind({ id, catalogType, outputModalities }),
167
+ });
168
+ }
169
+ return [...models.values()];
170
+ }
171
+
172
+ export async function readBoundedJson(response) {
173
+ const declared = Number(response.headers.get("content-length"));
174
+ if (Number.isFinite(declared) && declared > MAX_CATALOG_BYTES) {
175
+ throw new Error("catalog is larger than 8 MiB");
176
+ }
177
+ const text = await response.text();
178
+ if (new TextEncoder().encode(text).byteLength > MAX_CATALOG_BYTES) {
179
+ throw new Error("catalog is larger than 8 MiB");
180
+ }
181
+ try {
182
+ return JSON.parse(text);
183
+ } catch {
184
+ throw new Error("catalog is not valid JSON");
185
+ }
186
+ }
187
+
188
+ /**
189
+ * The plain `/v1/models` listing, parsed, by id. It carries models the
190
+ * enriched catalog omits (the registry `type` that marks image models, and
191
+ * media models only this listing knows), so it gets its own deadline instead
192
+ * of the enriched request's remaining time and one retry: a slow first
193
+ * response must never silently hide every image model until the next
194
+ * five-minute refresh.
195
+ * @returns `{ models, ok }`; `ok` is false when the listing could not be read.
196
+ */
197
+ export async function fetchListing(fetchImpl, rootURL, options) {
198
+ const timeoutMs = options.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
199
+ const attempt = async () => {
200
+ const timeout = AbortSignal.timeout(timeoutMs);
201
+ const signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout]);
202
+ const response = await fetchImpl(`${rootURL}/v1/models`, {
203
+ method: "GET",
204
+ headers: {
205
+ Accept: "application/json",
206
+ ...(options.apiKey === undefined || options.apiKey === ""
207
+ ? {}
208
+ : { Authorization: `Bearer ${options.apiKey}` }),
209
+ },
210
+ signal,
211
+ });
212
+ if (!response.ok) return { models: new Map(), ok: false };
213
+ return { models: new Map(parseCatalog(await readBoundedJson(response)).map((m) => [m.id, m])), ok: true };
214
+ };
215
+ try {
216
+ return await attempt();
217
+ } catch (error) {
218
+ if (options.signal?.aborted) throw options.signal.reason;
219
+ if (error instanceof Error && /catalog is larger|not valid JSON|does not contain/.test(error.message)) {
220
+ return { models: new Map(), ok: false };
221
+ }
222
+ try {
223
+ return await attempt();
224
+ } catch (retryError) {
225
+ if (options.signal?.aborted) throw options.signal.reason;
226
+ return { models: new Map(), ok: false };
227
+ }
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Fill catalog gaps from the plain listing: `owned_by` (native protocol),
233
+ * the registry `type` and output modalities (media kind). A media model that
234
+ * only the plain listing carries is added; plain-only chat models are not.
235
+ */
236
+ export function mergeListing(models, listing) {
237
+ const merged = models.map((m) => {
238
+ const plainEntry = listing.get(m.id);
239
+ if (plainEntry === undefined) return m;
240
+ const next = { ...m };
241
+ for (const field of ["ownedBy", "catalogType", "outputModalities"]) {
242
+ if (next[field] === undefined && plainEntry[field] !== undefined) next[field] = plainEntry[field];
243
+ }
244
+ next.detectedKind = detectMediaKind(next);
245
+ return next;
246
+ });
247
+ const known = new Set(merged.map((m) => m.id));
248
+ for (const entry of listing.values()) {
249
+ if (!known.has(entry.id) && entry.detectedKind !== "chat") merged.push(entry);
250
+ }
251
+ return merged;
252
+ }
253
+
254
+ export async function discoverCpa(options) {
255
+ const fetchImpl = options.fetch ?? fetch;
256
+ const failures = [];
257
+ const candidates = discoveryCandidates(options);
258
+ for (const rootURL of candidates) {
259
+ const modelsURL = `${rootURL}/v1/models?client_version=pi`;
260
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS);
261
+ const signal =
262
+ options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout]);
263
+ // Start the plain listing together with the enriched catalog; both carry
264
+ // different fields, and the listing alone knows some image models.
265
+ const listingPromise = fetchListing(fetchImpl, rootURL, options);
266
+ try {
267
+ const response = await fetchImpl(modelsURL, {
268
+ method: "GET",
269
+ headers: {
270
+ Accept: "application/json",
271
+ ...(options.apiKey === undefined || options.apiKey === ""
272
+ ? {}
273
+ : { Authorization: `Bearer ${options.apiKey}` }),
274
+ },
275
+ signal,
276
+ });
277
+ if (!response.ok) {
278
+ void listingPromise.catch(() => {});
279
+ failures.push(`${rootURL}: HTTP ${response.status}`);
280
+ continue;
281
+ }
282
+ const models = parseCatalog(await readBoundedJson(response));
283
+ // The enriched catalog omits `owned_by`; the plain listing carries the
284
+ // model family each upstream reports, which decides its native protocol,
285
+ // and the registry type that marks image models.
286
+ const listing = await listingPromise;
287
+ return { rootURL, modelsURL, models: mergeListing(models, listing.models), listingOk: listing.ok };
288
+ } catch (error) {
289
+ void listingPromise.catch(() => {});
290
+ if (options.signal?.aborted) throw options.signal.reason;
291
+ failures.push(`${rootURL}: ${error instanceof Error ? error.message : String(error)}`);
292
+ }
293
+ }
294
+ throw new Error(`dsh-cliproxyapi: no usable CPA service found (${failures.join("; ")})`);
295
+ }
@@ -0,0 +1,144 @@
1
+ // HTTP route names, host/origin admission and bounded JSON request handling.
2
+
3
+
4
+ export const ROUTES = {
5
+ status: "/api/dsh-cliproxyapi/status",
6
+ refresh: "/api/dsh-cliproxyapi/refresh",
7
+ save: "/api/dsh-cliproxyapi/save",
8
+ addAccount: "/api/dsh-cliproxyapi/accounts/add",
9
+ removeAccount: "/api/dsh-cliproxyapi/accounts/remove",
10
+ testAccount: "/api/dsh-cliproxyapi/accounts/test",
11
+ updateStatus: "/api/dsh-cliproxyapi/updates/status",
12
+ updateCheck: "/api/dsh-cliproxyapi/updates/check",
13
+ updateSave: "/api/dsh-cliproxyapi/updates/save",
14
+ updateDownload: "/api/dsh-cliproxyapi/updates/download",
15
+ quotaStatus: "/api/dsh-cliproxyapi/quota/status",
16
+ quotaRefresh: "/api/dsh-cliproxyapi/quota/refresh",
17
+ quotaSave: "/api/dsh-cliproxyapi/quota/save",
18
+ mediaStatus: "/api/dsh-cliproxyapi/media/status",
19
+ mediaSave: "/api/dsh-cliproxyapi/media/save",
20
+ mediaDiagnose: "/api/dsh-cliproxyapi/media/diagnose",
21
+ mediaSession: "/api/dsh-cliproxyapi/media/session",
22
+ mediaSessionSave: "/api/dsh-cliproxyapi/media/session/save",
23
+ mediaFile: "/api/dsh-cliproxyapi/media/file",
24
+ mediaCommand: "/api/dsh-cliproxyapi/media/command",
25
+ mediaConfirm: "/api/dsh-cliproxyapi/media/confirm",
26
+ };
27
+
28
+ export function sendJson(res, status, payload) {
29
+ res.writeHead(status, {
30
+ "cache-control": "no-store",
31
+ "content-type": "application/json; charset=utf-8",
32
+ });
33
+ res.end(JSON.stringify(payload));
34
+ }
35
+
36
+ export function loopbackAuthority(host) {
37
+ if (typeof host !== "string") return false;
38
+ const lower = host.toLowerCase();
39
+ const name = lower.startsWith("[")
40
+ ? lower.slice(0, lower.indexOf("]") + 1)
41
+ : lower.split(":")[0];
42
+ return (
43
+ name === "127.0.0.1" ||
44
+ name === "localhost" ||
45
+ name === "[::1]" ||
46
+ /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(name)
47
+ );
48
+ }
49
+
50
+ export function admitRequest(ctx, req, res, expectedMethod) {
51
+ if (req.method !== expectedMethod) {
52
+ sendJson(res, 405, { error: "Method Not Allowed" });
53
+ return false;
54
+ }
55
+ const connection = ctx.get?.("connection");
56
+ if (typeof connection?.requestRejection === "function") {
57
+ let rejection;
58
+ try {
59
+ rejection = connection.requestRejection(req);
60
+ } catch {
61
+ rejection = 403;
62
+ }
63
+ if (rejection !== undefined) {
64
+ const code = typeof rejection === "number" ? rejection : rejection?.status ?? 403;
65
+ sendJson(res, code, { error: "Request rejected by host connection security policy" });
66
+ return false;
67
+ }
68
+ }
69
+ if (expectedMethod === "POST") {
70
+ const host = req.headers.host;
71
+ const trusted = Array.isArray(connection?.trustedHosts) ? connection.trustedHosts : [];
72
+ if (
73
+ host !== undefined &&
74
+ !loopbackAuthority(host) &&
75
+ !trusted.some((t) => String(t).toLowerCase() === host.toLowerCase())
76
+ ) {
77
+ sendJson(res, 403, { error: "Forbidden host" });
78
+ return false;
79
+ }
80
+ if (req.headers["sec-fetch-site"] === "cross-site") {
81
+ sendJson(res, 403, { error: "Cross-site request forbidden" });
82
+ return false;
83
+ }
84
+ const origin = req.headers.origin;
85
+ if (origin !== undefined) {
86
+ try {
87
+ if (new URL(origin).host !== host) {
88
+ sendJson(res, 403, { error: "Origin mismatch" });
89
+ return false;
90
+ }
91
+ } catch {
92
+ sendJson(res, 403, { error: "Invalid Origin" });
93
+ return false;
94
+ }
95
+ }
96
+ }
97
+ return true;
98
+ }
99
+
100
+ /** Same authority, using the scheme the Origin itself declares (host comparison only). */
101
+ export function sameAuthorityOrigin(origin, host) {
102
+ let originUrl;
103
+ try { originUrl = new URL(origin); } catch { return false; }
104
+ if (originUrl.protocol !== "http:" && originUrl.protocol !== "https:") return false;
105
+ if (originUrl.username || originUrl.password) return false;
106
+ try {
107
+ return originUrl.host === new URL(`${originUrl.protocol}//${host}`).host;
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Update writes need an authenticated browser request. The host connection
115
+ * service already enforces the Host/Origin fence and its session cookie, so
116
+ * this only narrows it: when a browser sends an Origin it must belong to this
117
+ * listener. A carrier that omits Origin (the desktop shell proxies API calls
118
+ * without it) is allowed, because the session cookie is still required and an
119
+ * unauthenticated caller is rejected before reaching the route.
120
+ */
121
+ export function admitUpdateRequest(ctx, req, res, method) {
122
+ if (!admitRequest(ctx, req, res, method)) return false;
123
+ if (method === "GET") return true;
124
+ const host = req.headers.host;
125
+ const origin = req.headers.origin;
126
+ if (host === undefined || origin !== undefined && !sameAuthorityOrigin(origin, host)) {
127
+ sendJson(res, 403, { ok: false, errorCode: "forbidden-origin", error: "Same-origin browser request required" });
128
+ return false;
129
+ }
130
+ return true;
131
+ }
132
+
133
+ export async function readJsonBody(req, maxBytes = 256 * 1024) {
134
+ const chunks = [];
135
+ let size = 0;
136
+ for await (const chunk of req) {
137
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
138
+ size += buf.length;
139
+ if (size > maxBytes) throw new Error("Request body too large");
140
+ chunks.push(buf);
141
+ }
142
+ const raw = Buffer.concat(chunks).toString("utf8");
143
+ return raw.trim() === "" ? {} : JSON.parse(raw);
144
+ }
@@ -0,0 +1,102 @@
1
+ // Chat model filtering, families, version ordering and catalog-derived recommendations.
2
+
3
+ import { MAX_RECOMMENDED_MODELS } from "./config.js";
4
+
5
+ export function splitPrefixes(csv) {
6
+ if (typeof csv !== "string" || csv.trim() === "") return [];
7
+ return csv
8
+ .split(",")
9
+ .map((s) => s.trim().toLowerCase())
10
+ .filter(Boolean);
11
+ }
12
+
13
+ export function filterModels(models, config) {
14
+ const includes = splitPrefixes(config.includePrefix);
15
+ const excludes = splitPrefixes(config.excludePrefix);
16
+ const selectedSet =
17
+ Array.isArray(config.selectedModels) && config.selectedModels.length > 0
18
+ ? new Set(config.selectedModels)
19
+ : null;
20
+
21
+ return models.filter((m) => {
22
+ if (selectedSet !== null && !selectedSet.has(m.id)) {
23
+ return false;
24
+ }
25
+ const idLower = m.id.toLowerCase();
26
+ if (includes.length > 0 && !includes.some((p) => idLower.startsWith(p) || idLower.includes(p))) {
27
+ return false;
28
+ }
29
+ if (excludes.length > 0 && excludes.some((p) => idLower.startsWith(p) || idLower.includes(p))) {
30
+ return false;
31
+ }
32
+ return true;
33
+ });
34
+ }
35
+
36
+ export function modelFamily(model) {
37
+ const label = (model.name ?? model.id).trim().toLowerCase();
38
+ const known = label.match(
39
+ /^(gpt-oss|gemini|claude|gpt|grok|deepseek|qwen|glm|kimi|minimax|mistral|llama|swe|o(?=\d))/
40
+ )?.[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
+ }
76
+
77
+ /**
78
+ * A starting selection derived from the server's own catalog: the newest
79
+ * model of each family, in catalog order, at most {@link MAX_RECOMMENDED_MODELS}.
80
+ * Among equally new models a plain id is preferred over a prefixed one
81
+ * (`gpt-6` over `vendor/gpt-6`).
82
+ * @param models - parsed catalog models.
83
+ * @returns model ids.
84
+ */
85
+ export function recommendModels(models) {
86
+ const groups = new Map();
87
+ for (const model of models) {
88
+ const family = modelFamily(model);
89
+ const group = groups.get(family);
90
+ if (group === undefined) groups.set(family, [model]);
91
+ else group.push(model);
92
+ }
93
+ const picks = [];
94
+ for (const group of groups.values()) {
95
+ const sorted = [...group].sort(
96
+ (a, b) => compareVersionDescending(a, b) || Number(a.id.includes("/")) - Number(b.id.includes("/"))
97
+ );
98
+ picks.push(sorted[0].id);
99
+ if (picks.length >= MAX_RECOMMENDED_MODELS) break;
100
+ }
101
+ return picks;
102
+ }
@@ -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
+ }