dsh-cliproxyapi-pro 1.9.1 → 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.
@@ -0,0 +1,367 @@
1
+ // Catalog-derived model recommendations and selection suggestions.
2
+ //
3
+ // Models are grouped into product lines (`claude-opus`, `gpt-sol`, `gemini-flash`)
4
+ // and families (`claude`, `gpt`). Each line is represented by its newest
5
+ // model; lines left behind by their family are stale. Recommendations are
6
+ // flagships: fresh lines close to the best capability score (without scores,
7
+ // non-light lines of well-known families). Optional online model info
8
+ // (lib/host/model-info.js) supplies release dates, line names, retirement and
9
+ // capability scores; without it the catalog's own dates and versions decide.
10
+
11
+ import { MAX_RECOMMENDED_MODELS } from "./config.js";
12
+ import { KNOWN_FAMILY, modelFamily } from "./models.js";
13
+ import { LIGHT_WORDS, bareId, compareVersionsDesc, isPrefixed, lineFromText, matchKeys, modelLine } from "./model-names.js";
14
+
15
+ const DAY_MS = 86_400_000;
16
+ /** A line whose newest model is this much older than its family's newest is stale. */
17
+ export const STALE_LINE_DAYS = 180;
18
+
19
+ function isoDay(ms) {
20
+ return ms === undefined ? undefined : new Date(ms).toISOString().slice(0, 10);
21
+ }
22
+
23
+ function parseDay(value) {
24
+ if (typeof value !== "string" || value.trim() === "") return undefined;
25
+ const ms = Date.parse(value.length === 7 ? `${value}-01` : value);
26
+ return Number.isFinite(ms) ? ms : undefined;
27
+ }
28
+
29
+ /** Whether online info marks a model as retired (deprecated or past its end date). */
30
+ export function isRetired(info, now = Date.now()) {
31
+ if (info === undefined) return false;
32
+ if (info.status === "deprecated") return true;
33
+ const ends = parseDay(info.expires);
34
+ return ends !== undefined && ends <= now;
35
+ }
36
+
37
+ /**
38
+ * The vendor family lines compete in: a known family name (`claude`, `gpt-oss`),
39
+ * else the first word of the line (`acme` for `acme-pro` and `acme-max`).
40
+ */
41
+ function familyOf(model, line) {
42
+ const known = modelFamily(model);
43
+ if (KNOWN_FAMILY.test(known) || line === undefined) return known;
44
+ return line.label.split("-")[0];
45
+ }
46
+
47
+ function describe(model, index, lookup, now) {
48
+ const info = lookup?.(model);
49
+ const local = modelLine(model);
50
+ const online = typeof info?.family === "string" ? lineFromText(info.family) : undefined;
51
+ const line = online ?? local;
52
+ const released = parseDay(info?.released);
53
+ const created = Number.isInteger(model.created) && model.created > 0 ? model.created * 1000 : undefined;
54
+ return {
55
+ model,
56
+ index,
57
+ info,
58
+ line,
59
+ family: familyOf(model, line),
60
+ version: local?.parsed.version,
61
+ date: released ?? created,
62
+ dateSource: released !== undefined ? "online" : created !== undefined ? "catalog" : undefined,
63
+ variant: (local?.parsed.variants.length ?? 0) > 0,
64
+ prefixed: isPrefixed(model.id),
65
+ retired: isRetired(info, now),
66
+ };
67
+ }
68
+
69
+ /** Whether `a` is a newer release than `b` (dates when both have one, else versions). */
70
+ function newer(a, b) {
71
+ if (a.date !== undefined && b.date !== undefined) return a.date > b.date;
72
+ return compareVersionsDesc(a.version, b.version) < 0;
73
+ }
74
+
75
+ function compareInLine(useDates) {
76
+ return (a, b) => {
77
+ if (a.retired !== b.retired) return a.retired ? 1 : -1;
78
+ if (useDates && a.date !== b.date) return b.date - a.date;
79
+ const byVersion = compareVersionsDesc(a.version, b.version);
80
+ if (byVersion !== 0) return byVersion;
81
+ if (a.date !== undefined && b.date !== undefined && a.date !== b.date) return b.date - a.date;
82
+ if (a.variant !== b.variant) return a.variant ? 1 : -1;
83
+ if (a.prefixed !== b.prefixed) return a.prefixed ? 1 : -1;
84
+ return a.index - b.index;
85
+ };
86
+ }
87
+
88
+ /** Capability signals, in order of trust; a family uses the first all its lines have. */
89
+ const SIGNALS = [
90
+ { read: (line) => line.rep.info?.intelligence, order: -1 },
91
+ { read: (line) => line.rep.info?.costOutput, order: -1 },
92
+ {
93
+ read: (line) => {
94
+ const priority = line.rep.model.priority;
95
+ return Number.isInteger(priority) && priority >= 0 && priority < 100 ? priority : undefined;
96
+ },
97
+ order: 1,
98
+ },
99
+ ];
100
+
101
+ function rankLines(lines) {
102
+ const signal = lines.length > 1
103
+ ? SIGNALS.find((s) => lines.every((line) => typeof s.read(line) === "number"))
104
+ : undefined;
105
+ const light = (line) => line.label.split("-").filter((word) => LIGHT_WORDS.has(word)).length;
106
+ return [...lines].sort((a, b) => {
107
+ if (signal !== undefined) {
108
+ const diff = (signal.read(a) - signal.read(b)) * signal.order;
109
+ if (diff !== 0) return diff;
110
+ }
111
+ if (light(a) !== light(b)) return light(a) - light(b);
112
+ if (a.date !== undefined && b.date !== undefined && a.date !== b.date) return b.date - a.date;
113
+ return a.index - b.index;
114
+ });
115
+ }
116
+
117
+ /**
118
+ * Group chat models into lines and families.
119
+ * @param models - chat models in catalog order.
120
+ * @param options.lookup - `(model) => info | undefined` from online model info.
121
+ * @returns `{ described, lines, families }`; families are in catalog order and
122
+ * their `fresh` lines best first.
123
+ */
124
+ export function analyzeModels(models, options = {}) {
125
+ const now = options.now ?? Date.now();
126
+ const described = models.map((model, index) => describe(model, index, options.lookup, now));
127
+ // A prefixed copy (`devin/grok-4-7`) without a date shares its twin's (`grok-4.7`).
128
+ const twinDates = new Map();
129
+ for (const entry of described) {
130
+ const key = entry.date === undefined ? undefined : matchKeys(entry.model.id)?.loose;
131
+ if (key !== undefined && !twinDates.has(key)) twinDates.set(key, entry);
132
+ }
133
+ for (const entry of described) {
134
+ if (entry.date !== undefined) continue;
135
+ const twin = twinDates.get(matchKeys(entry.model.id)?.loose);
136
+ if (twin !== undefined) {
137
+ entry.date = twin.date;
138
+ entry.dateSource = twin.dateSource;
139
+ }
140
+ }
141
+ const byKey = new Map();
142
+ for (const entry of described) {
143
+ if (entry.line === undefined) continue; // opaque ids are never recommended
144
+ const group = byKey.get(entry.line.key);
145
+ if (group === undefined) byKey.set(entry.line.key, { key: entry.line.key, label: entry.line.label, members: [entry] });
146
+ else group.members.push(entry);
147
+ }
148
+ const lines = [...byKey.values()].map((group) => {
149
+ const useDates = group.members.every((m) => m.date !== undefined);
150
+ const members = [...group.members].sort(compareInLine(useDates));
151
+ const rep = members[0];
152
+ // A just-released model may not be scored yet; its line keeps its best known score.
153
+ const scores = members.filter((m) => !m.retired).map((m) => m.info?.intelligence).filter((s) => typeof s === "number");
154
+ return {
155
+ score: scores.length > 0 ? Math.max(...scores) : undefined,
156
+ key: group.key,
157
+ label: group.label,
158
+ members,
159
+ rep,
160
+ family: rep.family,
161
+ date: rep.date,
162
+ major: rep.version?.[0],
163
+ retired: rep.retired,
164
+ index: Math.min(...members.map((m) => m.index)),
165
+ };
166
+ });
167
+ const familyMap = new Map();
168
+ for (const line of [...lines].sort((a, b) => a.index - b.index)) {
169
+ const family = familyMap.get(line.family);
170
+ if (family === undefined) familyMap.set(line.family, { name: line.family, lines: [line] });
171
+ else family.lines.push(line);
172
+ }
173
+ const staleMs = STALE_LINE_DAYS * DAY_MS;
174
+ for (const family of familyMap.values()) {
175
+ const live = family.lines.filter((line) => !line.retired);
176
+ const dates = live.map((line) => line.date).filter((d) => d !== undefined);
177
+ const majors = live.map((line) => line.major).filter((m) => m !== undefined);
178
+ const bestDate = dates.length > 0 ? Math.max(...dates) : undefined;
179
+ const maxMajor = majors.length > 0 ? Math.max(...majors) : undefined;
180
+ for (const line of family.lines) {
181
+ line.stale =
182
+ line.retired ||
183
+ (line.date !== undefined && bestDate !== undefined
184
+ ? line.date < bestDate - staleMs
185
+ : line.major !== undefined && maxMajor !== undefined && line.major < maxMajor);
186
+ }
187
+ family.fresh = rankLines(family.lines.filter((line) => !line.stale));
188
+ }
189
+ return { described, lines, families: [...familyMap.values()] };
190
+ }
191
+
192
+ function detail(line) {
193
+ const rep = line.rep;
194
+ return {
195
+ id: rep.model.id,
196
+ line: line.label,
197
+ family: line.family,
198
+ ...(rep.date === undefined ? {} : { released: isoDay(rep.date) }),
199
+ ...(line.score === undefined ? {} : { score: line.score }),
200
+ source: rep.info !== undefined ? "online" : rep.dateSource === "catalog" ? "catalog" : "name",
201
+ };
202
+ }
203
+
204
+ /** A flagship scores at least this share of the account's best fresh line. */
205
+ export const FLAGSHIP_RATIO = 0.8;
206
+
207
+ const isLight = (line) => line.label.split("-").some((word) => LIGHT_WORDS.has(word));
208
+
209
+ /**
210
+ * Owners that count as a prefixed channel's own vendor besides the prefix
211
+ * itself (vocabulary, not model ids): Devin's own models are owned by Cognition.
212
+ */
213
+ export const CHANNEL_OWNER_ALIASES = { devin: ["cognition"] };
214
+
215
+ /**
216
+ * The CPA channel a model comes from: its id prefix (`devin/…`), else the
217
+ * `owned_by` the plain listing reports (`xai`, `openai`, `antigravity`).
218
+ */
219
+ export function modelChannel(model) {
220
+ const id = String(model.id ?? "");
221
+ const slash = id.lastIndexOf("/");
222
+ if (slash > 0) return id.slice(0, slash).toLowerCase();
223
+ const owner = typeof model.ownedBy === "string" ? model.ownedBy.trim().toLowerCase() : "";
224
+ return owner === "" ? undefined : owner;
225
+ }
226
+
227
+ /** Whether a model is the channel's own (Devin's SWE), not a model it relays (Devin's Claude). */
228
+ function isHouseModel(model, channel) {
229
+ if (!isPrefixed(model.id)) return true;
230
+ const owner = typeof model.ownedBy === "string" ? model.ownedBy.trim().toLowerCase() : "";
231
+ return owner === channel || (CHANNEL_OWNER_ALIASES[channel] ?? []).includes(owner);
232
+ }
233
+
234
+ /** The best line among a channel's own models: score, price, then its main (largest) line. */
235
+ function channelBest(lines) {
236
+ const num = (v) => (typeof v === "number" ? v : -1);
237
+ return [...lines].sort(
238
+ (a, b) =>
239
+ num(b.score) - num(a.score) ||
240
+ num(b.rep.info?.costOutput) - num(a.rep.info?.costOutput) ||
241
+ Number(isLight(a)) - Number(isLight(b)) ||
242
+ b.members.length - a.members.length ||
243
+ a.index - b.index
244
+ )[0];
245
+ }
246
+
247
+ /**
248
+ * One representative per channel the account connects: the best fresh line
249
+ * of the channel's own models (Devin → SWE, a Grok channel → Grok), unless
250
+ * that line is already recommended.
251
+ */
252
+ function channelPicks(models, options, taken) {
253
+ const byChannel = new Map();
254
+ for (const model of models) {
255
+ const channel = modelChannel(model);
256
+ if (channel === undefined || !isHouseModel(model, channel)) continue;
257
+ const list = byChannel.get(channel);
258
+ if (list === undefined) byChannel.set(channel, [model]);
259
+ else list.push(model);
260
+ }
261
+ const picks = [];
262
+ for (const [channel, house] of byChannel) {
263
+ const fresh = analyzeModels(house, options).families.flatMap((family) => family.fresh);
264
+ if (fresh.length === 0) continue;
265
+ const best = channelBest(fresh);
266
+ if (taken.has(best.key)) continue;
267
+ taken.add(best.key);
268
+ picks.push({ line: best, channel });
269
+ }
270
+ return picks;
271
+ }
272
+
273
+ /**
274
+ * Flagships plus one model per channel.
275
+ * - With capability scores (online model info): every fresh line scoring at
276
+ * least {@link FLAGSHIP_RATIO} of the best one, strongest first; light,
277
+ * unscored and niche lines fall away.
278
+ * - Without scores: the fresh non-light lines of well-known families
279
+ * ({@link KNOWN_FAMILY}), families taking turns.
280
+ * - Then every channel not represented yet adds the best line of its own
281
+ * models ({@link modelChannel}), detail `via: "channel"`.
282
+ * At most `max` models; channel picks keep their place.
283
+ * @returns `{ ids, details }`; every detail names the line, family, release
284
+ * date and score (when known) and where the facts came from.
285
+ */
286
+ export function planRecommendations(models, options = {}) {
287
+ const max = options.max ?? MAX_RECOMMENDED_MODELS;
288
+ const { families } = analyzeModels(models, options);
289
+ const fresh = families.flatMap((family) => family.fresh);
290
+ const scored = fresh.filter((line) => line.score !== undefined);
291
+ let picks;
292
+ if (scored.length >= 2) {
293
+ const best = Math.max(...scored.map((line) => line.score));
294
+ picks = scored
295
+ .filter((line) => line.score >= best * FLAGSHIP_RATIO)
296
+ .sort((a, b) => b.score - a.score || a.index - b.index);
297
+ } else {
298
+ const heavy = families
299
+ .filter((family) => KNOWN_FAMILY.test(family.name))
300
+ .map((family) => {
301
+ const lines = family.fresh.filter((line) => !isLight(line));
302
+ return lines.length > 0 ? lines : family.fresh.slice(0, 1);
303
+ });
304
+ picks = [];
305
+ for (let round = 0; heavy.some((lines) => lines[round] !== undefined); round += 1) {
306
+ for (const lines of heavy) if (lines[round] !== undefined) picks.push(lines[round]);
307
+ }
308
+ }
309
+ const extra = channelPicks(models, options, new Set(picks.map((line) => line.key))).slice(0, max);
310
+ const details = [
311
+ ...picks.slice(0, Math.max(0, max - extra.length)).map(detail),
312
+ ...extra.map(({ line, channel }) => ({ ...detail(line), via: "channel", channel })),
313
+ ];
314
+ return { ids: details.map((d) => d.id), details };
315
+ }
316
+
317
+ /** Recommended model ids (see {@link planRecommendations}). */
318
+ export function recommendModels(models, options = {}) {
319
+ return planRecommendations(models, options).ids;
320
+ }
321
+
322
+ /**
323
+ * Advice about a saved selection, never applied automatically:
324
+ * - `upgrades`: a checked line has a newer, unchecked model;
325
+ * - `missing`: a checked id is no longer in the catalog (only when the
326
+ * catalog is complete), with a same-named replacement when one exists;
327
+ * - `retired`: a checked model is deprecated or past its end date upstream.
328
+ * @param chatModels - this account's chat models.
329
+ * @param allIds - every id in the catalog, any kind (media ids are not missing).
330
+ */
331
+ export function selectionSuggestions(chatModels, selectedIds, options = {}) {
332
+ const selected = new Set(selectedIds ?? []);
333
+ const { described, lines } = analyzeModels(chatModels, options);
334
+ const upgrades = [];
335
+ for (const line of lines) {
336
+ const rep = line.rep;
337
+ if (rep.retired || selected.has(rep.model.id)) continue;
338
+ const from = line.members.filter((m) => selected.has(m.model.id) && newer(rep, m)).map((m) => m.model.id);
339
+ if (from.length === 0) continue;
340
+ upgrades.push({ to: rep.model.id, from, line: line.label, ...(rep.date === undefined ? {} : { released: isoDay(rep.date) }) });
341
+ }
342
+
343
+ const known = new Set(options.allIds ?? chatModels.map((m) => m.id));
344
+ const replacementFor = (id) => {
345
+ const keys = matchKeys(id);
346
+ const bare = bareId(id);
347
+ const candidates = described.filter((d) => !selected.has(d.model.id) && (bareId(d.model.id) === bare || (keys !== undefined && matchKeys(d.model.id)?.exact === keys.exact)));
348
+ candidates.sort((a, b) => Number(a.prefixed) - Number(b.prefixed) || a.index - b.index);
349
+ return candidates[0]?.model.id;
350
+ };
351
+ const missing = options.catalogComplete === false || known.size === 0
352
+ ? []
353
+ : [...selected].filter((id) => !known.has(id)).map((id) => {
354
+ const replacement = replacementFor(id);
355
+ return { id, ...(replacement === undefined ? {} : { replacement }) };
356
+ });
357
+
358
+ const lineOf = new Map(lines.flatMap((line) => line.members.map((m) => [m.model.id, line])));
359
+ const retired = described
360
+ .filter((d) => d.retired && selected.has(d.model.id))
361
+ .map((d) => {
362
+ const rep = lineOf.get(d.model.id)?.rep;
363
+ const replacement = rep !== undefined && !rep.retired && rep.model.id !== d.model.id ? rep.model.id : undefined;
364
+ return { id: d.model.id, ...(replacement === undefined ? {} : { replacement }) };
365
+ });
366
+ return { upgrades, missing, retired };
367
+ }
@@ -2,9 +2,11 @@
2
2
 
