omp-config-crypt 0.9.4 → 0.9.6

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://…]
@@ -148,7 +151,7 @@ Pika, Vidu, Wanx, SDXL, Imagen, Ideogram, Kolors, `*-image`, `*-video`) while st
148
151
  The summary supports rechecking all selected models; failed, cancelled or unstarted rechecks cannot inherit
149
152
  previous successes. Check results, source labels and latency remain in memory and are not saved. `/provider test`
150
153
  checks one model and reports its latency; it does not claim the entire provider is verified.
151
- Draft cancellation does not write; saved changes load after restarting OMP.
154
+ Draft cancellation does not write. In-session interactive and non-UI `/provider` add, edit, and deletion synchronize immediately into the active OMP session's model catalog (`/models`). If the current session model belongs to a provider whose configuration is deleted or edited without that model ID, an alternative model must be selected before writing; if no replacement model is available, or if the current model is actively generating, the operation is blocked with zero configuration writes. If model catalog synchronization fails, configuration writes remain preserved on disk and a warning notification is displayed. Standalone `omp-sync` and other external OMP processes operate strictly at the file level and load changes upon their next startup.
152
155
  PRIVATE is the default and is excluded by encrypted-sync filtering; PUBLIC includes credentials
153
156
  in encrypted synchronization. Private providers remain mirrored in both existing stores.
154
157
  Background maintenance preserves the active `models.local.json` store; only obsolete root-level
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
@@ -462,14 +462,14 @@ export function restoreArchive(blob, pass, root = configRoot(), options = {}) {
462
462
  repairUnreadablePlugins(effectivePayload, root, { install: options.installFn });
463
463
  }
464
464
 
465
- let plan = planSync(effectivePayload, root, { strategy: options.strategy });
465
+ let plan = planSync(effectivePayload, root, { strategy: options.strategy, keepLocalRoles: options.keepLocalRoles === true });
466
466
 
467
467
  // Self-healing stage 2: install plugin dependencies the plan blocked on, then replan
468
468
  // once (the install mutates the plugins tree, so the original plan is stale). Remaining
469
469
  // blocked actions still fail the apply.
470
470
  if (!dryRun && plan.prerequisites.length > 0 && options.autoFixPlugins !== false) {
471
471
  const fx = fixPluginPrerequisites(plan, root, { install: options.installFn, payload: effectivePayload });
472
- if (fx.fixed.length > 0) plan = planSync(effectivePayload, root, { strategy: options.strategy });
472
+ if (fx.fixed.length > 0) plan = planSync(effectivePayload, root, { strategy: options.strategy, keepLocalRoles: options.keepLocalRoles === true });
473
473
  }
474
474
 
