omp-config-crypt 0.6.2 → 0.6.4

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.
@@ -21,26 +21,201 @@ const LOCAL_LOADER_SCRIPT = `import fs from "node:fs";
21
21
  import path from "node:path";
22
22
  import os from "node:os";
23
23
 
24
- export default function (pi) {
24
+ const DEFAULT_CONTEXT_WINDOW = 256000; // 默认 256K
25
+ const DEFAULT_MAX_TOKENS = 65536;
26
+
27
+ /**
28
+ * 根据名称指纹与知名模型规范推断模型规格
29
+ */
30
+ function inferModelSpec(modelId) {
31
+ const id = (modelId || "").toLowerCase();
32
+
33
+ // Gemini 系列
34
+ if (/gemini.*pro/.test(id)) {
35
+ return { contextWindow: 2000000, maxTokens: 65536, hasImage: true };
36
+ }
37
+ if (/gemini.*(flash|lite)/.test(id)) {
38
+ return { contextWindow: 1000000, maxTokens: 65536, hasImage: true };
39
+ }
40
+
41
+ // DeepSeek 系列
42
+ if (/deepseek.*(v4|pro|flash)/.test(id)) {
43
+ return { contextWindow: 1048576, maxTokens: 65536, hasImage: /flash|vl/.test(id) };
44
+ }
45
+ if (/deepseek/.test(id)) {
46
+ return { contextWindow: 1048576, maxTokens: 32000, hasImage: /vl/.test(id) };
47
+ }
48
+
49
+ // Kimi / Moonshot 系列
50
+ if (/kimi|moonshot/.test(id)) {
51
+ return { contextWindow: 512000, maxTokens: 32000, hasImage: false };
52
+ }
53
+
54
+ // Claude 系列
55
+ if (/claude/.test(id)) {
56
+ return { contextWindow: 200000, maxTokens: 64000, hasImage: true };
57
+ }
58
+
59
+ // GPT-6 / Codex 系列
60
+ if (/(gpt-6|gpt-5\\.[0-9]).*(sol|terra)/.test(id)) {
61
+ return { contextWindow: 256000, maxTokens: 384000, reasoning: true, hasImage: false };
62
+ }
63
+ if (/gpt-6|astra/.test(id)) {
64
+ return { contextWindow: 256000, maxTokens: 32000, hasImage: false };
65
+ }
66
+
67
+ // Qwen 系列
68
+ if (/qwen.*(max|plus|turbo|2\\.5)/.test(id)) {
69
+ return { contextWindow: 131072, maxTokens: 32000, hasImage: /vl/.test(id) };
70
+ }
71
+
72
+ // 未知模型默认兜底为 256K
73
+ return { contextWindow: DEFAULT_CONTEXT_WINDOW, maxTokens: DEFAULT_MAX_TOKENS, hasImage: false };
74
+ }
75
+
76
+ /**
77
+ * 优化单一模型配置(拦截 128K 矮截断并赋最优值)
78
+ */
79
+ function optimizeModel(model, onlineSpecs = {}) {
80
+ const id = model.id || "";
81
+ const cleanId = id.toLowerCase().replace(/^(3rd|linuxdo|ark|agy)\\//, "");
82
+ const online = onlineSpecs[cleanId] || onlineSpecs[id];
83
+
84
+ const inferred = inferModelSpec(id);
85
+
86
+ let cw = model.contextWindow;
87
+ let mt = model.maxTokens;
88
+ let input = Array.isArray(model.input) ? [...model.input] : ["text"];
89
+ let reasoning = model.reasoning;
90
+
91
+ // 当未设定或处于旧的 128K 兜底(<= 128000)时,自动触发提档
92
+ if (!cw || cw <= 128000) {
93
+ cw = online?.contextWindow || inferred.contextWindow || DEFAULT_CONTEXT_WINDOW;
94
+ }
95
+
96
+ // 保证 contextWindow 至少为 DEFAULT_CONTEXT_WINDOW
97
+ if (cw < DEFAULT_CONTEXT_WINDOW) {
98
+ cw = DEFAULT_CONTEXT_WINDOW;
99
+ }
100
+
101
+ if (!mt || mt === 32000) {
102
+ mt = online?.maxTokens || inferred.maxTokens || DEFAULT_MAX_TOKENS;
103
+ }
104
+
105
+ if ((inferred.hasImage || online?.hasImage) && !input.includes("image")) {
106
+ input.push("image");
107
+ }
108
+
109
+ if (inferred.reasoning && reasoning === undefined) {
110
+ reasoning = true;
111
+ }
112
+
113
+ return {
114
+ ...model,
115
+ contextWindow: cw,
116
+ maxTokens: mt,
117
+ input,
118
+ ...(reasoning !== undefined ? { reasoning } : {})
119
+ };
120
+ }
121
+
122
+ export default async function (pi) {
25
123
  const agentDir = process.env.OMP_CFG_ROOT || path.join(os.homedir(), ".omp", "agent");
124
+ const cacheDir = path.join(agentDir, "cache");
125
+ const cachePath = path.join(cacheDir, "model-specs.json");
26
126
  const localPath = path.join(agentDir, "models.local.json");
27
- if (!fs.existsSync(localPath)) return;
28
- try {
29
- const data = JSON.parse(fs.readFileSync(localPath, "utf8"));
30
- for (const [name, cfg] of Object.entries(data.providers || {})) {
31
- pi.registerProvider(name, cfg);
127
+
128
+ // 读取本地缓存的在线模型规格
129
+ let onlineSpecs = {};
130
+ if (fs.existsSync(cachePath)) {
131
+ try {
132
+ onlineSpecs = JSON.parse(fs.readFileSync(cachePath, "utf8"));
133
+ } catch {}
134
+ }
135
+
136
+ // 注册 Provider 并执行模型参数自适应优化
137
+ if (fs.existsSync(localPath)) {
138
+ try {
139
+ const data = JSON.parse(fs.readFileSync(localPath, "utf8"));
140
+ for (const [name, cfg] of Object.entries(data.providers || {})) {
141
+ const optimizedCfg = { ...cfg };
142
+ if (Array.isArray(cfg.models)) {
143
+ optimizedCfg.models = cfg.models.map(m => optimizeModel(m, onlineSpecs));
144
+ }
145
+ pi.registerProvider(name, optimizedCfg);
146
+ }
147
+ } catch (err) {
148
+ console.error("[local-models] Failed to load private providers:", err);
32
149
  }
33
- } catch (err) {
34
- console.error("[local-models] Failed to load private providers:", err);
35
150
  }
151
+
152
+ // 异步在后台静默刷新 OpenRouter 权威模型规格并落盘缓存
153
+ (async () => {
154
+ try {
155
+ const controller = new AbortController();
156
+ const timer = setTimeout(() => controller.abort(), 6000);
157
+ const res = await fetch("https://openrouter.ai/api/v1/models", { signal: controller.signal });
158
+ clearTimeout(timer);
159
+ if (!res.ok) return;
160
+ const json = await res.json();
161
+ const updatedSpecs = {};
162
+ for (const m of json.data || []) {
163
+ if (!m.id) continue;
164
+ const shortName = m.id.split("/").pop().toLowerCase();
165
+ const spec = {
166
+ contextWindow: m.context_length || DEFAULT_CONTEXT_WINDOW,
167
+ maxTokens: m.top_provider?.max_completion_tokens || DEFAULT_MAX_TOKENS,
168
+ hasImage: m.architecture?.modality?.includes("image") || false
169
+ };
170
+ updatedSpecs[shortName] = spec;
171
+ updatedSpecs[m.id.toLowerCase()] = spec;
172
+ }
173
+ if (!fs.existsSync(cacheDir)) {
174
+ fs.mkdirSync(cacheDir, { recursive: true });
175
+ }
176
+ fs.writeFileSync(cachePath, JSON.stringify(updatedSpecs, null, 2), "utf8");
177
+ } catch {}
178
+ })();
179
+
180
+ // 注册 /models-optimize 治理命令
181
+ pi.registerCommand("models-optimize", {
182
+ description: "一键洗牌优化 models.yml 与 models.local.json 中的模型上下文与输出参数(默认 256K 兜底)",
183
+ handler: async (args, ctx) => {
184
+ ctx.ui.notify("正在扫描并优化模型参数...", "info");
185
+ // 动态清洗 models.local.json
186
+ if (fs.existsSync(localPath)) {
187
+ try {
188
+ const raw = JSON.parse(fs.readFileSync(localPath, "utf8"));
189
+ let updated = false;
190
+ for (const p of Object.values(raw.providers || {})) {
191
+ if (Array.isArray(p.models)) {
192
+ p.models = p.models.map(m => {
193
+ const opt = optimizeModel(m, onlineSpecs);
194
+ if (opt.contextWindow !== m.contextWindow || opt.maxTokens !== m.maxTokens) {
195
+ updated = true;
196
+ }
197
+ return opt;
198
+ });
199
+ }
200
+ }
201
+ if (updated) {
202
+ fs.writeFileSync(localPath, JSON.stringify(raw, null, 2), "utf8");
203
+ }
204
+ } catch (e) {
205
+ ctx.ui.notify(\`优化 models.local.json 失败: \${e.message}\`, "error");
206
+ }
207
+ }
208
+ ctx.ui.notify("模型规格优化完成,默认上下文已对齐至 ≥256K", "info");
209
+ }
210
+ });
36
211
  }
37
212
  `;