3
3
  import { effectiveKind } from "../media/index.js";
4
4
  import { DEFAULT_API_KEY_ENV, PI_AI_NS, DEFAULT_MODEL_NS } from "./config.js";
5
- import { modelFamily, recommendModels } from "./models.js";
5
+ import { modelFamily } from "./models.js";
6
+ import { recommendModels } from "./recommend.js";
6
7
  import { nativeProtocol, modelProtocol, applyModelOverride, isChatModel, buildPiAiRoutes, managedRouteKeys } from "./routes.js";
7
8
  import { discoverCpa } from "./discovery.js";
9
+ import { withOnlineLimits } from "./model-info.js";
8
10
 
9
11
  export function sleep(ms) {
10
12
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -71,6 +73,8 @@ export function formatModelView(m, selectedSet, config) {
71
73
  maxTokens: m.maxTokens ?? 64000,
72
74
  image: m.inputModalities.includes("image"),
73
75
  reasoningLevels: m.reasoningLevels,
76
+ // Limits the catalog left out, filled from online model info.
77
+ ...(Array.isArray(m.onlineLimits) ? { onlineLimits: m.onlineLimits } : {}),
74
78
  },
75
79
  };
76
80
  }
@@ -107,7 +111,16 @@ export class CpaRuntime {
107
111
  try {
108
112
  overrides = this.options.kindOverrides?.() ?? {};
109
113
  } catch {}
110
- return models.map((m) => ({ ...m, kind: effectiveKind(m, overrides) }));
114
+ return models.map((m) => ({ ...withOnlineLimits(m, this.lookupInfo(m)), kind: effectiveKind(m, overrides) }));
115
+ }
116
+
117
+ /** Online facts about one catalog model (lib/host/model-info.js), when switched on. */
118
+ lookupInfo(model) {
119
+ try {
120
+ return this.options.lookupInfo?.(model);
121
+ } catch {
122
+ return undefined;
123
+ }
111
124
  }
