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,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
+ }
@@ -0,0 +1,165 @@
1
+ // Native wire protocols, model overrides and managed llm-pi-ai route profiles.
2
+
3
+ import { REASONING_LEVELS, PROTOCOLS, PROTOCOL_ROUTES } from "./config.js";
4
+ import { filterModels, sortModelsNewestFirst } from "./models.js";
5
+
6
+ /**
7
+ * Pick the wire protocol that reaches a model with the fewest translations.
8
+ *
9
+ * CLIProxyAPI serves every model on OpenAI Chat, OpenAI Responses and
10
+ * Anthropic Messages and translates between them and the upstream channel.
11
+ * Speaking the upstream's own protocol skips that translation:
12
+ * - Claude family -> Anthropic Messages (`/v1/messages`)
13
+ * - OpenAI / Codex / Grok -> OpenAI Responses (`/v1/responses`)
14
+ * - everything else, including Gemini -> OpenAI Chat Completions; DSH
15
+ * cannot speak Gemini generateContent on a custom route.
16
+ * `owned_by` from the CPA listing names the family; the id is the fallback.
17
+ * @param model - parsed catalog model.
18
+ * @returns one of {@link PROTOCOLS}.
19
+ */
20
+ export function nativeProtocol(model) {
21
+ const owner = String(model.ownedBy ?? "").toLowerCase();
22
+ const bare = String(model.id ?? "").toLowerCase().split("/").pop() ?? "";
23
+ if (owner === "anthropic" || /^claude/.test(bare)) return "anthropic-messages";
24
+ if (owner === "openai" || owner === "xai") return "openai-responses";
25
+ if (/^(gpt|o\d|codex|grok)/.test(bare) && !/^gpt-oss/.test(bare)) return "openai-responses";
26
+ return "openai-completions";
27
+ }
28
+
29
+ /** The protocol a model is synchronized with under the given config. */
30
+ export function modelProtocol(model, config) {
31
+ const override = config.modelOverrides?.[model.id]?.protocol;
32
+ if (override !== undefined) return override;
33
+ return config.protocolMode === "fixed" ? config.protocol : nativeProtocol(model);
34
+ }
35
+
36
+ /** The DSH route key carrying one protocol. */
37
+ export function routeKeyFor(provider, protocol) {
38
+ return `${provider}${PROTOCOL_ROUTES[protocol].suffix}`;
39
+ }
40
+
41
+ export function routeBaseURL(rootURL, protocol) {
42
+ return protocol === "anthropic-messages" ? rootURL : `${rootURL}/v1`;
43
+ }
44
+
45
+ export function supportedReasoning(model) {
46
+ if (!model.reasoning) return undefined;
47
+ const declared = new Set(model.reasoningLevels);
48
+ const levels =
49
+ declared.size === 0
50
+ ? REASONING_LEVELS
51
+ : REASONING_LEVELS.filter((level) => declared.has(level));
52
+ const result = {};
53
+ for (const level of levels) {
54
+ result[level] = level === "off" ? null : model.reasoningWire?.[level] ?? level;
55
+ }
56
+ return Object.keys(result).length === 0 ? undefined : result;
57
+ }
58
+
59
+ /**
60
+ * Claude models that take adaptive thinking with an `effort` value rather
61
+ * than a token budget: Opus/Sonnet 4.6+, Haiku 5+, Fable and every 5.x.
62
+ * Older Claude models keep budget-based thinking.
63
+ */
64
+ export function claudeUsesAdaptiveThinking(model) {
65
+ const bare = String(model.id).toLowerCase().split("/").pop() ?? "";
66
+ if (/^claude-fable/.test(bare)) return true;
67
+ const match = bare.match(/^claude-(?:opus|sonnet|haiku)-(\d+)(?:-(\d+))?/);
68
+ if (match === null) return /^claude-\d+-fable/.test(bare);
69
+ const major = Number(match[1]);
70
+ const minor = match[2] !== undefined && match[2].length <= 2 ? Number(match[2]) : 0;
71
+ return major > 4 || (major === 4 && minor >= 6);
72
+ }
73
+
74
+ export function applyModelOverride(model, override) {
75
+ if (override === undefined) return model;
76
+ const next = { ...model };
77
+ if (override.contextWindow !== undefined) next.contextWindow = override.contextWindow;
78
+ if (override.maxTokens !== undefined) next.maxTokens = override.maxTokens;
79
+ if (override.image === true || override.image === false) {
80
+ const rest = model.inputModalities.filter((item) => item !== "image");
81
+ next.inputModalities = override.image ? [...new Set(["text", "image", ...rest])] : rest.length > 0 ? rest : ["text"];
82
+ }
83
+ if (Array.isArray(override.reasoningLevels)) {
84
+ next.reasoningLevels = [...override.reasoningLevels];
85
+ next.reasoning = override.reasoningLevels.some((level) => level !== "off");
86
+ }
87
+ return next;
88
+ }
89
+
90
+ export function protocolCompat(model, protocol, hasReasoning) {
91
+ if (protocol === "openai-completions") {
92
+ return hasReasoning ? { supportsReasoningEffort: true, thinkingFormat: "openai" } : undefined;
93
+ }
94
+ if (protocol === "anthropic-messages") {
95
+ return hasReasoning && claudeUsesAdaptiveThinking(model)
96
+ ? { forceAdaptiveThinking: true }
97
+ : undefined;
98
+ }
99
+ return undefined;
100
+ }
101
+
102
+ export function toPiAiModelProfile(model, protocol) {
103
+ const reasoningEfforts = supportedReasoning(model);
104
+ const compat = protocolCompat(model, protocol, reasoningEfforts !== undefined);
105
+ return {
106
+ id: model.id,
107
+ ...(model.name === undefined ? {} : { name: model.name }),
108
+ contextWindow: model.contextWindow ?? 262144,
109
+ maxTokens: model.maxTokens ?? 64000,
110
+ input: model.inputModalities.includes("image") ? ["text", "image"] : ["text"],
111
+ ...(reasoningEfforts === undefined ? {} : { reasoningEfforts }),
112
+ ...(compat === undefined ? {} : { compat }),
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Build one llm-pi-ai route per protocol the selected models need.
118
+ * The base route key (e.g. `cli-proxy`) always carries OpenAI Chat so that
119
+ * existing sessions and the default-model setting keep resolving; Responses
120
+ * and Messages models get `<key>-responses` / `<key>-messages` siblings.
121
+ * @returns `{ allModels, orderedModels, routes }` where `routes` maps each
122
+ * route key to its profile, in protocol order, and every ordered model
123
+ * carries its `protocol` and `route`.
124
+ */
125
+ /** Whether a model belongs in chat routes: `kind` (with overrides) or detection says chat. */
126
+ export function isChatModel(model) {
127
+ return (model.kind ?? model.detectedKind ?? "chat") === "chat";
128
+ }
129
+
130
+ export function buildPiAiRoutes(config, discovery, hasApiKey) {
131
+ const allOrdered = sortModelsNewestFirst(discovery.models);
132
+ // Image / video models are served by CPA's media endpoints, never by chat routes.
133
+ const chatOrdered = allOrdered.filter(isChatModel);
134
+ const filtered = filterModels(chatOrdered, config).map((model) => {
135
+ const effective = applyModelOverride(model, config.modelOverrides?.[model.id]);
136
+ const protocol = modelProtocol(model, config);
137
+ return { ...effective, protocol, route: routeKeyFor(config.provider, protocol) };
138
+ });
139
+ if (filtered.length === 0) {
140
+ throw new Error(
141
+ `dsh-cliproxyapi: none of the selected models matched the ${chatOrdered.length} chat model(s) offered by ${discovery.rootURL}. Select models in Settings → CLIProxyAPI → Models.`
142
+ );
143
+ }
144
+ const auth = hasApiKey
145
+ ? { apiKeyEnv: config.apiKeyEnv }
146
+ : { headers: { Authorization: "Bearer cpa-local" } };
147
+ const routes = {};
148
+ for (const protocol of PROTOCOLS) {
149
+ const members = filtered.filter((m) => m.protocol === protocol);
150
+ if (members.length === 0) continue;
151
+ routes[routeKeyFor(config.provider, protocol)] = {
152
+ displayName: `${config.displayName}${PROTOCOL_ROUTES[protocol].label}`,
153
+ api: protocol,
154
+ baseURL: routeBaseURL(discovery.rootURL, protocol),
155
+ models: members.map((m) => toPiAiModelProfile(m, protocol)),
156
+ ...auth,
157
+ };
158
+ }
159
+ return { allModels: allOrdered, orderedModels: filtered, routes };
160
+ }
161
+
162
+ /** Every route key this plugin may own under a provider prefix. */
163
+ export function managedRouteKeys(provider) {
164
+ return PROTOCOLS.map((protocol) => routeKeyFor(provider, protocol));
165
+ }