475
475
  if (dryRun) {
@@ -890,12 +890,13 @@ export function parseSpec(spec) {
890
890
 
891
891
  export function extractDryRun(str) {
892
892
  const raw = String(str || "").trim();
893
- if (!raw) return { dryRun: false, force: false, strategy: null, clean: "" };
893
+ if (!raw) return { dryRun: false, force: false, strategy: null, keepLocal: false, clean: "" };
894
894
  const re = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^"\\]*)*)'|(\S+)/g;
895
895
  let match;
896
896
  let dryRun = false;
897
897
  let force = false;
898
898
  let strategy = null;
899
+ let keepLocal = false;
899
900
  const kept = [];
900
901
  const tokens = [];
901
902
  while ((match = re.exec(raw))) {
@@ -912,6 +913,10 @@ export function extractDryRun(str) {
912
913
  force = true;
913
914
  continue;
914
915
  }
916
+ if (token === "--local") {
917
+ keepLocal = true;
918
+ continue;
919
+ }
915
920
  if (token === "--strategy") {
916
921
  const value = tokens[++i];
917
922
  if (value === undefined || value.startsWith("-")) {
@@ -929,7 +934,7 @@ export function extractDryRun(str) {
929
934
  }
930
935
  kept.push(token);
931
936
  }
932
- return { dryRun, force, strategy, clean: kept.join(" ") };
937
+ return { dryRun, force, strategy, keepLocal, clean: kept.join(" ") };
933
938
  }
934
939
 
935
940
  export function formatSyncReport(result = {}) {
@@ -1167,14 +1172,14 @@ export default function (pi) {
1167
1172
  pi.registerCommand("config-import", {
1168
1173
  description: "Decrypt and restore an omp config archive (--dry-run to preview)",
1169
1174
  handler: async (args, ctx) => {
1170
- const { dryRun, strategy, clean: src } = extractDryRun(args || "");
1175
+ const { dryRun, strategy, keepLocal, clean: src } = extractDryRun(args || "");
1171
1176
  if (!src) {
1172
1177
  ctx.ui.notify("usage: /config-import <file.enc> [--dry-run] [--strategy prefer-remote|prefer-local]", "error");
1173
1178
  return;
1174
1179
  }
1175
1180
  try {
1176
1181
  const pass = await askPass(ctx, "Import passphrase");
1177
- const r = importEncrypted(src, pass, configRoot(), { dryRun, strategy });
1182
+ const r = importEncrypted(src, pass, configRoot(), { dryRun, strategy, keepLocalRoles: keepLocal });
1178
1183
  if (r.adaptedFile) {
1179
1184
  ctx.ui.notify(`[import] incompatible v${r.legacy?.from}; adapted -> ${r.adaptedFile}`, "info");
1180
1185
  }
@@ -1226,9 +1231,9 @@ export default function (pi) {
1226
1231
  const sel = await selectPublicResources(ctx, root);
1227
1232
  if (sel === null) return;
1228
1233
  }
1229
- const { dryRun, force, strategy, clean: spec } = extractDryRun(args || "");
1234
+ const { dryRun, force, strategy, keepLocal, clean: spec } = extractDryRun(args || "");
1230
1235
  if (!spec) {
1231
- ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run] [--force] [--strategy prefer-remote|prefer-local]", "error");
1236
+ ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run] [--force] [--strategy prefer-remote|prefer-local] [--local]", "error");
1232
1237
  return;
1233
1238
  }
1234
1239
  try {
@@ -1236,8 +1241,8 @@ export default function (pi) {
1236
1241
  const pass = await askPass(ctx, "Pull passphrase");
1237
1242
  const token = await askToken(ctx, "Cloud token", target.kind === "gist");
1238
1243
  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 });
1244
+ ? await pullGist(target.id, pass, configRoot(), token, { dryRun, force, strategy, keepLocalRoles: keepLocal })
1245
+ : await pullHttp(target.url, pass, configRoot(), token, { dryRun, force, strategy, keepLocalRoles: keepLocal });
1241
1246
  if (Array.isArray(r.preflight) && r.preflight.length > 0) {
1242
1247
  ctx.ui.notify(
1243
1248
  "[pull] preflight:\n" + r.preflight.map((c) => ` [${c.status.toUpperCase()}] ${c.id}: ${c.detail}`).join("\n"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.9.4",
3
+ "version": "0.9.6",
4
4
  "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -11,7 +11,9 @@
11
11
  "omp-sync": "./bin/omp-sync.js"
12
12
  },
13
13
  "scripts": {
14
- "test": "node test/sync-portable.test.mjs"
14
+ "test": "node test/sync-portable.test.mjs",
15
+ "eval": "node eval/change-eval.mjs",
16
+ "eval:gate": "omp-agent-eval"
15
17
  },
16
18
  "keywords": [
17
19
  "omp",
@@ -8,6 +8,214 @@ const DIALOG = { outline: true, helpText: "↑↓ 选择 · Enter 确认 · Esc
8
8
  const select = (ctx, title, options) => ctx.ui.select(title, options, DIALOG);
9
9
  const rolesFor = (name, agentDir) => Object.entries(getRoles(agentDir))
10
10
  .filter(([, ref]) => ref.startsWith(`${name}/`)).map(([role]) => role);
11
+ const DEFAULT_CONTEXT_WINDOW = 256000;
12
+ const DEFAULT_MAX_TOKENS = 65536;
13
+
14
+ function inferModelSpec(modelId) {
15
+ const id = (modelId || "").toLowerCase();
16
+ if (/gemini.*pro/.test(id)) {
17
+ return { contextWindow: 2000000, maxTokens: 65536, hasImage: true };
18
+ }
19
+ if (/gemini.*(flash|lite)/.test(id)) {
20
+ return { contextWindow: 1000000, maxTokens: 65536, hasImage: true };
21
+ }
22
+ if (/deepseek.*(v4|pro|flash)/.test(id)) {
23
+ return { contextWindow: 1048576, maxTokens: 65536, hasImage: /flash|vl/.test(id) };
24
+ }
25
+ if (/deepseek/.test(id)) {
26
+ return { contextWindow: 1048576, maxTokens: 32000, hasImage: /vl/.test(id) };
27
+ }
28
+ if (/kimi|moonshot/.test(id)) {
29
+ return { contextWindow: 512000, maxTokens: 32000, hasImage: false };
30
+ }
31
+ if (/claude/.test(id)) {
32
+ return { contextWindow: 200000, maxTokens: 64000, hasImage: true };
33
+ }
34
+ if (/(gpt-6|gpt-5\.[0-9]).*(sol|terra)/.test(id)) {
35
+ return { contextWindow: 256000, maxTokens: 384000, reasoning: true, hasImage: false };
36
+ }
37
+ if (/gpt-6|astra/.test(id)) {
38
+ return { contextWindow: 256000, maxTokens: 32000, hasImage: false };
39
+ }
40
+ if (/qwen.*(max|plus|turbo|2\.5)/.test(id)) {
41
+ return { contextWindow: 131072, maxTokens: 32000, hasImage: /vl/.test(id) };
42
+ }
43
+ return { contextWindow: DEFAULT_CONTEXT_WINDOW, maxTokens: DEFAULT_MAX_TOKENS, hasImage: false };
44
+ }
45
+
46
+ function optimizeRuntimeModel(model) {
47
+ const id = model.id || "";
48
+ const inferred = inferModelSpec(id);
49
+ let cw = model.contextWindow;
50
+ let mt = model.maxTokens;
51
+ let input = Array.isArray(model.input) ? [...model.input] : ["text"];
52
+ let reasoning = model.reasoning;
53
+
54
+ if (!cw || cw <= 128000) {
55
+ cw = inferred.contextWindow || DEFAULT_CONTEXT_WINDOW;
56
+ }
57
+ if (cw < DEFAULT_CONTEXT_WINDOW) {
58
+ cw = DEFAULT_CONTEXT_WINDOW;
59
+ }
60
+ if (!mt || mt === 32000) {
61
+ mt = inferred.maxTokens || DEFAULT_MAX_TOKENS;
62
+ }
63
+ if (inferred.hasImage && !input.includes("image")) {
64
+ input.push("image");
65
+ }
66
+ if (inferred.reasoning && reasoning === undefined) {
67
+ reasoning = true;
68
+ }
69
+ return {
70
+ ...model,
71
+ contextWindow: cw,
72
+ maxTokens: mt,
73
+ input,
74
+ ...(reasoning !== undefined ? { reasoning } : {})
75
+ };
76
+ }
77
+
78
+ export function runtimeConfig(provider) {
79
+ const isPrivate = Boolean(provider.isPrivate || provider.private);
80
+ let models = Array.isArray(provider.models) ? provider.models : [];
81
+ if (isPrivate) {
82
+ models = models.map(m => optimizeRuntimeModel(m));
83
+ } else {
84
+ models = models.map(m => ({ ...m }));
85
+ }
86
+ const cfg = {
87
+ api: provider.api,
88
+ baseUrl: provider.baseUrl,
89
+ apiKey: provider.apiKey,
90
+ models,
91
+ };
92
+ if (provider.authHeader !== undefined) {
93
+ cfg.authHeader = provider.authHeader;
94
+ }
95
+ return cfg;
96
+ }
97
+
98
+ export function currentModel(ctx) {
99
+ try {
100
+ if (typeof ctx?.models?.current === "function") {
101
+ const cur = ctx.models.current();
102
+ if (cur) return cur;
103
+ }
104
+ } catch {}
105
+ try {
106
+ if (ctx?.model) return ctx.model;
107
+ } catch {}
108
+ return null;
109
+ }
110
+
111
+ export async function refreshRegistry(ctx) {
112
+ if (typeof ctx?.modelRegistry?.refresh === "function") {
113
+ await ctx.modelRegistry.refresh();
114
+ }
115
+ }
116
+
117
+ export async function registerRuntimeProvider(pi, ctx, provider) {
118
+ const name = provider.name || provider.id;
119
+ const isPrivate = Boolean(provider.isPrivate || provider.private);
120
+ if (isPrivate) {
121
+ if (typeof pi?.registerProvider !== "function") {
122
+ throw new Error("模型目录同步不可用");
123
+ }
124
+ pi.registerProvider(name, runtimeConfig(provider));
125
+ }
126
+ if (!isPrivate && typeof ctx?.modelRegistry?.refresh !== "function") {
127
+ throw new Error("模型目录同步不可用");
128
+ }
129
+ await refreshRegistry(ctx);
130
+ }
131
+
132
+ export async function syncRemovedProvider(pi, ctx, name, wasPrivate) {
133
+ if (wasPrivate) {
134
+ if (typeof pi?.unregisterProvider !== "function") {
135
+ throw new Error("模型目录同步不可用");
136
+ }
137
+ await pi.unregisterProvider(name);
138
+ }
139
+ if (!wasPrivate && typeof ctx?.modelRegistry?.refresh !== "function") {
140
+ throw new Error("模型目录同步不可用");
141
+ }
142
+ await refreshRegistry(ctx);
143
+ }
144
+
145
+ export function availableModels(ctx) {
146
+ try {
147
+ if (typeof ctx?.modelRegistry?.getAvailable === "function") {
148
+ const list = ctx.modelRegistry.getAvailable();
149
+ if (Array.isArray(list)) return list;
150
+ }
151
+ } catch {}
152
+ return [];
153
+ }
154
+
155
+ export async function ensureCurrentModel(pi, ctx, { provider, modelId, modelIds, action }) {
156
+ const cur = currentModel(ctx);
157
+ if (!cur || cur.provider !== provider) return true;
158
+
159
+ if (typeof ctx?.waitForIdle === "function") {
160
+ await ctx.waitForIdle();
161
+ }
162
+ if (typeof ctx?.isIdle === "function" && !ctx.isIdle()) {
163
+ ctx.ui?.notify?.(`当前模型正在响应,完成后再${action}`, "warning");
164
+ return false;
165
+ }
166
+
167
+ if (action === "保存") {
168
+ const ids = Array.isArray(modelIds)
169
+ ? modelIds
170
+ : (Array.isArray(modelId) ? modelId : (modelId ? [modelId] : []));
171
+ if (ids.includes(cur.id)) {
172
+ return true;
173
+ }
174
+ }
175
+
176
+ const candidateMap = new Map();
177
+ for (const m of availableModels(ctx)) {
178
+ if (m?.provider && m?.id && m.provider !== provider) {
179
+ const key = `${m.provider}/${m.id}`;
180
+ if (!candidateMap.has(key)) candidateMap.set(key, m);
181
+ }
182
+ }
183
+
184
+ const options = Array.from(candidateMap.keys());
185
+ if (!options.length) {
186
+ ctx.ui?.notify?.(`没有可切换的其它模型,未${action}`, "warning");
187
+ return false;
188
+ }
189
+
190
+ if (!ctx?.hasUI) {
191
+ ctx.ui?.notify?.(`当前模型属于 ${provider},请先使用 /model 切换后再${action}`, "warning");
192
+ return false;
193
+ }
194
+
195
+ const chosenKey = await select(ctx, "当前模型将被移除,请选择替代模型", options);
196
+ if (!chosenKey) return false;
197
+
198
+ const chosenModel = candidateMap.get(chosenKey);
199
+ try {
200
+ if (typeof pi?.setModel !== "function") {
201
+ throw new Error("宿主不支持 setModel");
202
+ }
203
+ await pi.setModel(chosenModel);
204
+ } catch (err) {
205
+ ctx.ui?.notify?.(`切换模型失败: ${err.message}`, "error");
206
+ return false;
207
+ }
208
+
209
+ const newCur = currentModel(ctx);
210
+ if (!newCur || newCur.provider !== chosenModel.provider || newCur.id !== chosenModel.id) {
211
+ ctx.ui?.notify?.(`切换模型失败: 无法激活 ${chosenKey}`, "error");
212
+ return false;
213
+ }
214
+
215
+ ctx.ui?.notify?.(`当前模型已切换到 ${chosenKey}`, "info");
216
+ return true;
217
+ }
218
+
11
219
 
12
220
  function validName(name) {
13
221
  if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) throw new Error("名称须以字母或数字开头,仅含字母、数字、_、-");
@@ -90,7 +298,7 @@ async function recheckDraftModels(ctx, draft) {
90
298
  for (const result of batch.results) if (result.ok) draft.checks.set(result.id, { ok: true, latencyMs: result.latencyMs });
91
299
  draft.checkIdentity = identity;
92
300
  }
93
- async function saveSummary(ctx, draft, agentDir, isNew) {
301
+ export async function saveSummary(pi, ctx, draft, agentDir, isNew) {
94
302
  if (!draft.requireVerifiedModels && draft.config.api === "anthropic-messages") draft.config.baseUrl = draft.config.baseUrl.replace(/\/v1$/i, "");
95
303
  for (;;) {
96
304
  if (draft.requireVerifiedModels && draft.checkIdentity !== checkIdentity(draft.config)) draft.checks = new Map();
@@ -109,13 +317,53 @@ async function saveSummary(ctx, draft, agentDir, isNew) {
109
317
  try {
110
318
  if (isNew && getProvider(draft.name, { agentDir })) throw new Error("名称已存在,请进入已有项编辑");
111
319
  if (!draft.config.models.length) throw new Error("请先配置实际模型 ID");
320
+
321
+ const cur = currentModel(ctx);
322
+ const curBelongsToThis = Boolean(cur && cur.provider === draft.name);
323
+ const newModelIds = draft.config.models.map(model => model.id);
324
+ const retainsCurrentId = curBelongsToThis && newModelIds.includes(cur.id);
325
+
326
+ if (curBelongsToThis) {
327
+ const ok = await ensureCurrentModel(pi, ctx, { provider: draft.name, modelId: newModelIds, action: "保存" });
328
+ if (!ok) return false;
329
+ }
330
+
112
331
  saveProvider({ name: draft.name, providerConfig: draft.config, isPrivate: draft.isPrivate, agentDir });
113
- ctx.ui.notify("已保存,重启 OMP 后加载配置", "info");
332
+ const savedProvider = getProvider(draft.name, { agentDir }) || {
333
+ name: draft.name,
334
+ isPrivate: draft.isPrivate,
335
+ ...draft.config,
336
+ };
337
+
338
+ let syncFailed = false;
339
+ try {
340
+ await registerRuntimeProvider(pi, ctx, savedProvider);
341
+ } catch (syncErr) {
342
+ syncFailed = true;
343
+ ctx.ui.notify(`配置已保存,但模型目录同步失败: ${syncErr.message}`, "error");
344
+ }
345
+
346
+ if (!syncFailed) {
347
+ if (retainsCurrentId) {
348
+ const available = availableModels(ctx);
349
+ const resolved = available.find(m => m.provider === draft.name && m.id === cur.id);
350
+ if (resolved && typeof pi?.setModel === "function") {
351
+ try {
352
+ await pi.setModel(resolved);
353
+ } catch {
354
+ ctx.ui.notify("配置已保存,但当前模型未能重新绑定", "warning");
355
+ }
356
+ } else {
357
+ ctx.ui.notify("配置已保存,但当前模型未能重新绑定", "warning");
358
+ }
359
+ }
360
+ ctx.ui.notify("已保存,模型目录已同步", "info");
361
+ }
114
362
  return true;
115
363
  } catch (error) { ctx.ui.notify(`保存失败,未完成保存: ${error.message}`, "error"); }
116
364
  }
117
365
  }
118
- async function addDraft(ctx, agentDir, seed = {}) {
366
+ async function addDraft(pi, ctx, agentDir, seed = {}) {
119
367
  const name = await inputField(ctx, "Provider 名称", seed.name || "例如 my-provider", value => {
120
368
  validName(value);
121
369
  if (getProvider(value, { agentDir })) throw new Error("名称已存在,请进入已有项编辑");
@@ -132,9 +380,9 @@ async function addDraft(ctx, agentDir, seed = {}) {
132
380
  if (isPrivate === undefined) return;
133
381
  const draft = { name, isPrivate, config: { baseUrl, api, apiKey, models: [] }, verified: false };
134
382
  if (!await acquireDraftModels(ctx, draft, agentDir, seed.model ? [seed.model] : [])) return;
135
- await saveSummary(ctx, draft, agentDir, true);
383
+ await saveSummary(pi, ctx, draft, agentDir, true);
136
384
  }
137
- async function editDraft(ctx, name, agentDir, supplied) {
385
+ async function editDraft(pi, ctx, name, agentDir, supplied) {
138
386
  const provider = getProvider(name, { agentDir });
139
387
  if (!provider) return ctx.ui.notify(`Provider '${name}' not found`, "warning");
140
388
  const draft = supplied || fromProvider(provider);
@@ -186,31 +434,43 @@ async function editDraft(ctx, name, agentDir, supplied) {
186
434
  ctx.ui.notify("已保留全部已配置模型,未重新测试", "info");
187
435
  } else if (operation === "重新选择并测试模型") await acquireDraftModels(ctx, draft, agentDir);
188
436
  }
189
- else if (field === "保存" && await saveSummary(ctx, draft, agentDir, false)) return;
437
+ else if (field === "保存" && await saveSummary(pi, ctx, draft, agentDir, false)) return;
190
438
  }
191
439
  }
192
- async function deleteProvider(ctx, name, agentDir) {
440
+ export async function deleteProvider(pi, ctx, name, agentDir) {
193
441
  const provider = getProvider(name, { agentDir });
194
442
  if (!provider) return ctx.ui.notify(`Provider '${name}' not found`, "warning");
443
+ const wasPrivate = Boolean(provider.isPrivate || provider.private);
195
444
  const roles = rolesFor(name, agentDir);
196
445
  if (roles.length) {
197
446
  ctx.ui.notify(`${name} 绑定角色: ${roles.join(", ")};请先通过 /role 改绑`, "warning"); return;
198
447
  }
199
- if (await ctx.ui.confirm(`删除 ${name}`, `名称: ${name}\n绑定角色: 无\n确认从两处配置删除?`)) {
200
- removeProvider({ name, agentDir });
201
- ctx.ui.notify(`已删除 ${name},重启 OMP 后加载配置`, "info");
448
+ if (!await ctx.ui.confirm(`删除 ${name}`, `名称: ${name}\n绑定角色: 无\n确认从两处配置删除?`)) {
449
+ return;
450
+ }
451
+ const modelOk = await ensureCurrentModel(pi, ctx, { provider: name, action: "删除" });
452
+ if (!modelOk) return;
453
+
454
+ const removed = removeProvider({ name, agentDir });
455
+ if (!removed) return;
456
+
457
+ try {
458
+ await syncRemovedProvider(pi, ctx, name, wasPrivate);
459
+ ctx.ui.notify(`已删除 ${name},模型目录已同步`, "info");
460
+ } catch (err) {
461
+ ctx.ui.notify(`配置已删除,但模型目录同步失败: ${err.message}`, "error");
202
462
  }
203
463
  }
204
464
 
205
465
  export async function runProviderMenu(pi, ctx, { agentDir, action, name, draft } = {}) {
206
466
  if (!ctx.hasUI) return;
207
- if (action === "add" || action === "wizard") return addDraft(ctx, agentDir, draft);
208
- if (action === "edit") return editDraft(ctx, name, agentDir, draft);
467
+ if (action === "add" || action === "wizard") return addDraft(pi, ctx, agentDir, draft);
468
+ if (action === "edit") return editDraft(pi, ctx, name, agentDir, draft);
209
469
  if (action === "test") {
210
470
  const provider = getProvider(name, { agentDir });
211
471
  return provider ? verifyDraft(ctx, fromProvider(provider)) : ctx.ui.notify(`Provider '${name}' not found`, "warning");
212
472
  }
213
- if (action === "rm" || action === "remove") return deleteProvider(ctx, name, agentDir);
473
+ if (action === "rm" || action === "remove") return deleteProvider(pi, ctx, name, agentDir);
214
474
  for (;;) {
215
475
  const providers = listProviders({ agentDir });
216
476
  const choice = await select(ctx, "PROVIDER // CONTROL", [
@@ -218,7 +478,7 @@ export async function runProviderMenu(pi, ctx, { agentDir, action, name, draft }
218
478
  { label: "≡ 管理已有 Provider", description: `${providers.length} 个 Provider` }, "× 退出",
219
479
  ]);
220
480
  if (!choice || choice === "× 退出") return;
221
- if (choice === "+ 添加 Provider") { await addDraft(ctx, agentDir); continue; }
481
+ if (choice === "+ 添加 Provider") { await addDraft(pi, ctx, agentDir); continue; }
222
482
  for (;;) {
223
483
  const current = listProviders({ agentDir });
224
484
  if (!current.length) { ctx.ui.notify("尚未配置 Provider", "info"); break; }
@@ -231,9 +491,9 @@ export async function runProviderMenu(pi, ctx, { agentDir, action, name, draft }
231
491
  const operation = await select(ctx, `PROVIDER // ${chosen}`, ["查看详情", "编辑配置", "验证连接", "删除", "返回"]);
232
492
  if (!operation || operation === "返回") break;
233
493
  if (operation === "查看详情") ctx.ui.notify(summary(fromProvider(provider), agentDir), "info");
234
- if (operation === "编辑配置") await editDraft(ctx, chosen, agentDir);
494
+ if (operation === "编辑配置") await editDraft(pi, ctx, chosen, agentDir);
235
495
  if (operation === "验证连接") await verifyDraft(ctx, fromProvider(provider));
236
- if (operation === "删除") { await deleteProvider(ctx, chosen, agentDir); if (!getProvider(chosen, { agentDir })) break; }
496
+ if (operation === "删除") { await deleteProvider(pi, ctx, chosen, agentDir); if (!getProvider(chosen, { agentDir })) break; }
237
497
  }
238
498
  }
239
499
  }
@@ -285,12 +545,28 @@ export async function handleProviderCommand(pi, ctx, args, agentDir) {
285
545
  if (!name || tokens.length !== 2) throw new Error(`Usage: /provider ${sub} <name>`);
286
546
  if (ctx.hasUI) return await runProviderMenu(pi, ctx, { agentDir, action: sub, name });
287
547
  if (sub === "edit" || sub === "test") throw new Error(`Usage: /provider ${sub} <name> (requires interactive UI)`);
548
+ const provider = getProvider(name, { agentDir });
549
+ if (!provider) {
550
+ ctx.ui.notify(`Provider '${name}' not found`, "info");
551
+ return;
552
+ }
553
+ const wasPrivate = Boolean(provider.isPrivate || provider.private);
288
554
  const roles = rolesFor(name, agentDir);
289
555
  if (roles.length) {
290
556
  ctx.ui.notify(`Provider '${name}' 绑定角色: ${roles.join(", ")};请先通过 /role 改绑`, "warning");
291
557
  return;
292
558
  }
293
- ctx.ui.notify(removeProvider({ name, agentDir }) ? `Removed provider '${name}'` : `Provider '${name}' not found`, "info"); return;
559
+ const modelOk = await ensureCurrentModel(pi, ctx, { provider: name, action: "删除" });
560
+ if (!modelOk) return;
561
+
562
+ removeProvider({ name, agentDir });
563
+ try {
564
+ await syncRemovedProvider(pi, ctx, name, wasPrivate);
565
+ ctx.ui.notify(`Removed provider '${name}' and synchronized the model catalog`, "info");
566
+ } catch (err) {
567
+ ctx.ui.notify(`配置已删除,但模型目录同步失败: ${err.message}`, "error");
568
+ }
569
+ return;
294
570
  }
295
571
  if (sub === "add" || sub === "wizard") {
296
572
  const options = parseAdd(tokens.slice(1));
@@ -304,16 +580,32 @@ export async function handleProviderCommand(pi, ctx, args, agentDir) {
304
580
  const draft = { name: options.name, isPrivate: options.isPrivate, verified: false,
305
581
  config: { api: options.api, baseUrl: options.baseUrl, apiKey: options.apiKey, models: [] } };
306
582
  if (!await acquireDraftModels(ctx, draft, agentDir, options.model ? [options.model] : [])) return;
307
- await saveSummary(ctx, draft, agentDir, true);
583
+ await saveSummary(pi, ctx, draft, agentDir, true);
308
584
  return;
309
585
  }
310
586
  const result = await probeProvider({ ...options, testModelId: options.model, providerName: options.name });
311
587
  if (!result.ok && !options.model) throw new Error(result.error);
312
588
  const models = result.ok ? result.models : [inferModelCapabilities(options.model, options.name)];
313
589
  if (options.model && !models.some(model => model.id === options.model)) models.push(inferModelCapabilities(options.model, options.name));
314
- saveProvider({ name: options.name, providerConfig: { baseUrl: result.ok ? result.normalizedBaseUrl : options.baseUrl,
315
- api: options.api, apiKey: options.apiKey, models }, isPrivate: options.isPrivate, agentDir });
316
- ctx.ui.notify("已保存(未验证),重启 OMP 后加载配置", "info"); return;
590
+ const providerConfig = {
591
+ baseUrl: result.ok ? result.normalizedBaseUrl : options.baseUrl,
592
+ api: options.api,
593
+ apiKey: options.apiKey,
594
+ models,
595
+ };
596
+ saveProvider({ name: options.name, providerConfig, isPrivate: options.isPrivate, agentDir });
597
+ const savedProvider = getProvider(options.name, { agentDir }) || {
598
+ name: options.name,
599
+ isPrivate: options.isPrivate,
600
+ ...providerConfig,
601
+ };
602
+ try {
603
+ await registerRuntimeProvider(pi, ctx, savedProvider);
604
+ ctx.ui.notify("已保存(未验证),模型目录已同步", "info");
605
+ } catch (syncErr) {
606
+ ctx.ui.notify(`配置已保存,但模型目录同步失败: ${syncErr.message}`, "error");
607
+ }
608
+ return;
317
609
  }
318
610
  throw new Error("Usage: /provider [ls|add|edit <name>|test <name>|rm <name>]");
319
611
  } catch (error) { ctx.ui.notify(`Provider command error: ${error.message}`, "error"); }
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);