omp-config-crypt 0.9.6 → 0.9.8

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.
package/README.md CHANGED
@@ -112,6 +112,17 @@ recomputed once. Unfixable findings (missing npm, unreachable/wrong target) fail
112
112
  next-step commands. `/config-doctor` (or `omp-sync doctor [gist:<id>|https://url]`) runs the
113
113
  same checks standalone; exit code 1 when any check fails.
114
114
 
115
+ After a successful (non-dry-run) pull, every chat-model reference in the restored
116
+ `config.yml` (top-level `modelRoles` and `modelPresets.*.modelRoles`) is probed with one
117
+ short verified generation. Unavailable references are grouped by model: ONE dialog per
118
+ distinct unavailable model offers verified replacement candidates from the configured
119
+ providers (same provider first, the failed model itself excluded), and the chosen
120
+ replacement is applied to EVERY reference of that model in one pass (`:thinking`
121
+ suffixes preserved per reference). Selecting a candidate re-verifies it once, then
122
+ rewrites all affected roles; `保留不改`/Esc keeps the original and the refs are reported
123
+ as skipped. `web/*` roles are never probed. Headless hosts skip the flow with a summary
124
+ notification.
125
+
115
126
  ### Provider control menu
116
127
 
117
128
  Run `/provider` in an interactive OMP session for the native keyboard menu (↑↓ / Enter / Esc).
package/bin/omp-sync.js CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  exportEncrypted,
17
17
  importEncrypted,
18
18
  pullGist,
19
+ pushGist,
19
20
  pushHttp,
20
21
  pullHttp,
21
22
  rollback,
package/index.js CHANGED
@@ -54,6 +54,7 @@ import {
54
54
  formatYamlModels,
55
55
  } from "./src/provider-store.js";
56
56
  import { getRoles, setRole, VALID_ROLES } from "./src/role-manager.js";
57
+ import { runPullModelHeal } from "./src/role-healer.js";
57
58
  import { handleProviderCommand, providerCompletions } from "./src/provider-menu.js";
