omp-config-crypt 0.9.5 → 0.9.7

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
@@ -1,4 +1,4 @@
1
- # omp-config-crypt (v0.7.0)
1
+ # omp-config-crypt (v0.9.6)
2
2
 
3
3
  Universal, zero-repair cross-platform configuration encryption and synchronization engine for `omp` (Oh My Pi).
4
4
 
@@ -62,6 +62,9 @@ npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN"
62
62
  # --strategy prefer-local keep local files and adopt them as the new baseline
63
63
  npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN" --strategy prefer-remote
64
64
 
65
+ # Keep every modelRoles leaf local (preset and top-level). Other conflicts still abort.
66
+ npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN" --local
67
+
65
68
  # Rollback to previous configuration snapshot
66
69
  npx omp-config-crypt rollback
67
70
 
@@ -95,8 +98,8 @@ Configuration exports include the installed `omp-config-crypt` source (excluding
95
98
  /config-push gist:new
96
99
  /config-push gist:<id>
97
100
  /config-push https://…
98
- /config-pull gist:<id> [--dry-run] [--force]
99
- /config-pull https://… [--dry-run] [--force]
101
+ /config-pull gist:<id> [--dry-run] [--force] [--local]
102
+ /config-pull https://… [--dry-run] [--force] [--local]
100
103
  /config-rollback
101
104
  /config-upgrade [--check]
102
105
  /config-doctor [gist:<id> | https://…]
@@ -109,6 +112,15 @@ recomputed once. Unfixable findings (missing npm, unreachable/wrong target) fail
109
112
  next-step commands. `/config-doctor` (or `omp-sync doctor [gist:<id>|https://url]`) runs the
110
113
  same checks standalone; exit code 1 when any check fails.
111
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 trigger an interactive dialog offering
118
+ verified replacement candidates from the configured providers (same provider first, the
119
+ failed model itself excluded; `:thinking` suffixes preserved). Selecting a candidate
120
+ re-verifies it, then rewrites the role in place; `保留不改`/Esc keeps the original and the
121
+ ref is reported as skipped. `web/*` roles are never probed. Headless hosts skip the flow
122
+ with a summary notification.
123
+
112
124
  ### Provider control menu
113
125
 
114
126
  Run `/provider` in an interactive OMP session for the native keyboard menu (↑↓ / Enter / Esc).
package/bin/omp-sync.js CHANGED
@@ -62,6 +62,8 @@ Commands:
62
62
  (--strategy prefer-remote|prefer-local auto-resolves
63
63
  conflicts by taking remote or local side; default:
64
64
  report conflicts and abort)
65
+ (--local keeps modelRoles leaves local and still
66
+ aborts on every other conflict)
65
67
  rollback Revert the most recent config restore from its backup
66
68
  doctor [target] Preflight env/config checks with self-healing
67
69
  (optional gist:<id> or https://url target)
@@ -91,6 +93,7 @@ Options:
91
93
  -y, --yes Non-interactive mode (use defaults without prompting)
92
94
  -f, --force Force operations (pull: adopt differing remote namespace)
93
95
  --strategy <mode> Conflict resolution for pull: prefer-remote | prefer-local
96
+ --local Keep modelRoles leaves local; other conflicts still abort
94
97
  --profile <name> Target specific profile scene (e.g. dev, ops)
95
98
 
96
99
  Environment Variables:
@@ -122,6 +125,7 @@ function parseCliArgs(argv) {
122
125
  nonInteractive: false,
123
126
  force: false,
124
127
  strategy: null,
128
+ keepLocal: false,
125
129
  checkOnly: false,
126
130
  positional: [],
127
131
  profile: null,
@@ -164,6 +168,8 @@ function parseCliArgs(argv) {
164
168
  options.strategy = args[++i];
165
169
  } else if (a.startsWith("--strategy=")) {
166
170
  options.strategy = a.slice(11);
171
+ } else if (a === "--local") {
172
+ options.keepLocal = true;
167
173
  } else if (a === "--check") {
168
174
  options.checkOnly = true;
169
175
  } else if (a === "--profile") {
@@ -323,6 +329,7 @@ async function main() {
323
329
  const res = importEncrypted(options.target, pass, root, {
324
330
  dryRun: options.dryRun,
325
331
  strategy: options.strategy,
332
+ keepLocalRoles: options.keepLocal,
326
333
  });
327
334
  if (res.adaptedFile) {
328
335
  console.log(`[import] incompatible v${res.legacy?.from}; adapted -> ${res.adaptedFile}`);
@@ -374,8 +381,8 @@ async function main() {
374
381
  const token = await resolveToken(options.token, target.kind === "gist");
375
382
  const res =
376
383
  target.kind === "gist"
377
- ? await pullGist(target.id, pass, root, token, { dryRun: options.dryRun, force: options.force, strategy: options.strategy })
378
- : await pullHttp(target.url, pass, root, token, { dryRun: options.dryRun, force: options.force, strategy: options.strategy });
384
+ ? await pullGist(target.id, pass, root, token, { dryRun: options.dryRun, force: options.force, strategy: options.strategy, keepLocalRoles: options.keepLocal })
385
+ : await pullHttp(target.url, pass, root, token, { dryRun: options.dryRun, force: options.force, strategy: options.strategy, keepLocalRoles: options.keepLocal });
379
386
  if (res.adoptedNamespace) {
380
387
  console.log(`[pull] Adopted remote namespace ${res.adoptedNamespace} (--force); prior policy/state saved as .bak`);
381
388
  }
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,
@@ -462,14 +463,14 @@ export function restoreArchive(blob, pass, root = configRoot(), options = {}) {
462
463
  repairUnreadablePlugins(effectivePayload, root, { install: options.installFn });
463
464
  }
464
465
 
465
- let plan = planSync(effectivePayload, root, { strategy: options.strategy });
466
+ let plan = planSync(effectivePayload, root, { strategy: options.strategy, keepLocalRoles: options.keepLocalRoles === true });
466
467
 
467
468
  // Self-healing stage 2: install plugin dependencies the plan blocked on, then replan
468
469
  // once (the install mutates the plugins tree, so the original plan is stale). Remaining
469
470
  // blocked actions still fail the apply.
470
471
  if (!dryRun && plan.prerequisites.length > 0 && options.autoFixPlugins !== false) {
471
472
  const fx = fixPluginPrerequisites(plan, root, { install: options.installFn, payload: effectivePayload });
472
- if (fx.fixed.length > 0) plan = planSync(effectivePayload, root, { strategy: options.strategy });
473
+ if (fx.fixed.length > 0) plan = planSync(effectivePayload, root, { strategy: options.strategy, keepLocalRoles: options.keepLocalRoles === true });
473
474
  }
474
475
 
475
476
  if (dryRun) {
@@ -890,12 +891,13 @@ export function parseSpec(spec) {
890
891
 
891
892
  export function extractDryRun(str) {
892
893
  const raw = String(str || "").trim();
893
- if (!raw) return { dryRun: false, force: false, strategy: null, clean: "" };
894
+ if (!raw) return { dryRun: false, force: false, strategy: null, keepLocal: false, clean: "" };
894
895
  const re = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^"\\]*)*)'|(\S+)/g;
895
896
  let match;
896
897
  let dryRun = false;
897
898
  let force = false;
898
899
  let strategy = null;
900
+ let keepLocal = false;
899
901
  const kept = [];
900
902
  const tokens = [];
901
903
  while ((match = re.exec(raw))) {
@@ -912,6 +914,10 @@ export function extractDryRun(str) {
912
914
  force = true;
913
915
  continue;
914
916
  }
917
+ if (token === "--local") {
918
+ keepLocal = true;
919
+ continue;
920
+ }
915
921
  if (token === "--strategy") {
916
922
  const value = tokens[++i];
917
923
  if (value === undefined || value.startsWith("-")) {
@@ -929,7 +935,7 @@ export function extractDryRun(str) {
929
935
  }
930
936
  kept.push(token);
931
937
  }
932
- return { dryRun, force, strategy, clean: kept.join(" ") };
938
+ return { dryRun, force, strategy, keepLocal, clean: kept.join(" ") };
933
939
  }
934
940
 
935
941
  export function formatSyncReport(result = {}) {
@@ -1167,14 +1173,14 @@ export default function (pi) {
1167
1173
  pi.registerCommand("config-import", {
1168
1174
  description: "Decrypt and restore an omp config archive (--dry-run to preview)",
1169
1175
  handler: async (args, ctx) => {
1170
- const { dryRun, strategy, clean: src } = extractDryRun(args || "");
1176
+ const { dryRun, strategy, keepLocal, clean: src } = extractDryRun(args || "");
1171
1177
  if (!src) {
1172
1178
  ctx.ui.notify("usage: /config-import <file.enc> [--dry-run] [--strategy prefer-remote|prefer-local]", "error");
1173
1179
  return;
1174
1180
  }
1175
1181
  try {
1176
1182
  const pass = await askPass(ctx, "Import passphrase");
1177
- const r = importEncrypted(src, pass, configRoot(), { dryRun, strategy });
1183
+ const r = importEncrypted(src, pass, configRoot(), { dryRun, strategy, keepLocalRoles: keepLocal });
1178
1184
  if (r.adaptedFile) {
1179
1185
  ctx.ui.notify(`[import] incompatible v${r.legacy?.from}; adapted -> ${r.adaptedFile}`, "info");
1180
1186
  }
@@ -1226,9 +1232,9 @@ export default function (pi) {
1226
1232
  const sel = await selectPublicResources(ctx, root);
1227
1233
  if (sel === null) return;
1228
1234
  }
1229
- const { dryRun, force, strategy, clean: spec } = extractDryRun(args || "");
1235
+ const { dryRun, force, strategy, keepLocal, clean: spec } = extractDryRun(args || "");
1230
1236
  if (!spec) {
1231
- ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run] [--force] [--strategy prefer-remote|prefer-local]", "error");
1237
+ ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run] [--force] [--strategy prefer-remote|prefer-local] [--local]", "error");
1232
1238
  return;
1233
1239
  }
1234
1240
  try {
@@ -1236,8 +1242,8 @@ export default function (pi) {
1236
1242
  const pass = await askPass(ctx, "Pull passphrase");
1237
1243
  const token = await askToken(ctx, "Cloud token", target.kind === "gist");
1238
1244
  const r = target.kind === "gist"
1239
- ? await pullGist(target.id, pass, configRoot(), token, { dryRun, force, strategy })
1240
- : await pullHttp(target.url, pass, configRoot(), token, { dryRun, force, strategy });
1245
+ ? await pullGist(target.id, pass, configRoot(), token, { dryRun, force, strategy, keepLocalRoles: keepLocal })
1246
+ : await pullHttp(target.url, pass, configRoot(), token, { dryRun, force, strategy, keepLocalRoles: keepLocal });
1241
1247
  if (Array.isArray(r.preflight) && r.preflight.length > 0) {
1242
1248
  ctx.ui.notify(
1243
1249
  "[pull] preflight:\n" + r.preflight.map((c) => ` [${c.status.toUpperCase()}] ${c.id}: ${c.detail}`).join("\n"),
@@ -1257,6 +1263,24 @@ export default function (pi) {
1257
1263
  ctx.ui.notify(`[dry-run]\n${formatSyncReport(r)}`, "info");
1258
1264
  } else {
1259
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
+ ctx.ui.notify(
1270
+ "[pull] 模型替换:\n" + heal.applied.map((a) => ` ${a.pointer}: ${a.from} -> ${a.to}`).join("\n") +
1271
+ "\nrestart omp 生效",
1272
+ "info",
1273
+ );
1274
+ }
1275
+ if (heal && heal.skipped.length > 0) {
1276
+ ctx.ui.notify(
1277
+ "[pull] 未替换的不可用引用:\n" + heal.skipped.map((s) => ` ${s.pointer}: ${s.ref} (${s.reason})`).join("\n"),
1278
+ "warn",
1279
+ );
1280
+ }
1281
+ } catch (healError) {
1282
+ ctx.ui.notify(`model heal skipped: ${healError?.message ?? healError}`, "warn");
1283
+ }
1260
1284
  }
1261
1285
  } catch (error) {
1262
1286
  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.5",
3
+ "version": "0.9.7",
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,331 @@
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
+ * Interactive repair flow over the checked refs. Returns applied rewrites
176
+ * [{ pointer, role, from, to }] and skipped refs; never throws on user abort.
177
+ * All probes inside run with a 10s timeout each, two parallel at most
178
+ * (testModelCandidates contract); the caller surfaces cost notice beforehand.
179
+ */
180
+ export async function healModelRefs({ ctx, checked, providers, configPath }) {
181
+ const applied = [];
182
+ const skipped = [];
183
+ const failures = checked.filter((r) => !r.ok);
184
+ if (failures.length === 0) return { applied, skipped };
185
+
186
+ ctx.ui.notify(
187
+ `[pull] 发现 ${failures.length} 个模型引用不可用,将逐一探测候选替代(每个候选 1 次短生成请求,可能产生费用;Esc 可跳过)`,
188
+ "info",
189
+ );
190
+
191
+ const text = fs.readFileSync(configPath, "utf8");
192
+ let updated = text;
193
+
194
+ for (const failed of failures) {
195
+ const candidates = replacementCandidates({ failedRef: failed, providers });
196
+ if (candidates.length === 0) {
197
+ skipped.push({ ...failed, reason: "no replacement candidates configured" });
198
+ continue;
199
+ }
200
+
201
+ const choice = await ctx.ui.select(
202
+ `模型不可用: ${failed.provider}/${failed.model} (${failed.error}) @ ${failed.pointer}`,
203
+ ["保留不改", ...candidates.map((c) => c.key)],
204
+ { outline: true, helpText: "↑↓ 选择 · Enter 确认 · Esc 保留原值" },
205
+ );
206
+
207
+ if (!choice || choice === "保留不改") {
208
+ skipped.push({ ...failed, reason: "user kept original" });
209
+ continue;
210
+ }
211
+
212
+ const chosen = candidates.find((c) => c.key === choice);
213
+ if (!chosen) {
214
+ skipped.push({ ...failed, reason: `unknown selection: ${choice}` });
215
+ continue;
216
+ }
217
+
218
+ // Verify the chosen candidate before rewriting (1 short generation).
219
+ const { results } = await testModelCandidates({
220
+ name: chosen.provider,
221
+ config: {
222
+ baseUrl: chosen.baseUrl,
223
+ api: chosen.api,
224
+ apiKey: chosen.apiKey,
225
+ },
226
+ ids: [chosen.model],
227
+ });
228
+ if (!results.some((r) => r.ok)) {
229
+ skipped.push({ ...failed, reason: `selected ${chosen.key} failed verification: ${results[0]?.error || "unknown"}` });
230
+ continue;
231
+ }
232
+
233
+ const nextRef = chosen.key + (failed.thinking ? `:${failed.thinking}` : "");
234
+ updated = applyPointerRef(updated, failed.pointer, nextRef);
235
+ applied.push({ pointer: failed.pointer, role: failed.role, from: failed.ref, to: nextRef });
236
+ }
237
+
238
+ if (applied.length > 0) {
239
+ fs.writeFileSync(configPath, updated, "utf8");
240
+ }
241
+ return { applied, skipped };
242
+ }
243
+
244
+ /**
245
+ * Rewrite one model reference at `pointer` ("modelRoles/<role>" or
246
+ * "modelPresets/<k>/modelRoles/<role>") in raw config.yml text.
247
+ * Top-level roles reuse updateRoleInYaml; preset roles are rewritten with a
248
+ * targeted line scan that preserves the rest of the document.
249
+ */
250
+ export function applyPointerRef(yamlStr, pointer, modelRef) {
251
+ const tokens = pointer.split("/").filter(Boolean);
252
+ if (tokens[0] === "modelRoles" && tokens.length === 2) {
253
+ return updateRoleInYaml(yamlStr, tokens[1], modelRef);
254
+ }
255
+ if (tokens[0] === "modelPresets" && tokens.length === 4 && tokens[2] === "modelRoles") {
256
+ const [/*presets*/, presetKey, /*roles*/, role] = tokens;
257
+ const lines = yamlStr.split("\n");
258
+ let inPresets = false, inPreset = false, inRoles = false, depthRoles = -1, found = false;
259
+ const out = lines.map((line) => {
260
+ if (found) return line;
261
+ const indent = line.search(/\S/);
262
+ const trimmed = indent === -1 ? "" : line.trim();
263
+ if (!trimmed || trimmed.startsWith("#")) return line;
264
+ if (indent === 0) {
265
+ inPresets = trimmed === "modelPresets:";
266
+ inPreset = false; inRoles = false;
267
+ return line;
268
+ }
269
+ if (inPresets && indent === 2) {
270
+ inPreset = trimmed === `${presetKey}:`;
271
+ inRoles = false;
272
+ return line;
273
+ }
274
+ if (inPreset && indent === 4 && trimmed === "modelRoles:") {
275
+ inRoles = true; depthRoles = indent;
276
+ return line;
277
+ }
278
+ if (inRoles && indent > depthRoles) {
279
+ const match = line.match(/^(\s*)([A-Za-z0-9_-]+):(.*)$/);
280
+ if (match && match[2] === role) {
281
+ found = true;
282
+ return `${match[1]}${role}: ${modelRef}`;
283
+ }
284
+ } else if (inRoles && indent <= depthRoles) {
285
+ inRoles = false;
286
+ }
287
+ return line;
288
+ });
289
+ if (!found) throw new Error(`pointer not found in config.yml: ${pointer}`);
290
+ return out.join("\n");
291
+ }
292
+ throw new Error(`unsupported model role pointer: ${pointer}`);
293
+ }
294
+
295
+ /**
296
+ * Entry point used by /config-pull after a successful (non-dry-run) restore.
297
+ * Returns null when the host has no interactive UI or nothing failed.
298
+ */
299
+ export async function runPullModelHeal(ctx, { root, notify } = {}) {
300
+ if (typeof ctx?.ui?.select !== "function") return null;
301
+
302
+ const configPath = fs.existsSync(path.join(root, "config.yml"))
303
+ ? path.join(root, "config.yml")
304
+ : path.join(root, "config.yaml");
305
+ if (!fs.existsSync(configPath)) return null;
306
+
307
+ let doc;
308
+ try {
309
+ const { parseYamlStrict } = await import("./sync-resources.js");
310
+ doc = parseYamlStrict(fs.readFileSync(configPath, "utf8"), path.basename(configPath)).toJS();
311
+ } catch {
312
+ return null;
313
+ }
314
+
315
+ const refs = collectModelRefs(doc);
316
+ if (refs.length === 0) return null;
317
+
318
+ const providers = listProviders({ agentDir: root });
319
+ const checked = await checkModelRefs({ refs, providers });
320
+ const failureCount = checked.filter((r) => !r.ok).length;
321
+ notify?.(
322
+ failureCount === 0
323
+ ? `[pull] 模型体检: ${refs.length} 个引用全部可用`
324
+ : `[pull] 模型体检: ${checked.length - failureCount}/${checked.length} 可用, ${failureCount} 不可用`,
325
+ "info",
326
+ );
327
+ if (failureCount === 0) return { applied: [], skipped: [], checked };
328
+
329
+ const heal = await healModelRefs({ ctx, checked, providers, configPath });
330
+ return { ...heal, checked };
331
+ }
package/src/sync-plan.js CHANGED
@@ -764,11 +764,19 @@ export function adaptLegacySnapshot(snapshot) {
764
764
  */
765
765
  export const SYNC_STRATEGIES = new Set(["manual", "prefer-remote", "prefer-local"]);
766
766
 
767
+ function isModelRoleSetting(id) {
768
+ if (!id.startsWith("setting:")) return false;
769
+ const tokens = id.slice("setting:".length).split("/").filter(Boolean);
770
+ const at = tokens.lastIndexOf("modelRoles");
771
+ return at >= 0 && at === tokens.length - 2;
772
+ }
773
+
767
774
  export function planSync(snapshot, root = configRoot(), options = {}) {
768
775
  const strategy = options.strategy == null || options.strategy === undefined ? "manual" : options.strategy;
769
776
  if (!SYNC_STRATEGIES.has(strategy)) {
770
777
  throw new Error(`Invalid sync strategy '${strategy}'; expected one of: ${Array.from(SYNC_STRATEGIES).join(", ")}`);
771
778
  }
779
+ const keepLocalRoles = options.keepLocalRoles === true;
772
780
  const validSnapshot = validateSnapshot(snapshot);
773
781
  const policy = readSyncPolicy(root);
774
782
  const state = readSyncState(root);
@@ -1013,6 +1021,15 @@ export function planSync(snapshot, root = configRoot(), options = {}) {
1013
1021
  }
1014
1022
  }
1015
1023
 
1024
+ // --local: modelRoles leaves stay local. Other conflicts still abort the plan.
1025
+ if (plannedAction === "conflict" && keepLocalRoles && isModelRoleSetting(id)) {
1026
+ plannedAction = localPresent ? "keep" : "delete";
1027
+ reason = "conflict-resolved-local-role";
1028
+ acceptedTransitions.set(id, localPresent
1029
+ ? { hash: localHash, tombstone: false }
1030
+ : { hash: SENTINEL_DELETED, tombstone: true });
1031
+ }
1032
+
1016
1033
  // Check for plugin prerequisite if plannedAction is add or update
1017
1034
  if ((plannedAction === "add" || plannedAction === "update") && id.startsWith("plugin:")) {
1018
1035
  const pluginName = id.slice("plugin:".length);