112
125
 
113
126
  /** Discovered chat models (what the picker, recommendations and seeding use). */
@@ -191,7 +204,7 @@ export class CpaRuntime {
191
204
  */
192
205
  seedSelection(config, models) {
193
206
  if (config.selectedModels !== undefined || models.length === 0) return undefined;
194
- const ids = recommendModels(models);
207
+ const ids = recommendModels(models, { lookup: (m) => this.lookupInfo(m) });
195
208
  try {
196
209
  this.options.seedSelection?.(ids);
197
210
  } catch (error) {
@@ -202,6 +215,17 @@ export class CpaRuntime {
202
215
  return ids;
203
216
  }
204
217
 
218
+ /**
219
+ * Before a first-run seed only: give online model info a few seconds to
220
+ * arrive so the seeded selection matches what the panel will recommend.
221
+ */
222
+ async awaitModelInfo(config) {
223
+ if (config.selectedModels !== undefined || this.options.modelInfoReady === undefined) return;
224
+ try {
225
+ await this.options.modelInfoReady();
226
+ } catch {}
227
+ }
228
+
205
229
  /** Route keys owned by other accounts, from the latest config. */
206
230
  reservedKeys() {
207
231
  try {
@@ -325,6 +349,7 @@ export class CpaRuntime {
325
349
  const { result } = await this.discover(config);
326
350
  this.allDiscoveredModels = result.models;
327
351
  this.listingOk = result.listingOk !== false;
352
+ await this.awaitModelInfo(config);
328
353
  this.seedSelection(config, this.chatModels(result.models));
329
354
  endpoint = result.rootURL;
330
355
  } catch (error) {
@@ -353,6 +378,7 @@ export class CpaRuntime {
353
378
  this.allDiscoveredModels = result.models;
354
379
  this.listingOk = result.listingOk !== false;
355
380
  this.scheduleListingRetry();
381
+ await this.awaitModelInfo(config);
356
382
  const seeded = this.seedSelection(config, this.chatModels(result.models));
357
383
 
358
384
  const effectiveConfig = {
package/lib/index.js CHANGED
@@ -14,7 +14,8 @@ export { PACKAGE_NAME, name, inject, DEFAULT_ACCOUNT_ID, DEFAULT_PROVIDER, DEFAU
14
14
  export { serializeSettings, createCpaController } from "./host/controller.js";
15
15
  export { normalizeCpaRoot, discoveryCandidates, parseCatalog, discoverCpa } from "./host/discovery.js";
16
16
  export { ROUTES } from "./host/http-gate.js";
17
- export { filterModels, modelFamily, sortModelsNewestFirst, recommendModels } from "./host/models.js";
17
+ export { filterModels, modelFamily, sortModelsNewestFirst } from "./host/models.js";
18
+ export { recommendModels, planRecommendations, selectionSuggestions } from "./host/recommend.js";
18
19
  export { nativeProtocol, modelProtocol, routeKeyFor, applyModelOverride, isChatModel, buildPiAiRoutes, managedRouteKeys } from "./host/routes.js";
19
20
  export { CpaRuntime } from "./host/runtime.js";
20
21
  export { resolveStateFilePath, loadPersistedState, savePersistedState } from "./host/state-store.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cliproxyapi-pro",
3
- "version": "1.9.1",
3
+ "version": "1.10.0",
4
4
  "description": "CLIProxyAPI (CPA) provider for DeepSeek Harness — multiple accounts, model sync over native protocols, per-credential quota, and optional image / video generation.",
5
5
  "keywords": [
6
6
  "dsh",