58
59
  import {
59
60
  runMaintenance,
@@ -1262,6 +1263,30 @@ export default function (pi) {
1262
1263
  ctx.ui.notify(`[dry-run]\n${formatSyncReport(r)}`, "info");
1263
1264
  } else {
1264
1265
  ctx.ui.notify(`restored ${r.files} files${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
1266
+ try {
1267
+ const heal = await runPullModelHeal(ctx, { root: configRoot(), notify: (msg, type) => ctx.ui.notify(msg, type) });
1268
+ if (heal && heal.applied.length > 0) {
1269
+ const byFrom = new Map();
1270
+ for (const a of heal.applied) {
1271
+ const groupKey = a.from.replace(/:[a-z]+$/, "");
1272
+ if (!byFrom.has(groupKey)) byFrom.set(groupKey, { to: a.to.replace(/:[a-z]+$/, ""), count: 0 });
1273
+ byFrom.get(groupKey).count++;
1274
+ }
1275
+ ctx.ui.notify(
1276
+ "[pull] 模型替换:\n" + [...byFrom.entries()].map(([from, g]) => ` ${from} -> ${g.to} (${g.count} 处)`).join("\n") +
1277
+ "\nrestart omp 生效",
1278
+ "info",
1279
+ );
1280
+ }
1281
+ if (heal && heal.skipped.length > 0) {
1282
+ ctx.ui.notify(
1283
+ "[pull] 未替换的不可用引用:\n" + heal.skipped.map((s) => ` ${s.pointer}: ${s.ref} (${s.reason})`).join("\n"),
1284
+ "warn",
1285
+ );
1286
+ }
1287
+ } catch (healError) {
1288
+ ctx.ui.notify(`model heal skipped: ${healError?.message ?? healError}`, "warn");
1289
+ }
1265
1290
  }
1266
1291
  } catch (error) {
1267
1292
  const report = error?.plan ? `\n${formatSyncReport(error.plan)}` : "";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.9.6",
3
+ "version": "0.9.8",
4
4
  "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Post-pull model availability healer.
3
+ *
4
+ * Scans every model reference in the restored config.yml (top-level modelRoles and
5
+ * modelPresets.*.modelRoles), probes each referenced model with one short verified
6
+ * generation, and offers an interactive replacement dialog for every reference that
7
+ * fails. Replacements are written back surgically with updateRoleInYaml, preserving
8
+ * comments and unrelated structure.
9
+ */
10
+
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { testModelCandidates } from "./provider-models.js";
14
+ import { listProviders } from "./provider-store.js";
15
+ import { updateRoleInYaml } from "./role-manager.js";
16
+
17
+ const ROLE_KEYS = ["advisor", "commit", "default", "judge", "memory", "plan", "slow", "smol", "task", "tiny", "vision"];
18
+ const PRESET_KEYS = ["fallback", "primary", "default", "fast", "deep"];
19
+
20
+ // web/* refs point at web-search tool backends (web/tavily), not chat models.
21
+ const WEB_ROLE = "web";
22
+
23
+ const THINKING_SUFFIX = /:(auto|minimal|low|medium|high|max)$/;
24
+
25
+ function parseModelRef(ref) {
26
+ if (typeof ref !== "string") return null;
27
+ const trimmed = ref.trim();
28
+ if (!trimmed || !trimmed.includes("/")) return null;
29
+ const slash = trimmed.indexOf("/");
30
+ const provider = trimmed.slice(0, slash);
31
+ if (!provider) return null;
32
+ let model = trimmed.slice(slash + 1);
33
+ if (!model) return null;
34
+ let thinking = null;
35
+ const suffix = model.match(THINKING_SUFFIX);
36
+ if (suffix) {
37
+ thinking = suffix[1];
38
+ model = model.slice(0, -suffix[0].length);
39
+ }
40
+ return { provider, model, thinking };
41
+ }
42
+
43
+ /**
44
+ * Collect model references from a parsed config.yml document.
45
+ * Returns [{ pointer, provider, model, thinking, ref }]; pointer uses the same
46
+ * dot-path shape as role-manager roles ("modelRoles" or "modelPresets.<k>.modelRoles").
47
+ */
48
+ export function collectModelRefs(configDoc) {
49
+ const refs = [];
50
+ const scanRoles = (roles, pointer) => {
51
+ if (!roles || typeof roles !== "object" || Array.isArray(roles)) return;
52
+ for (const [role, ref] of Object.entries(roles)) {
53
+ if (typeof ref !== "string" || role === WEB_ROLE) continue;
54
+ const parsed = parseModelRef(ref);
55
+ if (parsed) refs.push({ pointer: `${pointer}/${role}`, role, ...parsed, ref: ref.trim() });
56
+ }
57
+ };
58
+ const topRoles = configDoc?.modelRoles;
59
+ if (topRoles && typeof topRoles === "object" && !Array.isArray(topRoles)) {
60
+ for (const [role, ref] of Object.entries(topRoles)) {
61
+ if (typeof ref !== "string" || role === WEB_ROLE) continue;
62
+ const parsed = parseModelRef(ref);
63
+ if (parsed) refs.push({ pointer: `modelRoles/${role}`, role, ...parsed, ref: ref.trim() });
64
+ }
65
+ }
66
+ const presets = configDoc?.modelPresets;
67
+ if (presets && typeof presets === "object" && !Array.isArray(presets)) {
68
+ for (const presetKey of Object.keys(presets)) {
69
+ const preset = presets[presetKey];
70
+ if (!preset || typeof preset !== "object" || Array.isArray(preset)) continue;
71
+ scanRoles(preset.modelRoles, `modelPresets/${presetKey}/modelRoles`);
72
+ }
73
+ }
74
+ return refs;
75
+ }
76
+
77
+ /**
78
+ * Deduplicate refs by provider/model, probe each once with a short verified
79
+ * generation (reuses testModelCandidates' two-worker pool), then annotate.
80
+ * Returns [{ ...ref, ok, error, latencyMs }].
81
+ */
82
+ export async function checkModelRefs({ refs, providers, signal, onResult }) {
83
+ const providerMap = new Map();
84
+ for (const p of providers) providerMap.set(p.name, p);
85
+
86
+ const groups = new Map();
87
+ for (const ref of refs) {
88
+ const key = `${ref.provider}/${ref.model}`;
89
+ if (!groups.has(key)) {
90
+ const p = providerMap.get(ref.provider);
91
+ groups.set(key, {
92
+ key,
93
+ ref,
94
+ config: p ? { baseUrl: p.baseUrl, api: p.api, apiKey: p.apiKey } : null,
95
+ results: null,
96
+ });
97
+ }
98
+ }
99
+
100
+ for (const group of groups.values()) {
101
+ if (signal?.aborted) break;
102
+ if (!group.config) {
103
+ group.results = [{ id: group.key, ok: false, error: `provider '${group.ref.provider}' not configured`, latencyMs: 0 }];
104
+ continue;
105
+ }
106
+ const { results } = await testModelCandidates({
107
+ name: group.ref.provider,
108
+ config: group.config,
109
+ ids: [group.ref.model],
110
+ signal,
111
+ });
112
+ group.results = results.length > 0 ? results : [{ id: group.key, ok: false, error: "probe cancelled", latencyMs: 0 }];
113
+ }
114
+
115
+ const resultMap = new Map();
116
+ for (const group of groups.values()) resultMap.set(group.key, group.results[0]);
117
+
118
+ return refs.map((ref) => {
119
+ const result = resultMap.get(`${ref.provider}/${ref.model}`);
120
+ return { ...ref, ok: result.ok, error: result.error || undefined, latencyMs: result.latencyMs || 0 };
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Candidate replacements: all distinct provider/model pairs from the configured
126
+ * provider stores, excluding the failed ref itself. Sorted with same-provider
127
+ * candidates first.
128
+ */
129
+ export function replacementCandidates({ failedRef, providers }) {
130
+ const seen = new Set();
131
+ const candidates = [];
132
+ for (const p of providers) {
133
+ for (const m of p.models || []) {
134
+ if (!m?.id) continue;
135
+ const key = `${p.name}/${m.id}`;
136
+ if (key === `${failedRef.provider}/${failedRef.model}` || seen.has(key)) continue;
137
+ seen.add(key);
138
+ candidates.push({
139
+ key,
140
+ provider: p.name,
141
+ model: m.id,
142
+ baseUrl: p.baseUrl,
143
+ api: p.api,
144
+ apiKey: p.apiKey,
145
+ sameProvider: p.name === failedRef.provider,
146
+ isPrivate: Boolean(p.isPrivate),
147
+ capabilities: m,
148
+ });
149
+ }
150
+ }
151
+ return candidates.sort((a, b) =>
152
+ a.sameProvider === b.sameProvider ? a.key.localeCompare(b.key, "en", { numeric: true }) : a.sameProvider ? -1 : 1,
153
+ );
154
+ }
155
+
156
+ /**
157
+ * Probe the candidates until one verified generation succeeds (sequential, cheap first).
158
+ * Returns the winning "provider/model" key or null when every candidate fails.
159
+ */
160
+ export async function findWorkingReplacement({ candidates, signal }) {
161
+ for (const candidate of candidates) {
162
+ if (signal?.aborted) return null;
163
+ const { results } = await testModelCandidates({
164
+ name: candidate.provider,
165
+ config: { baseUrl: candidate.baseUrl, api: candidate.api, apiKey: candidate.apiKey },
166
+ ids: [candidate.model],
167
+ signal,
168
+ });
169
+ if (results.some((r) => r.ok)) return candidate.key;
170
+ }
171
+ return null;
172
+ }
173
+
174
+ /**
175
+ * Unified interactive repair flow over the checked refs. Groups failures by
176
+ * provider/model: ONE dialog per distinct unavailable model, and the chosen
177
+ * replacement is applied to EVERY reference of that model in one pass
178
+ * (identical thinking suffixes share the decision).
179
+ * Returns applied rewrites [{ pointer, role, from, to }] and skipped refs;
180
+ * never throws on user abort.
181
+ */
182
+ export async function healModelRefs({ ctx, checked, providers, configPath }) {
183
+ const applied = [];
184
+ const skipped = [];
185
+ const failures = checked.filter((r) => !r.ok);
186
+ if (failures.length === 0) return { applied, skipped };
187
+
188
+ // Group by distinct unavailable provider/model (thinking suffix is preserved
189
+ // per-ref at rewrite time, so grouping key is bare provider/model).
190
+ const groups = new Map();
191
+ for (const failed of failures) {
192
+ const key = `${failed.provider}/${failed.model}`;
193
+ if (!groups.has(key)) groups.set(key, { key, failed, refs: [] });
194
+ groups.get(key).refs.push(failed);
195
+ }
196
+
197
+ ctx.ui.notify(
198
+ `[pull] 发现 ${groups.size} 个不可用模型(${failures.length} 处引用),每个模型统一选择一次替代(每个候选 1 次短生成请求,可能产生费用;Esc 可跳过)`,
199
+ "info",
200
+ );
201
+
202
+ const text = fs.readFileSync(configPath, "utf8");
203
+ let updated = text;
204
+
205
+ for (const { key, failed, refs } of groups.values()) {
206
+ const candidates = replacementCandidates({ failedRef: failed, providers });
207
+ if (candidates.length === 0) {
208
+ for (const ref of refs) skipped.push({ ...ref, reason: "no replacement candidates configured" });
209
+ continue;
210
+ }
211
+
212
+ const locations = [...new Set(refs.map((r) => r.pointer))].join(", ");
213
+ const choice = await ctx.ui.select(
214
+ `模型不可用: ${key} (${failed.error}) · ${refs.length} 处引用 [${locations}]`,
215
+ ["保留不改", ...candidates.map((c) => c.key)],
216
+ { outline: true, helpText: "↑↓ 选择 · Enter 确认 · Esc 保留原值 · 所选替代应用到全部引用" },
217
+ );
218
+
219
+ if (!choice || choice === "保留不改") {
220
+ for (const ref of refs) skipped.push({ ...ref, reason: "user kept original" });
221
+ continue;
222
+ }
223
+
224
+ const chosen = candidates.find((c) => c.key === choice);
225
+ if (!chosen) {
226
+ for (const ref of refs) skipped.push({ ...ref, reason: `unknown selection: ${choice}` });
227
+ continue;
228
+ }
229
+
230
+ // Verify the chosen candidate once before rewriting (1 short generation).
231
+ const { results } = await testModelCandidates({
232
+ name: chosen.provider,
233
+ config: { baseUrl: chosen.baseUrl, api: chosen.api, apiKey: chosen.apiKey },
234
+ ids: [chosen.model],
235
+ });
236
+ if (!results.some((r) => r.ok)) {
237
+ const detail = `selected ${chosen.key} failed verification: ${results[0]?.error || "unknown"}`;
238
+ for (const ref of refs) skipped.push({ ...ref, reason: detail });
239
+ continue;
240
+ }
241
+
242
+ // Apply to every reference of this model; group applied by target for summary.
243
+ for (const ref of refs) {
244
+ const nextRef = chosen.key + (ref.thinking ? `:${ref.thinking}` : "");
245
+ updated = applyPointerRef(updated, ref.pointer, nextRef);
246
+ applied.push({ pointer: ref.pointer, role: ref.role, from: ref.ref, to: nextRef });
247
+ }
248
+ }
249
+
250
+ if (applied.length > 0) {
251
+ fs.writeFileSync(configPath, updated, "utf8");
252
+ }
253
+ return { applied, skipped };
254
+ }
255
+
256
+ /**
257
+ * Rewrite one model reference at `pointer` ("modelRoles/<role>" or
258
+ * "modelPresets/<k>/modelRoles/<role>") in raw config.yml text.
259
+ * Top-level roles reuse updateRoleInYaml; preset roles are rewritten with a
260
+ * targeted line scan that preserves the rest of the document.
261
+ */
262
+ export function applyPointerRef(yamlStr, pointer, modelRef) {
263
+ const tokens = pointer.split("/").filter(Boolean);
264
+ if (tokens[0] === "modelRoles" && tokens.length === 2) {
265
+ return updateRoleInYaml(yamlStr, tokens[1], modelRef);
266
+ }
267
+ if (tokens[0] === "modelPresets" && tokens.length === 4 && tokens[2] === "modelRoles") {
268
+ const [/*presets*/, presetKey, /*roles*/, role] = tokens;
269
+ const lines = yamlStr.split("\n");
270
+ let inPresets = false, inPreset = false, inRoles = false, depthRoles = -1, found = false;
271
+ const out = lines.map((line) => {
272
+ if (found) return line;
273
+ const indent = line.search(/\S/);
274
+ const trimmed = indent === -1 ? "" : line.trim();
275
+ if (!trimmed || trimmed.startsWith("#")) return line;
276
+ if (indent === 0) {
277
+ inPresets = trimmed === "modelPresets:";
278
+ inPreset = false; inRoles = false;
279
+ return line;
280
+ }
281
+ if (inPresets && indent === 2) {
282
+ inPreset = trimmed === `${presetKey}:`;
283
+ inRoles = false;
284
+ return line;
285
+ }
286
+ if (inPreset && indent === 4 && trimmed === "modelRoles:") {
287
+ inRoles = true; depthRoles = indent;
288
+ return line;
289
+ }
290
+ if (inRoles && indent > depthRoles) {
291
+ const match = line.match(/^(\s*)([A-Za-z0-9_-]+):(.*)$/);
292
+ if (match && match[2] === role) {
293
+ found = true;
294
+ return `${match[1]}${role}: ${modelRef}`;
295
+ }
296
+ } else if (inRoles && indent <= depthRoles) {
297
+ inRoles = false;
298
+ }
299
+ return line;
300
+ });
301
+ if (!found) throw new Error(`pointer not found in config.yml: ${pointer}`);
302
+ return out.join("\n");
303
+ }
304
+ throw new Error(`unsupported model role pointer: ${pointer}`);
305
+ }
306
+
307
+ /**
308
+ * Entry point used by /config-pull after a successful (non-dry-run) restore.
309
+ * Returns null when the host has no interactive UI or nothing failed.
310
+ */
311
+ export async function runPullModelHeal(ctx, { root, notify } = {}) {
312
+ if (typeof ctx?.ui?.select !== "function") return null;
313
+
314
+ const configPath = fs.existsSync(path.join(root, "config.yml"))
315
+ ? path.join(root, "config.yml")
316
+ : path.join(root, "config.yaml");
317
+ if (!fs.existsSync(configPath)) return null;
318
+
319
+ let doc;
320
+ try {
321
+ const { parseYamlStrict } = await import("./sync-resources.js");
322
+ doc = parseYamlStrict(fs.readFileSync(configPath, "utf8"), path.basename(configPath)).toJS();
323
+ } catch {
324
+ return null;
325
+ }
326
+
327
+ const refs = collectModelRefs(doc);
328
+ if (refs.length === 0) return null;
329
+
330
+ const providers = listProviders({ agentDir: root });
331
+ const checked = await checkModelRefs({ refs, providers });
332
+ const failureCount = checked.filter((r) => !r.ok).length;
333
+ notify?.(
334
+ failureCount === 0
335
+ ? `[pull] 模型体检: ${refs.length} 个引用全部可用`
336
+ : `[pull] 模型体检: ${checked.length - failureCount}/${checked.length} 可用, ${failureCount} 不可用`,
337
+ "info",
338
+ );
339
+ if (failureCount === 0) return { applied: [], skipped: [], checked };
340
+
341
+ const heal = await healModelRefs({ ctx, checked, providers, configPath });
342
+ return { ...heal, checked };
343
+ }