38
213
 
39
214
  /**
40
- * Ensures ~/.omp/extensions/local-models.js exists so private models are ambiently registered.
215
+ * Ensures ~/.omp/agent/extensions/local-models.js exists for native extension scanning.
41
216
  */
42
217
  export function ensureLocalExtension(ompDir) {
43
- const extDir = path.join(ompDir, "extensions");
218
+ const extDir = path.join(ompDir, "agent", "extensions");
44
219
  if (!fs.existsSync(extDir)) {
45
220
  fs.mkdirSync(extDir, { recursive: true });
46
221
  }
@@ -124,7 +299,7 @@ export function parseYamlModels(str) {
124
299
  curModel.compat = {};
125
300
  continue;
126
301
  }
127
- if (inCompat && indent >= 8) {
302
+ if (inCompat && indent > 8) {
128
303
  const colonIdx = trimmed.indexOf(":");
129
304
  if (colonIdx > 0) {
130
305
  const k = trimmed.slice(0, colonIdx).trim();
@@ -136,6 +311,7 @@ export function parseYamlModels(str) {
136
311
  }
137
312
  continue;
138
313
  }
314
+ inCompat = false;
139
315
 
140
316
  const colonIdx = trimmed.indexOf(":");
141
317
  if (colonIdx > 0) {
@@ -162,6 +338,7 @@ export function parseYamlModels(str) {
162
338
  * Format providers object back to standard YAML.
163
339
  */
164
340
  export function formatYamlModels(providers) {
341
+ assertSupportedProviders(providers);
165
342
  let out = "providers:\n";
166
343
  for (const [name, cfg] of Object.entries(providers || {})) {
167
344
  out += ` ${name}:\n`;
@@ -175,7 +352,7 @@ export function formatYamlModels(providers) {
175
352
  for (const m of cfg.models) {
176
353
  out += ` - id: ${m.id}\n`;
177
354
  if (m.name) out += ` name: ${m.name}\n`;
178
- if (m.reasoning) out += ` reasoning: true\n`;
355
+ if (m.reasoning !== undefined) out += ` reasoning: ${m.reasoning}\n`;
179
356
  if (m.input) {
180
357
  const inp = Array.isArray(m.input) ? `[${m.input.join(",")}]` : m.input;
181
358
  out += ` input: ${inp}\n`;
@@ -211,11 +388,12 @@ export function readPublicProviders(agentDir) {
211
388
  * Write public providers to models.yml.
212
389
  */
213
390
  export function writePublicProviders(agentDir, providers) {
391
+ assertPublicSource(agentDir);
392
+ const content = formatYamlModels(providers);
214
393
  if (!fs.existsSync(agentDir)) {
215
394
  fs.mkdirSync(agentDir, { recursive: true });
216
395
  }
217
396
  const filePath = path.join(agentDir, "models.yml");
218
- const content = formatYamlModels(providers);
219
397
  fs.writeFileSync(filePath, content, "utf8");
220
398
  }
221
399
 
@@ -227,9 +405,13 @@ export function readPrivateProviders(agentDir) {
227
405
  if (!fs.existsSync(filePath)) return {};
228
406
  try {
229
407
  const json = JSON.parse(fs.readFileSync(filePath, "utf8"));
408
+ if (!json || typeof json !== "object" || Array.isArray(json) ||
409
+ (json.providers !== undefined && (!json.providers || typeof json.providers !== "object" || Array.isArray(json.providers)))) {
410
+ throw new Error("Expected providers mapping");
411
+ }
230
412
  return json.providers || {};
231
- } catch {
232
- return {};
413
+ } catch (error) {
414
+ throw new Error(`models.local.json 无法读取,未写入: ${error.message}`);
233
415
  }
234
416
  }
235
417
 
@@ -258,6 +440,7 @@ export function saveProvider({
258
440
  }
259
441
 
260
442
  const cleanConfig = {
443
+ ...providerConfig,
261
444
  private: Boolean(isPrivate),
262
445
  baseUrl: providerConfig.baseUrl,
263
446
  api: providerConfig.api || "openai-completions",
@@ -266,24 +449,19 @@ export function saveProvider({
266
449
  models: Array.isArray(providerConfig.models) ? providerConfig.models : [],
267
450
  };
268
451
 
269
- // Always save to models.yml so OMP /model natively sees and uses it
452
+ // Validate both stores and all formatter limitations before the first write.
270
453
  const pub = readPublicProviders(agentDir);
454
+ const priv = readPrivateProviders(agentDir);
271
455
  pub[name] = cleanConfig;
456
+ assertPublicSource(agentDir);
457
+ formatYamlModels(pub);
458
+ if (isPrivate) priv[name] = cleanConfig;
459
+ else delete priv[name];
272
460
  writePublicProviders(agentDir, pub);
273
-
274
- // Also record in models.local.json for redundancy
275
- if (isPrivate) {
276
- const priv = readPrivateProviders(agentDir);
277
- priv[name] = cleanConfig;
461
+ if (isPrivate || fs.existsSync(path.join(agentDir, "models.local.json"))) {
278
462
  writePrivateProviders(agentDir, priv);
279
- ensureLocalExtension(getOmpDir(agentDir));
280
- } else {
281
- const priv = readPrivateProviders(agentDir);
282
- if (priv[name]) {
283
- delete priv[name];
284
- writePrivateProviders(agentDir, priv);
285
- }
286
463
  }
464
+ if (isPrivate) ensureLocalExtension(getOmpDir(agentDir));
287
465
 
288
466
  return { name, isPrivate, providerConfig: cleanConfig };
289
467
  }
@@ -292,21 +470,16 @@ export function saveProvider({
292
470
  * Remove a provider from both stores.
293
471
  */
294
472
  export function removeProvider({ name, agentDir = getAgentDir() }) {
295
- let removed = false;
296
-
297
473
  const pub = readPublicProviders(agentDir);
298
- if (pub[name]) {
299
- delete pub[name];
300
- writePublicProviders(agentDir, pub);
301
- removed = true;
302
- }
303
-
304
474
  const priv = readPrivateProviders(agentDir);
305
- if (priv[name]) {
306
- delete priv[name];
307
- writePrivateProviders(agentDir, priv);
308
- removed = true;
309
- }
475
+ const removed = Boolean(pub[name] || priv[name]);
476
+ if (!removed) return false;
477
+ delete pub[name];
478
+ delete priv[name];
479
+ assertPublicSource(agentDir);
480
+ formatYamlModels(pub);
481
+ writePublicProviders(agentDir, pub);
482
+ if (fs.existsSync(path.join(agentDir, "models.local.json"))) writePrivateProviders(agentDir, priv);
310
483
 
311
484
  return removed;
312
485
  }
@@ -317,7 +490,7 @@ export function removeProvider({ name, agentDir = getAgentDir() }) {
317
490
  export function listProviders({ agentDir = getAgentDir() } = {}) {
318
491
  const pub = readPublicProviders(agentDir);
319
492
  const priv = readPrivateProviders(agentDir);
320
- const merged = { ...priv, ...pub };
493
+ const merged = { ...pub, ...priv };
321
494
 
322
495
  const list = [];
323
496
  for (const [name, cfg] of Object.entries(merged)) {
@@ -344,7 +517,64 @@ export function getProvider(name, { agentDir = getAgentDir() } = {}) {
344
517
  }
345
518
  const pub = readPublicProviders(agentDir);
346
519
  if (pub[name]) {
347
- return { name, isPrivate: false, ...pub[name] };
520
+ return { name, isPrivate: Boolean(pub[name].private), ...pub[name] };
348
521
  }
349
522
  return null;
350
523
  }
524
+
525
+ const PROVIDER_FIELDS = new Set(["private", "baseUrl", "api", "apiKey", "authHeader", "models"]);
526
+ const MODEL_FIELDS = new Set(["id", "name", "reasoning", "input", "contextWindow", "maxTokens", "compat"]);
527
+ function unsupported(field) {
528
+ throw new Error(`公开 YAML 格式不支持字段或结构 ${field};未写入`);
529
+ }
530
+ function assertSupportedProviders(providers) {
531
+ for (const [name, cfg] of Object.entries(providers || {})) {
532
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) unsupported(name);
533
+ if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) unsupported(name);
534
+ for (const [key, value] of Object.entries(cfg)) {
535
+ if (!PROVIDER_FIELDS.has(key)) unsupported(`${name}.${key}`);
536
+ if (key !== "models" && value !== null && typeof value === "object") unsupported(`${name}.${key}`);
537
+ if (typeof value === "string" && /[\r\n]/.test(value)) unsupported(`${name}.${key}`);
538
+ }
539
+ for (const model of cfg.models || []) {
540
+ for (const [key, value] of Object.entries(model)) {
541
+ if (!MODEL_FIELDS.has(key)) unsupported(`${name}.models.${key}`);
542
+ if (key === "compat") {
543
+ for (const [flag, setting] of Object.entries(value || {})) {
544
+ if (setting !== null && typeof setting === "object") unsupported(`${name}.models.compat.${flag}`);
545
+ }
546
+ } else if (key === "input") {
547
+ if (!Array.isArray(value) || value.some(item => typeof item !== "string")) unsupported(`${name}.models.input`);
548
+ } else if (value !== null && typeof value === "object" || typeof value === "string" && /[\r\n]/.test(value)) {
549
+ unsupported(`${name}.models.${key}`);
550
+ }
551
+ }
552
+ }
553
+ }
554
+ }
555
+ function assertPublicSource(agentDir) {
556
+ const file = ["models.yml", "models.yaml"].map(name => path.join(agentDir, name)).find(name => fs.existsSync(name));
557
+ if (!file) return;
558
+ // The fixed-field formatter cannot preserve arbitrary YAML. Reject unfamiliar structure.
559
+ let section = "", provider = "";
560
+ for (const line of fs.readFileSync(file, "utf8").split("\n")) {
561
+ const text = line.trim();
562
+ if (!text || text.startsWith("#")) continue;
563
+ const indent = line.search(/\S/);
564
+ const field = text.replace(/^-\s*/, "").split(":")[0];
565
+ if (indent === 0 && text === "providers:") { section = "providers"; continue; }
566
+ if (indent === 2 && /^[A-Za-z0-9][A-Za-z0-9_-]*:$/.test(text)) { provider = field; section = "provider"; continue; }
567
+ if (provider && indent === 4 && PROVIDER_FIELDS.has(field)) {
568
+ section = field === "models" && text === "models:" ? "models" : "provider";
569
+ if (section === "provider" && field !== "apiKey" && !text.slice(text.indexOf(":") + 1).trim()) unsupported(`${provider}.${field}`);
570
+ continue;
571
+ }
572
+ if (section === "models" || section === "model" || section === "compat") {
573
+ if (indent === 6 && text.startsWith("- ") && field === "id") { section = "model"; continue; }
574
+ if (indent === 8 && MODEL_FIELDS.has(field)) { section = field === "compat" ? "compat" : "model"; continue; }
575
+ if (indent === 10 && section === "compat" && /^[A-Za-z0-9_-]+:\s*\S/.test(text)) continue;
576
+ }
577
+ unsupported(`${provider || "root"}.${field}`);
578
+ }
579
+ assertSupportedProviders(readPublicProviders(agentDir));
580
+ }
package/src/rehydrator.js CHANGED
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
4
  import { execFileSync } from "node:child_process";
5
- import { ompHome } from "../index.js";
5
+ import { ompHome } from "./sync-files.js";
6
6
 
7
7
  const LINKS_FILE = ".plugin-links.json";
8
8