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.
- package/README.md +66 -1
- package/bin/omp-sync.js +145 -43
- package/index.js +742 -507
- package/package.json +4 -1
- package/src/maintenance.js +31 -3
- package/src/prober.js +199 -166
- package/src/provider-menu.js +308 -0
- package/src/provider-models.js +223 -0
- package/src/provider-store.js +273 -43
- package/src/rehydrator.js +1 -1
- package/src/sync-files.js +621 -0
- package/src/sync-plan.js +1062 -0
- package/src/sync-policy.js +322 -0
- package/src/sync-resources.js +744 -0
- package/src/sync-transaction.js +516 -0
package/index.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Exports an encrypted AES-256-GCM blob (scrypt-derived key); import restores files,
|
|
4
4
|
* remaps host paths adaptively, and maintains atomic backups for instant rollback.
|
|
5
5
|
*/
|
|
6
|
-
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
|
|
6
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync } from "node:crypto";
|
|
7
7
|
import { gzipSync, gunzipSync } from "node:zlib";
|
|
8
8
|
import fs from "node:fs";
|
|
9
9
|
import os from "node:os";
|
|
@@ -40,6 +40,7 @@ import {
|
|
|
40
40
|
formatYamlModels,
|
|
41
41
|
} from "./src/provider-store.js";
|
|
42
42
|
import { getRoles, setRole, VALID_ROLES } from "./src/role-manager.js";
|
|
43
|
+
import { handleProviderCommand, providerCompletions } from "./src/provider-menu.js";
|
|
43
44
|
import {
|
|
44
45
|
runMaintenance,
|
|
45
46
|
cleanCorruptFiles,
|
|
@@ -79,242 +80,202 @@ export {
|
|
|
79
80
|
removeCron,
|
|
80
81
|
};
|
|
81
82
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
return process.env.OMP_CFG_ROOT || path.join(os.homedir(), ".omp", "agent");
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** Root .omp folder (parent of agent directory). */
|
|
125
|
-
export function ompHome(root = configRoot()) {
|
|
126
|
-
return process.env.OMP_HOME || path.dirname(root);
|
|
127
|
-
}
|
|
83
|
+
// New public/private sync infrastructure
|
|
84
|
+
import { configRoot, ompHome, resolveDestination } from "./src/sync-files.js";
|
|
85
|
+
export { configRoot, ompHome, resolveDestination };
|
|
86
|
+
import {
|
|
87
|
+
POLICY_FILE,
|
|
88
|
+
readSyncPolicy,
|
|
89
|
+
setResourceScope,
|
|
90
|
+
resolveResourceScope,
|
|
91
|
+
resolveSyncNamespace,
|
|
92
|
+
validateResourceId,
|
|
93
|
+
checkSettingOverlap,
|
|
94
|
+
} from "./src/sync-policy.js";
|
|
95
|
+
import {
|
|
96
|
+
inventoryResources,
|
|
97
|
+
readResource,
|
|
98
|
+
sanitizeResourceForExport,
|
|
99
|
+
restoreResourceForImport,
|
|
100
|
+
HOME_PLACEHOLDER,
|
|
101
|
+
} from "./src/sync-resources.js";
|
|
102
|
+
import {
|
|
103
|
+
STATE_FILE,
|
|
104
|
+
SENTINEL_DELETED,
|
|
105
|
+
canonicalHash,
|
|
106
|
+
readSyncState,
|
|
107
|
+
writeSyncState,
|
|
108
|
+
validateSnapshot,
|
|
109
|
+
inspectArchivePayload,
|
|
110
|
+
adaptLegacySnapshot,
|
|
111
|
+
planSync,
|
|
112
|
+
} from "./src/sync-plan.js";
|
|
113
|
+
import {
|
|
114
|
+
applySyncPlan,
|
|
115
|
+
rollbackSync,
|
|
116
|
+
commitFileTransaction,
|
|
117
|
+
} from "./src/sync-transaction.js";
|
|
118
|
+
import {
|
|
119
|
+
createReadContext,
|
|
120
|
+
withSyncLock,
|
|
121
|
+
} from "./src/sync-files.js";
|
|
128
122
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
123
|
+
export {
|
|
124
|
+
POLICY_FILE,
|
|
125
|
+
readSyncPolicy,
|
|
126
|
+
setResourceScope,
|
|
127
|
+
resolveResourceScope,
|
|
128
|
+
validateResourceId,
|
|
129
|
+
checkSettingOverlap,
|
|
130
|
+
inventoryResources,
|
|
131
|
+
readResource,
|
|
132
|
+
sanitizeResourceForExport,
|
|
133
|
+
restoreResourceForImport,
|
|
134
|
+
STATE_FILE,
|
|
135
|
+
SENTINEL_DELETED,
|
|
136
|
+
canonicalHash,
|
|
137
|
+
readSyncState,
|
|
138
|
+
writeSyncState,
|
|
139
|
+
validateSnapshot,
|
|
140
|
+
inspectArchivePayload,
|
|
141
|
+
adaptLegacySnapshot,
|
|
142
|
+
planSync,
|
|
143
|
+
applySyncPlan,
|
|
144
|
+
rollbackSync,
|
|
145
|
+
commitFileTransaction,
|
|
146
|
+
};
|
|
133
147
|
|
|
134
|
-
|
|
135
|
-
const len = Math.min(buf.length, 1024);
|
|
136
|
-
for (let i = 0; i < len; i++) {
|
|
137
|
-
if (buf[i] === 0) return false;
|
|
138
|
-
}
|
|
139
|
-
return true;
|
|
140
|
-
}
|
|
148
|
+
const MAGIC = Buffer.from("OMPCFG1\0", "latin1");
|
|
141
149
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
out.push(...walk(abs, rel));
|
|
151
|
-
}
|
|
152
|
-
} else if (ent.isFile()) {
|
|
153
|
-
if (!shouldIgnore(rel)) {
|
|
154
|
-
out.push(rel);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
return out;
|
|
159
|
-
}
|
|
150
|
+
/**
|
|
151
|
+
* Collect is now defined strictly as the read-only file projection of public resources.
|
|
152
|
+
* Zero side-effects; never writes disk or .plugin-links.json.
|
|
153
|
+
*/
|
|
154
|
+
export function collect(root = configRoot()) {
|
|
155
|
+
const policy = readSyncPolicy(root);
|
|
156
|
+
const state = readSyncState(root);
|
|
157
|
+
const inventory = inventoryResources(root);
|
|
160
158
|
|
|
161
|
-
export function collect(root) {
|
|
162
159
|
const out = [];
|
|
163
160
|
const seen = new Set();
|
|
164
161
|
|
|
165
162
|
function addItem(rel, abs) {
|
|
166
163
|
const norm = rel.replace(/\\/g, "/");
|
|
167
|
-
if (!seen.has(norm) &&
|
|
164
|
+
if (!seen.has(norm) && fs.existsSync(abs)) {
|
|
168
165
|
seen.add(norm);
|
|
169
166
|
out.push({ rel: norm, abs });
|
|
170
167
|
}
|
|
171
168
|
}
|
|
172
169
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
if (
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
const isExtra = name.endsWith(".yml") || name.endsWith(".yaml") || name.endsWith(".json");
|
|
181
|
-
if (isCore || isToken || isExtra) {
|
|
182
|
-
addItem(name, path.join(root, name));
|
|
170
|
+
for (const item of inventory) {
|
|
171
|
+
const scopeInfo = resolveResourceScope(item.id, policy, state, item);
|
|
172
|
+
if (scopeInfo.scope === "public") {
|
|
173
|
+
if (item.category === "provider") {
|
|
174
|
+
let y = path.join(root, "models.yml");
|
|
175
|
+
if (!fs.existsSync(y) && fs.existsSync(path.join(root, "models.yaml"))) {
|
|
176
|
+
y = path.join(root, "models.yaml");
|
|
183
177
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
178
|
+
addItem(path.basename(y), y);
|
|
179
|
+
} else if (item.category === "mcp") {
|
|
180
|
+
addItem("mcp.json", path.join(root, "mcp.json"));
|
|
181
|
+
} else if (item.category === "setting") {
|
|
182
|
+
let c = path.join(root, "config.yml");
|
|
183
|
+
if (!fs.existsSync(c) && fs.existsSync(path.join(root, "config.yaml"))) {
|
|
184
|
+
c = path.join(root, "config.yaml");
|
|
185
|
+
}
|
|
186
|
+
addItem(path.basename(c), c);
|
|
187
|
+
} else if (item.category === "plugin") {
|
|
188
|
+
const pdir = path.join(ompHome(root), "plugins");
|
|
189
|
+
addItem("plugins/package.json", path.join(pdir, "package.json"));
|
|
190
|
+
const lockPath = path.join(pdir, "omp-plugins.lock.json");
|
|
191
|
+
if (fs.existsSync(lockPath)) {
|
|
192
|
+
addItem("plugins/omp-plugins.lock.json", lockPath);
|
|
193
|
+
}
|
|
194
|
+
} else if (item.category === "asset") {
|
|
195
|
+
const readRes = readResource(root, item.id);
|
|
196
|
+
if (readRes && Array.isArray(readRes.value)) {
|
|
197
|
+
for (const f of readRes.value) {
|
|
198
|
+
addItem(f.path, resolveDestination(f.path, root));
|
|
199
|
+
}
|
|
193
200
|
}
|
|
194
201
|
}
|
|
195
202
|
}
|
|
196
203
|
}
|
|
197
204
|
|
|
198
|
-
// 3. User extensions under ~/.omp/extensions/ (sibling to agent/)
|
|
199
|
-
const ompDir = ompHome(root);
|
|
200
|
-
const extDir = path.join(ompDir, "extensions");
|
|
201
|
-
if (fs.existsSync(extDir) && fs.statSync(extDir).isDirectory()) {
|
|
202
|
-
for (const file of walk(extDir)) {
|
|
203
|
-
addItem(`extensions/${file}`, path.join(extDir, file));
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// 4. Installed plugins lockfile & manifest under ~/.omp/plugins/
|
|
208
|
-
const pluginsDir = path.join(ompDir, "plugins");
|
|
209
|
-
const links = getPluginLinks(pluginsDir);
|
|
210
|
-
if (Object.keys(links).length > 0) {
|
|
211
|
-
savePluginLinks(pluginsDir, links);
|
|
212
|
-
}
|
|
213
|
-
const linksFile = path.join(pluginsDir, ".plugin-links.json");
|
|
214
|
-
if (fs.existsSync(linksFile) && fs.statSync(linksFile).isFile()) {
|
|
215
|
-
addItem("plugins/.plugin-links.json", linksFile);
|
|
216
|
-
}
|
|
217
|
-
const lockFile = path.join(pluginsDir, "omp-plugins.lock.json");
|
|
218
|
-
if (fs.existsSync(lockFile) && fs.statSync(lockFile).isFile()) {
|
|
219
|
-
addItem("plugins/omp-plugins.lock.json", lockFile);
|
|
220
|
-
}
|
|
221
|
-
const pluginPkg = path.join(pluginsDir, "package.json");
|
|
222
|
-
if (fs.existsSync(pluginPkg) && fs.statSync(pluginPkg).isFile()) {
|
|
223
|
-
addItem("plugins/package.json", pluginPkg);
|
|
224
|
-
}
|
|
225
|
-
// 5. Global tools under ~/.omp/tools/
|
|
226
|
-
const toolsDir = path.join(ompDir, "tools");
|
|
227
|
-
if (fs.existsSync(toolsDir) && fs.statSync(toolsDir).isDirectory()) {
|
|
228
|
-
for (const file of walk(toolsDir)) {
|
|
229
|
-
addItem(`tools/${file}`, path.join(toolsDir, file));
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// 6. Global hooks under ~/.omp/hooks/
|
|
234
|
-
const hooksDir = path.join(ompDir, "hooks");
|
|
235
|
-
if (fs.existsSync(hooksDir) && fs.statSync(hooksDir).isDirectory()) {
|
|
236
|
-
for (const file of walk(hooksDir)) {
|
|
237
|
-
addItem(`hooks/${file}`, path.join(hooksDir, file));
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
|
|
241
205
|
return out;
|
|
242
206
|
}
|
|
243
207
|
|
|
244
|
-
/**
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
if (
|
|
248
|
-
norm.startsWith("extensions/") ||
|
|
249
|
-
norm.startsWith("plugins/") ||
|
|
250
|
-
norm.startsWith("tools/") ||
|
|
251
|
-
norm.startsWith("hooks/")
|
|
252
|
-
) {
|
|
253
|
-
return path.join(ompHome(root), norm);
|
|
254
|
-
}
|
|
255
|
-
return path.join(root, norm);
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/** Build the encrypted archive in memory with path sanitization. */
|
|
208
|
+
/**
|
|
209
|
+
* Builds the encrypted archive v3 containing only classified public resources and tombstones.
|
|
210
|
+
*/
|
|
259
211
|
export function buildArchive(pass, root = configRoot()) {
|
|
260
212
|
if (!pass) throw new Error("empty passphrase");
|
|
261
|
-
const
|
|
262
|
-
const
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
|
|
213
|
+
const policy = readSyncPolicy(root);
|
|
214
|
+
const state = readSyncState(root);
|
|
215
|
+
const namespace = resolveSyncNamespace(policy, state);
|
|
216
|
+
if (!namespace) {
|
|
217
|
+
throw new Error("No sync namespace established; classify the first public resource before export/push");
|
|
218
|
+
}
|
|
219
|
+
const inventory = inventoryResources(root);
|
|
220
|
+
|
|
221
|
+
const publicResources = [];
|
|
222
|
+
const activePublicIds = new Set();
|
|
223
|
+
|
|
224
|
+
for (const item of inventory) {
|
|
225
|
+
const scopeInfo = resolveResourceScope(item.id, policy, state, item);
|
|
226
|
+
if (scopeInfo.scope === "public") {
|
|
227
|
+
activePublicIds.add(item.id);
|
|
228
|
+
const readRes = readResource(root, item.id);
|
|
229
|
+
if (!readRes || !Object.hasOwn(readRes, "value")) {
|
|
230
|
+
throw new Error(`Public resource '${item.id}' is missing during export; fix the resource or mark it private`);
|
|
231
|
+
}
|
|
232
|
+
publicResources.push({
|
|
233
|
+
id: item.id,
|
|
234
|
+
value: sanitizeResourceForExport(item.id, readRes.value, root),
|
|
235
|
+
});
|
|
281
236
|
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Tombstones calculation:
|
|
240
|
+
// Baseline-managed items that are now deleted or marked private
|
|
241
|
+
const tombstonesSet = new Set(state.tombstones || []);
|
|
242
|
+
if (state.resources) {
|
|
243
|
+
for (const [id, rec] of Object.entries(state.resources)) {
|
|
244
|
+
if (rec.hash && rec.hash !== SENTINEL_DELETED) {
|
|
245
|
+
if (!activePublicIds.has(id)) {
|
|
246
|
+
tombstonesSet.add(id);
|
|
289
247
|
}
|
|
290
248
|
}
|
|
291
|
-
data = Buffer.from(str, "utf8").toString("base64");
|
|
292
|
-
} else {
|
|
293
|
-
data = raw.toString("base64");
|
|
294
249
|
}
|
|
295
|
-
|
|
296
|
-
|
|
250
|
+
}
|
|
251
|
+
// Clear any ID that is currently active public
|
|
252
|
+
for (const id of activePublicIds) {
|
|
253
|
+
tombstonesSet.delete(id);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (publicResources.length === 0 && tombstonesSet.size === 0) {
|
|
257
|
+
throw new Error(
|
|
258
|
+
"No public resources classified for sync. Use 'scope set <id> public' or '/config-scope set <id> public' before export/push."
|
|
259
|
+
);
|
|
260
|
+
}
|
|
297
261
|
|
|
298
262
|
const payload = {
|
|
299
|
-
v:
|
|
263
|
+
v: 3,
|
|
264
|
+
namespace,
|
|
300
265
|
createdAt: new Date().toISOString(),
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
files,
|
|
266
|
+
resources: publicResources,
|
|
267
|
+
tombstones: Array.from(tombstonesSet).sort(),
|
|
304
268
|
};
|
|
269
|
+
validateSnapshot(payload);
|
|
305
270
|
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
const iv = randomBytes(12);
|
|
309
|
-
const key = scryptSync(pass, salt, 32);
|
|
310
|
-
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
311
|
-
const ct = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
312
|
-
const blob = Buffer.concat([MAGIC, salt, iv, cipher.getAuthTag(), ct]);
|
|
313
|
-
return { blob, files: files.length };
|
|
271
|
+
const blob = encryptArchivePayload(payload, pass);
|
|
272
|
+
return { blob, files: publicResources.length, payload };
|
|
314
273
|
}
|
|
315
274
|
|
|
316
|
-
/**
|
|
317
|
-
|
|
275
|
+
/**
|
|
276
|
+
* Decrypts an encrypted archive blob and returns the parsed JSON payload.
|
|
277
|
+
*/
|
|
278
|
+
export function decryptArchiveBlob(blob, pass) {
|
|
318
279
|
if (!pass) throw new Error("empty passphrase");
|
|
319
280
|
if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) {
|
|
320
281
|
throw new Error("not an omp-config-crypt archive");
|
|
@@ -329,150 +290,108 @@ export function restoreArchive(blob, pass, root = configRoot(), options = {}) {
|
|
|
329
290
|
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
330
291
|
decipher.setAuthTag(tag);
|
|
331
292
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
293
|
+
let decrypted;
|
|
294
|
+
try {
|
|
295
|
+
decrypted = gunzipSync(Buffer.concat([decipher.update(ct), decipher.final()]));
|
|
296
|
+
} catch (err) {
|
|
297
|
+
throw new Error(`Archive decryption failed: ${err.message}`);
|
|
335
298
|
}
|
|
336
299
|
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
const targetHomePosix = targetHome.replace(/\\/g, "/");
|
|
340
|
-
const sourceHome = payload.sourceHome;
|
|
341
|
-
const backupDir = path.join(root, `.import-backup-${Date.now()}`);
|
|
342
|
-
const actions = [];
|
|
343
|
-
let restored = 0;
|
|
344
|
-
|
|
345
|
-
for (const f of payload.files) {
|
|
346
|
-
const rel = String(f.path || "").replace(/\\/g, "/");
|
|
347
|
-
if (!rel || rel.includes("..") || path.isAbsolute(rel)) {
|
|
348
|
-
throw new Error(`unsafe path in archive: ${rel}`);
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
const dst = resolveDestination(rel, root);
|
|
352
|
-
let buf = Buffer.from(f.data, "base64");
|
|
353
|
-
let remapped = false;
|
|
354
|
-
|
|
355
|
-
if (payload.v >= 2 && isText(buf)) {
|
|
356
|
-
let str = buf.toString("utf8");
|
|
357
|
-
const orig = str;
|
|
358
|
-
|
|
359
|
-
const isJsonOrYaml = rel.endsWith(".json") || rel.endsWith(".yml") || rel.endsWith(".yaml");
|
|
360
|
-
const effectiveHome = process.platform === "win32" && isJsonOrYaml ? targetHomePosix : targetHome;
|
|
361
|
-
|
|
362
|
-
str = str.split(HOME_PLACEHOLDER).join(effectiveHome);
|
|
363
|
-
if (sourceHome) {
|
|
364
|
-
str = str.split(sourceHome).join(effectiveHome);
|
|
365
|
-
const sourceHomePosix = sourceHome.replace(/\\/g, "/");
|
|
366
|
-
if (sourceHomePosix !== sourceHome) {
|
|
367
|
-
str = str.split(sourceHomePosix).join(effectiveHome);
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
if (str !== orig) {
|
|
372
|
-
remapped = true;
|
|
373
|
-
buf = Buffer.from(str, "utf8");
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
const exists = fs.existsSync(dst);
|
|
377
|
-
|
|
378
|
-
// Intelligently merge existing local private providers in models.yml so they are never overwritten
|
|
379
|
-
if ((rel === "models.yml" || rel === "models.yaml") && exists) {
|
|
380
|
-
try {
|
|
381
|
-
const existingRaw = fs.readFileSync(dst, "utf8");
|
|
382
|
-
const existingProviders = parseYamlModels(existingRaw);
|
|
383
|
-
const privateProviders = {};
|
|
384
|
-
for (const [name, cfg] of Object.entries(existingProviders)) {
|
|
385
|
-
if (cfg.private) {
|
|
386
|
-
privateProviders[name] = cfg;
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
if (Object.keys(privateProviders).length > 0) {
|
|
390
|
-
const incomingProviders = parseYamlModels(buf.toString("utf8"));
|
|
391
|
-
const merged = { ...incomingProviders, ...privateProviders };
|
|
392
|
-
buf = Buffer.from(formatYamlModels(merged), "utf8");
|
|
393
|
-
}
|
|
394
|
-
} catch {}
|
|
395
|
-
}
|
|
396
|
-
actions.push({ path: rel, dest: dst, exists, remapped });
|
|
300
|
+
return JSON.parse(decrypted.toString("utf8"));
|
|
301
|
+
}
|
|
397
302
|
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
303
|
+
/**
|
|
304
|
+
* Encrypts a JSON-serializable snapshot payload into an archive buffer.
|
|
305
|
+
*/
|
|
306
|
+
export function encryptArchivePayload(payload, pass) {
|
|
307
|
+
if (!pass) throw new Error("empty passphrase");
|
|
308
|
+
const plain = gzipSync(Buffer.from(JSON.stringify(payload)), { level: 9 });
|
|
309
|
+
const salt = randomBytes(16);
|
|
310
|
+
const iv = randomBytes(12);
|
|
311
|
+
const key = scryptSync(pass, salt, 32);
|
|
312
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
313
|
+
const ct = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
314
|
+
return Buffer.concat([MAGIC, salt, iv, cipher.getAuthTag(), ct]);
|
|
315
|
+
}
|
|
409
316
|
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
317
|
+
/**
|
|
318
|
+
* Adapts a legacy v1 or v2 archive to v3 specification with same passphrase.
|
|
319
|
+
*/
|
|
320
|
+
export function adaptArchive(blob, pass) {
|
|
321
|
+
const payload = decryptArchiveBlob(blob, pass);
|
|
322
|
+
const inspection = inspectArchivePayload(payload);
|
|
323
|
+
if (inspection.compatible) {
|
|
324
|
+
throw new Error("archive already v3; no adaptation needed");
|
|
416
325
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
if (!dryRun) {
|
|
420
|
-
const obsoleteCandidates = [
|
|
421
|
-
path.join(ompHome(root), "extensions", "agy.js"),
|
|
422
|
-
path.join(ompHome(root), "extensions", "local-models.js"),
|
|
423
|
-
path.join(root, "models.local.json"),
|
|
424
|
-
];
|
|
425
|
-
for (const p of obsoleteCandidates) {
|
|
426
|
-
if (fs.existsSync(p)) {
|
|
427
|
-
try {
|
|
428
|
-
fs.rmSync(p, { force: true });
|
|
429
|
-
purged.push(p);
|
|
430
|
-
} catch {}
|
|
431
|
-
}
|
|
432
|
-
}
|
|
326
|
+
if (!inspection.adaptable) {
|
|
327
|
+
throw new Error(inspection.reason);
|
|
433
328
|
}
|
|
434
|
-
|
|
329
|
+
const adapted = adaptLegacySnapshot(payload);
|
|
330
|
+
const outBlob = encryptArchivePayload(adapted, pass);
|
|
435
331
|
return {
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
purged,
|
|
440
|
-
backupDir: !dryRun && fs.existsSync(backupDir) ? backupDir : null,
|
|
441
|
-
rehydration,
|
|
332
|
+
blob: outBlob,
|
|
333
|
+
payload: adapted,
|
|
334
|
+
legacy: adapted.legacy,
|
|
442
335
|
};
|
|
443
336
|
}
|
|
444
337
|
|
|
445
|
-
/**
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
const
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
338
|
+
/**
|
|
339
|
+
* Restores an encrypted archive buffer into the config tree with 3-way merge planning and journaled transaction.
|
|
340
|
+
*/
|
|
341
|
+
export function restoreArchive(blob, pass, root = configRoot(), options = {}) {
|
|
342
|
+
const payload = decryptArchiveBlob(blob, pass);
|
|
343
|
+
const inspection = inspectArchivePayload(payload);
|
|
344
|
+
let effectivePayload = payload;
|
|
345
|
+
let legacyInfo = null;
|
|
346
|
+
|
|
347
|
+
if (inspection.compatible) {
|
|
348
|
+
// Already compatible v3
|
|
349
|
+
} else if (inspection.adaptable) {
|
|
350
|
+
effectivePayload = adaptLegacySnapshot(payload);
|
|
351
|
+
legacyInfo = {
|
|
352
|
+
from: effectivePayload.legacy.from,
|
|
353
|
+
unmapped: effectivePayload.legacy.unmapped,
|
|
354
|
+
adapted: true,
|
|
355
|
+
};
|
|
356
|
+
} else {
|
|
357
|
+
throw new Error(inspection.reason);
|
|
457
358
|
}
|
|
458
359
|
|
|
459
|
-
const
|
|
460
|
-
const
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
360
|
+
const dryRun = Boolean(options.dryRun);
|
|
361
|
+
const plan = planSync(effectivePayload, root);
|
|
362
|
+
|
|
363
|
+
if (dryRun) {
|
|
364
|
+
return {
|
|
365
|
+
files: plan.writes.length,
|
|
366
|
+
dryRun: true,
|
|
367
|
+
actions: plan.actions,
|
|
368
|
+
conflicts: plan.conflicts,
|
|
369
|
+
blocked: plan.blocked,
|
|
370
|
+
prerequisites: plan.prerequisites,
|
|
371
|
+
writes: plan.writes,
|
|
372
|
+
...(legacyInfo ? { legacy: legacyInfo } : {}),
|
|
373
|
+
};
|
|
470
374
|
}
|
|
471
375
|
|
|
472
|
-
|
|
473
|
-
|
|
376
|
+
// Apply plan atomically
|
|
377
|
+
const result = applySyncPlan(plan, root);
|
|
378
|
+
return {
|
|
379
|
+
files: result.filesWritten,
|
|
380
|
+
dryRun: false,
|
|
381
|
+
actions: plan.actions,
|
|
382
|
+
backupDir: result.backupDir,
|
|
383
|
+
conflicts: plan.conflicts,
|
|
384
|
+
blocked: plan.blocked,
|
|
385
|
+
prerequisites: plan.prerequisites,
|
|
386
|
+
...(legacyInfo ? { legacy: legacyInfo } : {}),
|
|
387
|
+
};
|
|
388
|
+
}
|
|
474
389
|
|
|
475
|
-
|
|
390
|
+
/**
|
|
391
|
+
* Reverts the most recent config restore using transaction journal.
|
|
392
|
+
*/
|
|
393
|
+
export function rollback(root = configRoot()) {
|
|
394
|
+
return rollbackSync(root);
|
|
476
395
|
}
|
|
477
396
|
|
|
478
397
|
/** Write an encrypted archive of the config tree. */
|
|
@@ -486,7 +405,32 @@ export function exportEncrypted(outFile, pass, root = configRoot()) {
|
|
|
486
405
|
|
|
487
406
|
/** Restore files from an encrypted archive, backing up overwritten ones. */
|
|
488
407
|
export function importEncrypted(srcFile, pass, root = configRoot(), options = {}) {
|
|
489
|
-
|
|
408
|
+
const abs = path.resolve(srcFile);
|
|
409
|
+
const blob = fs.readFileSync(abs);
|
|
410
|
+
const payload = decryptArchiveBlob(blob, pass);
|
|
411
|
+
const inspection = inspectArchivePayload(payload);
|
|
412
|
+
|
|
413
|
+
if (!inspection.compatible && inspection.adaptable) {
|
|
414
|
+
const adaptedOut = `${abs}.v3.enc`;
|
|
415
|
+
if (fs.existsSync(adaptedOut) && !options.force) {
|
|
416
|
+
throw new Error(`adapted archive already exists: ${adaptedOut}`);
|
|
417
|
+
}
|
|
418
|
+
const adapted = adaptLegacySnapshot(payload);
|
|
419
|
+
const adaptedBlob = encryptArchivePayload(adapted, pass);
|
|
420
|
+
fs.writeFileSync(adaptedOut, adaptedBlob, { mode: 0o600 });
|
|
421
|
+
const res = restoreArchive(adaptedBlob, pass, root, options);
|
|
422
|
+
return {
|
|
423
|
+
...res,
|
|
424
|
+
adaptedFile: adaptedOut,
|
|
425
|
+
legacy: {
|
|
426
|
+
from: inspection.version,
|
|
427
|
+
unmapped: adapted.legacy.unmapped,
|
|
428
|
+
adapted: true,
|
|
429
|
+
},
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
return restoreArchive(blob, pass, root, options);
|
|
490
434
|
}
|
|
491
435
|
|
|
492
436
|
async function askPass(ctx, title) {
|
|
@@ -540,8 +484,44 @@ async function askToken(ctx, title, required) {
|
|
|
540
484
|
|
|
541
485
|
const GIST_FILE = "omp-config.enc.b64";
|
|
542
486
|
|
|
487
|
+
const TRANSIENT_FETCH_CODE =
|
|
488
|
+
/ECONNRESET|ETIMEDOUT|ECONNREFUSED|EPIPE|UND_ERR|SOCKET_HANG_UP|OTHER_SIDE_CLOSED/i;
|
|
489
|
+
|
|
490
|
+
function isTransientFetchError(err) {
|
|
491
|
+
const code = err?.cause?.code || err?.code;
|
|
492
|
+
return typeof code === "string" && TRANSIENT_FETCH_CODE.test(code);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* fetch with bounded retry for transient network failures (flaky routes, mid-transfer RSTs).
|
|
497
|
+
* Retries transport errors carrying a transient code and 429/5xx responses with backoff;
|
|
498
|
+
* client errors (4xx) and caller timeouts fail immediately.
|
|
499
|
+
*/
|
|
500
|
+
async function fetchWithRetry(url, init = {}, attempts = 3) {
|
|
501
|
+
let lastError;
|
|
502
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
503
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
504
|
+
try {
|
|
505
|
+
const res = await fetch(url, init);
|
|
506
|
+
if ((res.status === 429 || res.status >= 500) && attempt < attempts) {
|
|
507
|
+
await sleep(750 * 2 ** (attempt - 1));
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
return res;
|
|
511
|
+
} catch (err) {
|
|
512
|
+
lastError = err;
|
|
513
|
+
if (!isTransientFetchError(err) || attempt === attempts) throw err;
|
|
514
|
+
await sleep(750 * 2 ** (attempt - 1));
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
const code = lastError?.cause?.code || lastError?.code || "network failure";
|
|
518
|
+
throw new Error(
|
|
519
|
+
`${code} after ${attempts} attempts: ${lastError.message} — retry later, or set HTTPS_PROXY + NODE_USE_ENV_PROXY=1 to route via a local proxy`
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
|
|
543
523
|
async function gh(token, pathname, init = {}) {
|
|
544
|
-
const res = await
|
|
524
|
+
const res = await fetchWithRetry(`https://api.github.com${pathname}`, {
|
|
545
525
|
...init,
|
|
546
526
|
signal: AbortSignal.timeout(30_000),
|
|
547
527
|
headers: {
|
|
@@ -556,9 +536,71 @@ async function gh(token, pathname, init = {}) {
|
|
|
556
536
|
}
|
|
557
537
|
|
|
558
538
|
/** Push the archive to a secret gist; returns its id and URL. */
|
|
539
|
+
function commitPushBaseline(root, payload) {
|
|
540
|
+
const readContext = createReadContext(root);
|
|
541
|
+
readContext.observe(path.join(root, STATE_FILE));
|
|
542
|
+
const current = readSyncState(root);
|
|
543
|
+
const resources = {};
|
|
544
|
+
for (const key of Object.keys(current.resources || {})) {
|
|
545
|
+
Object.defineProperty(resources, key, {
|
|
546
|
+
value: { ...current.resources[key] },
|
|
547
|
+
enumerable: true,
|
|
548
|
+
configurable: true,
|
|
549
|
+
writable: true,
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
for (const resource of payload.resources || []) {
|
|
553
|
+
Object.defineProperty(resources, resource.id, {
|
|
554
|
+
value: { hash: canonicalHash(resource.value), hashFormat: "portable-v1" },
|
|
555
|
+
enumerable: true,
|
|
556
|
+
configurable: true,
|
|
557
|
+
writable: true,
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
const tombstones = Array.from(new Set(payload.tombstones || [])).sort();
|
|
561
|
+
for (const id of tombstones) {
|
|
562
|
+
Object.defineProperty(resources, id, {
|
|
563
|
+
value: { hash: SENTINEL_DELETED, hashFormat: "portable-v1" },
|
|
564
|
+
enumerable: true,
|
|
565
|
+
configurable: true,
|
|
566
|
+
writable: true,
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
const nextState = {
|
|
570
|
+
version: 1,
|
|
571
|
+
namespace: payload.namespace || current.namespace,
|
|
572
|
+
resources,
|
|
573
|
+
tombstones,
|
|
574
|
+
};
|
|
575
|
+
return withSyncLock(root, (lock) =>
|
|
576
|
+
commitFileTransaction(
|
|
577
|
+
root,
|
|
578
|
+
{
|
|
579
|
+
readContext,
|
|
580
|
+
entries: new Map(),
|
|
581
|
+
nextState,
|
|
582
|
+
needsCommit: true,
|
|
583
|
+
stateGuard: (() => {
|
|
584
|
+
const stateAbs = path.join(root, STATE_FILE);
|
|
585
|
+
const bytes = readContext.readFile(stateAbs);
|
|
586
|
+
if (bytes === undefined) {
|
|
587
|
+
return { existed: false, hash: SENTINEL_DELETED, mode: null };
|
|
588
|
+
}
|
|
589
|
+
return {
|
|
590
|
+
existed: true,
|
|
591
|
+
hash: createHash("sha256").update(bytes).digest("hex"),
|
|
592
|
+
mode: readContext.fileMode(stateAbs),
|
|
593
|
+
};
|
|
594
|
+
})(),
|
|
595
|
+
},
|
|
596
|
+
lock
|
|
597
|
+
)
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
|
|
559
601
|
export async function pushGist(id, pass, root = configRoot(), token = envToken()) {
|
|
560
602
|
if (!token) throw new Error("GitHub token required: set OMP_CFG_CLOUD_TOKEN or GITHUB_TOKEN");
|
|
561
|
-
const { blob, files } = buildArchive(pass, root);
|
|
603
|
+
const { blob, files, payload } = buildArchive(pass, root);
|
|
562
604
|
const content = blob.toString("base64");
|
|
563
605
|
const body = { files: { [GIST_FILE]: { content } } };
|
|
564
606
|
const data =
|
|
@@ -568,41 +610,100 @@ export async function pushGist(id, pass, root = configRoot(), token = envToken()
|
|
|
568
610
|
method: "POST",
|
|
569
611
|
body: JSON.stringify({ description: "omp config (encrypted)", public: false, ...body }),
|
|
570
612
|
});
|
|
613
|
+
|
|
614
|
+
try {
|
|
615
|
+
commitPushBaseline(root, payload);
|
|
616
|
+
} catch (error) {
|
|
617
|
+
throw new Error(`Upload succeeded; local baseline commit failed: ${error.message}`);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
|
|
571
621
|
return { id: data.id, url: data.html_url, files, bytes: blob.length };
|
|
572
622
|
}
|
|
573
623
|
|
|
624
|
+
function restoreRemoteArchive(blob, pass, root = configRoot(), options = {}) {
|
|
625
|
+
const payload = decryptArchiveBlob(blob, pass);
|
|
626
|
+
const inspection = inspectArchivePayload(payload);
|
|
627
|
+
|
|
628
|
+
if (inspection.compatible) {
|
|
629
|
+
return restoreArchive(blob, pass, root, options);
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
if (!inspection.adaptable) {
|
|
633
|
+
throw new Error(inspection.reason);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const adapted = adaptLegacySnapshot(payload);
|
|
637
|
+
const adaptedBlob = encryptArchivePayload(adapted, pass);
|
|
638
|
+
|
|
639
|
+
if (options.dryRun) {
|
|
640
|
+
const res = restoreArchive(adaptedBlob, pass, root, options);
|
|
641
|
+
return {
|
|
642
|
+
...res,
|
|
643
|
+
legacy: {
|
|
644
|
+
from: inspection.version,
|
|
645
|
+
unmapped: adapted.legacy.unmapped,
|
|
646
|
+
adapted: true,
|
|
647
|
+
},
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
const adaptedFile = path.join(os.tmpdir(), `omp-archive-v3-${Date.now()}.enc`);
|
|
652
|
+
fs.writeFileSync(adaptedFile, adaptedBlob, { mode: 0o600 });
|
|
653
|
+
const res = restoreArchive(adaptedBlob, pass, root, options);
|
|
654
|
+
return {
|
|
655
|
+
...res,
|
|
656
|
+
adaptedFile,
|
|
657
|
+
legacy: {
|
|
658
|
+
from: inspection.version,
|
|
659
|
+
unmapped: adapted.legacy.unmapped,
|
|
660
|
+
adapted: true,
|
|
661
|
+
},
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
|
|
574
665
|
/** Pull the archive from a secret gist. */
|
|
575
666
|
export async function pullGist(id, pass, root = configRoot(), token = envToken(), options = {}) {
|
|
576
667
|
if (!token) throw new Error("GitHub token required: set OMP_CFG_CLOUD_TOKEN or GITHUB_TOKEN");
|
|
577
668
|
const data = await gh(token, `/gists/${id}`);
|
|
578
669
|
const content = data?.files?.[GIST_FILE]?.content;
|
|
579
670
|
if (!content) throw new Error(`gist ${id} has no ${GIST_FILE}`);
|
|
580
|
-
|
|
671
|
+
const blob = Buffer.from(content, "base64");
|
|
672
|
+
return restoreRemoteArchive(blob, pass, root, options);
|
|
581
673
|
}
|
|
582
674
|
|
|
583
675
|
/** Push to any endpoint accepting PUT (presigned S3, WebDAV, custom). */
|
|
584
676
|
export async function pushHttp(url, pass, root = configRoot(), token = envToken()) {
|
|
585
|
-
const { blob, files } = buildArchive(pass, root);
|
|
677
|
+
const { blob, files, payload } = buildArchive(pass, root);
|
|
586
678
|
const headers = { "content-type": "application/octet-stream" };
|
|
587
679
|
if (token) headers.authorization = `Bearer ${token}`;
|
|
588
|
-
const res = await
|
|
680
|
+
const res = await fetchWithRetry(url, {
|
|
589
681
|
method: "PUT",
|
|
590
682
|
body: blob,
|
|
591
683
|
signal: AbortSignal.timeout(30_000),
|
|
592
684
|
headers,
|
|
593
685
|
});
|
|
594
686
|
if (!res.ok) throw new Error(`PUT ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
687
|
+
|
|
688
|
+
try {
|
|
689
|
+
commitPushBaseline(root, payload);
|
|
690
|
+
} catch (error) {
|
|
691
|
+
throw new Error(`Upload succeeded; local baseline commit failed: ${error.message}`);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
|
|
595
695
|
return { url, files, bytes: blob.length };
|
|
596
696
|
}
|
|
597
697
|
|
|
598
698
|
/** Pull from any endpoint serving the archive. */
|
|
599
699
|
export async function pullHttp(url, pass, root = configRoot(), token = envToken(), options = {}) {
|
|
600
|
-
const res = await
|
|
700
|
+
const res = await fetchWithRetry(url, {
|
|
601
701
|
signal: AbortSignal.timeout(30_000),
|
|
602
702
|
headers: token ? { authorization: `Bearer ${token}` } : {},
|
|
603
703
|
});
|
|
604
704
|
if (!res.ok) throw new Error(`GET ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
605
|
-
|
|
705
|
+
const blob = Buffer.from(await res.arrayBuffer());
|
|
706
|
+
return restoreRemoteArchive(blob, pass, root, options);
|
|
606
707
|
}
|
|
607
708
|
|
|
608
709
|
export function parseSpec(spec) {
|
|
@@ -612,22 +713,253 @@ export function parseSpec(spec) {
|
|
|
612
713
|
throw new Error("expected gist:<id|new> or an https URL");
|
|
613
714
|
}
|
|
614
715
|
|
|
615
|
-
function extractDryRun(str) {
|
|
616
|
-
const
|
|
617
|
-
|
|
618
|
-
|
|
716
|
+
export function extractDryRun(str) {
|
|
717
|
+
const raw = String(str || "").trim();
|
|
718
|
+
if (!raw) return { dryRun: false, clean: "" };
|
|
719
|
+
const tokens = [];
|
|
720
|
+
const re = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|(\S+)/g;
|
|
721
|
+
let match;
|
|
722
|
+
while ((match = re.exec(raw))) {
|
|
723
|
+
tokens.push(match[1] !== undefined ? match[1] : match[2] !== undefined ? match[2] : match[3]);
|
|
724
|
+
}
|
|
725
|
+
let dryRun = false;
|
|
726
|
+
const kept = [];
|
|
727
|
+
for (const token of tokens) {
|
|
728
|
+
if (token === "--dry-run" || token === "-d") {
|
|
729
|
+
dryRun = true;
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
kept.push(token);
|
|
733
|
+
}
|
|
734
|
+
return { dryRun, clean: kept.join(" ") };
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
export function formatSyncReport(result = {}) {
|
|
738
|
+
const lines = [];
|
|
739
|
+
for (const action of result.actions || []) {
|
|
740
|
+
lines.push(`[${action.action}] ${action.id} (${action.reason}) -> ${action.targetPath || ""}`);
|
|
741
|
+
}
|
|
742
|
+
for (const write of result.writes || []) {
|
|
743
|
+
lines.push(`[write:${write.operation}] ${write.path}`);
|
|
744
|
+
}
|
|
745
|
+
for (const conflict of result.conflicts || []) {
|
|
746
|
+
lines.push(`! conflict ${conflict.id}: ${conflict.reason}${conflict.targetPath ? ` (${conflict.targetPath})` : ""}`);
|
|
747
|
+
}
|
|
748
|
+
for (const blocked of result.blocked || []) {
|
|
749
|
+
lines.push(`X blocked ${blocked.id || ""}: ${blocked.reason}${blocked.targetPath ? ` (${blocked.targetPath})` : ""}`.replace(" ", " "));
|
|
750
|
+
}
|
|
751
|
+
for (const prerequisite of result.prerequisites || []) {
|
|
752
|
+
lines.push(`* prerequisite ${prerequisite}`);
|
|
753
|
+
}
|
|
754
|
+
if (!lines.length) {
|
|
755
|
+
lines.push("(no planned actions)");
|
|
756
|
+
}
|
|
757
|
+
return lines.join("\n");
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* Prompts interactive host user with multi-select askDialog to confirm exclusion of
|
|
762
|
+
* machine-binding resources. All non-private candidates default to public sync; only
|
|
763
|
+
* checked (excluded) items stay out of the public bundle.
|
|
764
|
+
*/
|
|
765
|
+
export async function selectPublicResources(ctx, root = configRoot()) {
|
|
766
|
+
// Returns "private" / "machine-binding" / null (generic, safe to sync by default).
|
|
767
|
+
function syncExclusionReason(item) {
|
|
768
|
+
if (item?.isPrivate === true) {
|
|
769
|
+
return "private";
|
|
770
|
+
}
|
|
771
|
+
let text;
|
|
772
|
+
try {
|
|
773
|
+
text = item?.value === undefined ? undefined : JSON.stringify(item.value);
|
|
774
|
+
} catch {
|
|
775
|
+
text = undefined;
|
|
776
|
+
}
|
|
777
|
+
if (text === undefined) {
|
|
778
|
+
text = String(item?.value ?? "");
|
|
779
|
+
}
|
|
780
|
+
const machineBindingPatterns = [
|
|
781
|
+
/(?:^|[^A-Za-z])[A-Za-z]:[\\/]/, // Windows drive path (not URL scheme)
|
|
782
|
+
/\\\\[^\\/]/, // UNC share path
|
|
783
|
+
/(?:^|[\s"'=])\/(?:Users|home|opt|data|usr|var)\//, // POSIX absolute path
|
|
784
|
+
/~\/|(?<![A-Za-z0-9_])(?:%USERPROFILE%|\$HOME|\$\{HOME\})/, // home dir tokens
|
|
785
|
+
/\b(?:127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\])\b/i, // loopback address
|
|
786
|
+
/!(?:bash|cat|type)\b/i, // local shell/file reads
|
|
787
|
+
];
|
|
788
|
+
return machineBindingPatterns.some((re) => re.test(text)) ? "machine-binding" : null;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
const inventory = inventoryResources(root);
|
|
792
|
+
if (!inventory || inventory.length === 0) {
|
|
793
|
+
ctx?.ui?.notify?.("No configuration resources found.", "info");
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
if (typeof ctx?.ui?.askDialog !== "function") {
|
|
798
|
+
ctx?.ui?.notify?.("当前宿主不支持空格多选,请升级 OMP", "error");
|
|
799
|
+
return null;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const policy = readSyncPolicy(root);
|
|
803
|
+
const state = readSyncState(root);
|
|
804
|
+
|
|
805
|
+
const sorted = [...inventory].sort((a, b) => a.id.localeCompare(b.id));
|
|
806
|
+
const candidates = sorted.filter(
|
|
807
|
+
(item) => resolveResourceScope(item.id, policy, state, item).scope !== "private"
|
|
808
|
+
);
|
|
809
|
+
|
|
810
|
+
const reasons = new Map();
|
|
811
|
+
const options = [];
|
|
812
|
+
for (const item of candidates) {
|
|
813
|
+
if (syncExclusionReason(item) === "machine-binding") {
|
|
814
|
+
reasons.set(item.id, "machine-binding");
|
|
815
|
+
options.push({
|
|
816
|
+
label: item.id,
|
|
817
|
+
description: `可能不适合同步 · ${item.id} · ${item.sourceRel}`,
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
const checkedSet = new Set();
|
|
823
|
+
|
|
824
|
+
if (options.length === 0) {
|
|
825
|
+
ctx?.ui?.notify?.(`未发现不适合同步项,默认同步 ${candidates.length} 项`, "info");
|
|
826
|
+
} else {
|
|
827
|
+
const dialogResult = await ctx.ui.askDialog([
|
|
828
|
+
{
|
|
829
|
+
id: "sync-exclude",
|
|
830
|
+
header: "SYNC",
|
|
831
|
+
question: "默认全部同步;空格勾选不适合同步的项 · Enter 确认 · Esc 取消",
|
|
832
|
+
multi: true,
|
|
833
|
+
options,
|
|
834
|
+
},
|
|
835
|
+
]);
|
|
836
|
+
|
|
837
|
+
if (!dialogResult || dialogResult.kind !== "submit") {
|
|
838
|
+
ctx?.ui?.notify?.("已取消,未修改公开范围", "info");
|
|
839
|
+
return null;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const answer = dialogResult.results?.find((item) => item.id === "sync-exclude");
|
|
843
|
+
const selectedOptions = dialogResult.selectedOptions ?? answer?.selectedOptions;
|
|
844
|
+
|
|
845
|
+
if (!Array.isArray(selectedOptions)) {
|
|
846
|
+
ctx?.ui?.notify?.("已取消,未修改公开范围", "info");
|
|
847
|
+
return null;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
for (const label of selectedOptions) {
|
|
851
|
+
if (!reasons.has(label)) {
|
|
852
|
+
ctx?.ui?.notify?.(`未知选项: ${label}`, "error");
|
|
853
|
+
return null;
|
|
854
|
+
}
|
|
855
|
+
checkedSet.add(label);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
for (const item of candidates) {
|
|
860
|
+
const id = item.id;
|
|
861
|
+
const isExplicitPublic = policy.resources?.[id] === "public";
|
|
862
|
+
if (checkedSet.has(id)) {
|
|
863
|
+
if (isExplicitPublic) {
|
|
864
|
+
try {
|
|
865
|
+
await setResourceScope(root, id, "private");
|
|
866
|
+
} catch (err) {
|
|
867
|
+
ctx?.ui?.notify?.(`公开范围未完成: ${id}: ${err.message || err}`, "error");
|
|
868
|
+
return null;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
} else if (!isExplicitPublic && !reasons.has(id)) {
|
|
872
|
+
// Generic (non machine-binding) candidates are public by default; unchecked
|
|
873
|
+
// machine-binding items keep their unclassified default (not synced).
|
|
874
|
+
try {
|
|
875
|
+
await setResourceScope(root, id, "public");
|
|
876
|
+
} catch (err) {
|
|
877
|
+
ctx?.ui?.notify?.(`公开范围未完成: ${id}: ${err.message || err}`, "error");
|
|
878
|
+
return null;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
const selected = candidates
|
|
884
|
+
.filter((item) => !checkedSet.has(item.id))
|
|
885
|
+
.filter((item) => !(reasons.has(item.id) && policy.resources?.[item.id] !== "public"))
|
|
886
|
+
.map((item) => item.id)
|
|
887
|
+
.sort();
|
|
888
|
+
const excluded = [...checkedSet].sort();
|
|
889
|
+
|
|
890
|
+
const updatedPolicy = readSyncPolicy(root);
|
|
891
|
+
const updatedState = readSyncState(root);
|
|
892
|
+
let publicCount = 0;
|
|
893
|
+
for (const item of inventory) {
|
|
894
|
+
const s = resolveResourceScope(item.id, updatedPolicy, updatedState, item);
|
|
895
|
+
if (s.scope === "public") publicCount++;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
return {
|
|
899
|
+
selected,
|
|
900
|
+
excluded,
|
|
901
|
+
publicCount,
|
|
902
|
+
};
|
|
619
903
|
}
|
|
620
904
|
|
|
621
905
|
/** Plugin entry: local and cloud config portability. */
|
|
622
906
|
export default function (pi) {
|
|
907
|
+
pi.registerCommand("config-scope", {
|
|
908
|
+
description: "Manage public/private synchronization scope (/config-scope list | set <id> public|private)",
|
|
909
|
+
handler: async (args, ctx) => {
|
|
910
|
+
const cleanArgs = (args || "").trim();
|
|
911
|
+
const parts = cleanArgs.split(/\s+/).filter(Boolean);
|
|
912
|
+
const sub = (parts[0] || "list").toLowerCase();
|
|
913
|
+
const root = configRoot();
|
|
914
|
+
|
|
915
|
+
try {
|
|
916
|
+
if (sub === "list" || sub === "ls") {
|
|
917
|
+
const policy = readSyncPolicy(root);
|
|
918
|
+
const state = readSyncState(root);
|
|
919
|
+
const inventory = inventoryResources(root);
|
|
920
|
+
if (inventory.length === 0) {
|
|
921
|
+
ctx.ui.notify("No configuration resources found.", "info");
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
const lines = inventory.map((item) => {
|
|
925
|
+
const scopeInfo = resolveResourceScope(item.id, policy, state, item);
|
|
926
|
+
return `[${scopeInfo.scope.toUpperCase()}] ${item.id} (source: ${item.sourceRel}, reason: ${scopeInfo.reason})`;
|
|
927
|
+
});
|
|
928
|
+
ctx.ui.notify(`Config Scope Inventory:\n${lines.join("\n")}`, "info");
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
if (sub === "set") {
|
|
933
|
+
const id = parts[1];
|
|
934
|
+
const scope = parts[2]?.toLowerCase();
|
|
935
|
+
if (!id || !scope || (scope !== "public" && scope !== "private")) {
|
|
936
|
+
ctx.ui.notify("Usage: /config-scope set <id> <public|private>", "error");
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
const res = await setResourceScope(root, id, scope);
|
|
940
|
+
let msg = `Scope for '${res.id}' set to '${res.scope}'.`;
|
|
941
|
+
if (res.warning) {
|
|
942
|
+
msg += `\n${res.warning}`;
|
|
943
|
+
}
|
|
944
|
+
ctx.ui.notify(msg, "info");
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
ctx.ui.notify(`Unknown subcommand: ${sub}. Use /config-scope list or /config-scope set <id> <public|private>`, "error");
|
|
949
|
+
} catch (err) {
|
|
950
|
+
ctx.ui.notify(`config-scope error: ${err.message || err}`, "error");
|
|
951
|
+
}
|
|
952
|
+
},
|
|
953
|
+
});
|
|
954
|
+
|
|
623
955
|
pi.registerCommand("config-export", {
|
|
624
|
-
description: "Encrypt omp config
|
|
956
|
+
description: "Encrypt public omp config resources to an archive",
|
|
625
957
|
handler: async (args, ctx) => {
|
|
626
958
|
const out = (args || "").trim() || path.join(os.homedir(), `omp-config-${Date.now()}.enc`);
|
|
627
959
|
try {
|
|
628
960
|
const pass = await askPass(ctx, "Export passphrase");
|
|
629
961
|
const r = exportEncrypted(out, pass);
|
|
630
|
-
ctx.ui.notify(`exported ${r.files}
|
|
962
|
+
ctx.ui.notify(`exported ${r.files} public resources (${r.bytes} B) → ${r.outFile}`, "info");
|
|
631
963
|
} catch (error) {
|
|
632
964
|
ctx.ui.notify(`config-export failed: ${error?.message ?? error}`, "error");
|
|
633
965
|
}
|
|
@@ -645,20 +977,29 @@ export default function (pi) {
|
|
|
645
977
|
try {
|
|
646
978
|
const pass = await askPass(ctx, "Import passphrase");
|
|
647
979
|
const r = importEncrypted(src, pass, configRoot(), { dryRun });
|
|
980
|
+
if (r.adaptedFile) {
|
|
981
|
+
ctx.ui.notify(`[import] incompatible v${r.legacy?.from}; adapted -> ${r.adaptedFile}`, "info");
|
|
982
|
+
}
|
|
648
983
|
if (dryRun) {
|
|
649
|
-
ctx.ui.notify(`[dry-run]
|
|
984
|
+
ctx.ui.notify(`[dry-run]\n${formatSyncReport(r)}`, "info");
|
|
650
985
|
} else {
|
|
651
986
|
ctx.ui.notify(`restored ${r.files} files${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
|
|
652
987
|
}
|
|
653
988
|
} catch (error) {
|
|
654
|
-
|
|
989
|
+
const report = error?.plan ? `\n${formatSyncReport(error.plan)}` : "";
|
|
990
|
+
ctx.ui.notify(`config-import failed: ${error?.message ?? error}${report}`, "error");
|
|
655
991
|
}
|
|
656
992
|
},
|
|
657
993
|
});
|
|
658
994
|
|
|
659
995
|
pi.registerCommand("config-push", {
|
|
660
|
-
description: "Encrypt and upload
|
|
996
|
+
description: "Encrypt and upload public configs to gist:<id|new> or an https URL",
|
|
661
997
|
handler: async (args, ctx) => {
|
|
998
|
+
const root = configRoot();
|
|
999
|
+
if (typeof ctx?.ui?.askDialog === "function") {
|
|
1000
|
+
const sel = await selectPublicResources(ctx, root);
|
|
1001
|
+
if (sel === null) return;
|
|
1002
|
+
}
|
|
662
1003
|
const spec = (args || "").trim();
|
|
663
1004
|
if (!spec) {
|
|
664
1005
|
ctx.ui.notify("usage: /config-push gist:new | gist:<id> | https://…", "error");
|
|
@@ -672,7 +1013,7 @@ export default function (pi) {
|
|
|
672
1013
|
? await pushGist(target.id, pass, configRoot(), token)
|
|
673
1014
|
: await pushHttp(target.url, pass, configRoot(), token);
|
|
674
1015
|
const where = r.url ? `${r.url} (id ${r.id})` : r.url;
|
|
675
|
-
ctx.ui.notify(`pushed ${r.files}
|
|
1016
|
+
ctx.ui.notify(`pushed ${r.files} public resources (${r.bytes} B) → ${where}`, "info");
|
|
676
1017
|
} catch (error) {
|
|
677
1018
|
ctx.ui.notify(`config-push failed: ${error?.message ?? error}`, "error");
|
|
678
1019
|
}
|
|
@@ -682,6 +1023,11 @@ export default function (pi) {
|
|
|
682
1023
|
pi.registerCommand("config-pull", {
|
|
683
1024
|
description: "Download and decrypt config from gist:<id> or an https URL (--dry-run to preview)",
|
|
684
1025
|
handler: async (args, ctx) => {
|
|
1026
|
+
const root = configRoot();
|
|
1027
|
+
if (typeof ctx?.ui?.askDialog === "function") {
|
|
1028
|
+
const sel = await selectPublicResources(ctx, root);
|
|
1029
|
+
if (sel === null) return;
|
|
1030
|
+
}
|
|
685
1031
|
const { dryRun, clean: spec } = extractDryRun(args || "");
|
|
686
1032
|
if (!spec) {
|
|
687
1033
|
ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run]", "error");
|
|
@@ -694,15 +1040,17 @@ export default function (pi) {
|
|
|
694
1040
|
const r = target.kind === "gist"
|
|
695
1041
|
? await pullGist(target.id, pass, configRoot(), token, { dryRun })
|
|
696
1042
|
: await pullHttp(target.url, pass, configRoot(), token, { dryRun });
|
|
1043
|
+
if (r.adaptedFile) {
|
|
1044
|
+
ctx.ui.notify(`[pull] incompatible v${r.legacy?.from}; adapted -> ${r.adaptedFile}`, "info");
|
|
1045
|
+
}
|
|
697
1046
|
if (dryRun) {
|
|
698
|
-
ctx.ui.notify(`[dry-run]
|
|
1047
|
+
ctx.ui.notify(`[dry-run]\n${formatSyncReport(r)}`, "info");
|
|
699
1048
|
} else {
|
|
700
|
-
|
|
701
|
-
const rehydratedMsg = rehydratedCount > 0 ? `, rehydrated ${rehydratedCount} plugins` : "";
|
|
702
|
-
ctx.ui.notify(`restored ${r.files} files${rehydratedMsg}${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
|
|
1049
|
+
ctx.ui.notify(`restored ${r.files} files${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
|
|
703
1050
|
}
|
|
704
1051
|
} catch (error) {
|
|
705
|
-
|
|
1052
|
+
const report = error?.plan ? `\n${formatSyncReport(error.plan)}` : "";
|
|
1053
|
+
ctx.ui.notify(`config-pull failed: ${error?.message ?? error}${report}`, "error");
|
|
706
1054
|
}
|
|
707
1055
|
},
|
|
708
1056
|
});
|
|
@@ -718,160 +1066,11 @@ export default function (pi) {
|
|
|
718
1066
|
}
|
|
719
1067
|
},
|
|
720
1068
|
});
|
|
721
|
-
pi.registerCommand("provider", {
|
|
722
|
-
description: "Manage LLM providers (/provider ls | add <name> <url> <key> | rm <name>)",
|
|
723
|
-
getArgumentCompletions: (prefix) => {
|
|
724
|
-
const parts = (prefix || "").split(/\s+/);
|
|
725
|
-
const sub = parts[0]?.toLowerCase();
|
|
726
|
-
|
|
727
|
-
if (!prefix.includes(" ") || parts.length <= 1) {
|
|
728
|
-
const subcommands = [
|
|
729
|
-
{ value: "add", description: "Auto-probe and add a new provider (wizard)" },
|
|
730
|
-
{ value: "ls", description: "List all configured providers & models" },
|
|
731
|
-
{ value: "rm", description: "Remove a provider from configuration" },
|
|
732
|
-
];
|
|
733
|
-
const p = parts[0]?.toLowerCase() || "";
|
|
734
|
-
return subcommands.filter((s) => s.value.startsWith(p));
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
if (sub === "rm" || sub === "remove") {
|
|
738
|
-
if (parts.length === 2) {
|
|
739
|
-
const providers = listProviders({ agentDir: configRoot() });
|
|
740
|
-
const target = parts[1].toLowerCase();
|
|
741
|
-
return providers
|
|
742
|
-
.map((p) => ({
|
|
743
|
-
value: p.name,
|
|
744
|
-
description: `${p.isPrivate ? "Private" : "Public"} (${p.models.length} models)`,
|
|
745
|
-
}))
|
|
746
|
-
.filter((i) => i.value.toLowerCase().startsWith(target));
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
if (sub === "add") {
|
|
751
|
-
const last = parts[parts.length - 1];
|
|
752
|
-
if (last.startsWith("-")) {
|
|
753
|
-
const flags = [
|
|
754
|
-
{ value: "--private", description: "Save to local-only, unsynced store (default)" },
|
|
755
|
-
{ value: "--public", description: "Save to synced models.yml" },
|
|
756
|
-
];
|
|
757
|
-
return flags.filter((f) => f.value.startsWith(last));
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
return null;
|
|
762
|
-
},
|
|
763
|
-
handler: async (args, ctx) => {
|
|
764
|
-
const cleanArgs = (args || "").trim();
|
|
765
|
-
const parts = cleanArgs.split(/\s+/).filter(Boolean);
|
|
766
|
-
const sub = parts[0] || "ls";
|
|
767
|
-
|
|
768
|
-
try {
|
|
769
|
-
if (sub === "ls" || sub === "list") {
|
|
770
|
-
const list = listProviders({ agentDir: configRoot() });
|
|
771
|
-
if (list.length === 0) {
|
|
772
|
-
ctx.ui.notify("No providers configured in public or private stores.", "info");
|
|
773
|
-
return;
|
|
774
|
-
}
|
|
775
|
-
const roles = getRoles(configRoot());
|
|
776
|
-
const lines = list.map((p) => {
|
|
777
|
-
const tier = p.isPrivate ? "PRIVATE (local-only)" : "PUBLIC (synced)";
|
|
778
|
-
const boundRoles = Object.entries(roles)
|
|
779
|
-
.filter(([_, ref]) => ref.startsWith(`${p.name}/`))
|
|
780
|
-
.map(([r]) => r);
|
|
781
|
-
const roleStr = boundRoles.length > 0 ? ` [roles: ${boundRoles.join(",")}]` : "";
|
|
782
|
-
return `${p.name} (${tier}, ${p.models.length} models)${roleStr}`;
|
|
783
|
-
});
|
|
784
|
-
ctx.ui.notify(`Providers:\n${lines.join("\n")}`, "info");
|
|
785
|
-
return;
|
|
786
|
-
}
|
|
787
|
-
|
|
788
|
-
if (sub === "rm" || sub === "remove") {
|
|
789
|
-
const name = parts[1];
|
|
790
|
-
if (!name) {
|
|
791
|
-
ctx.ui.notify("Usage: /provider rm <name>", "error");
|
|
792
|
-
return;
|
|
793
|
-
}
|
|
794
|
-
const removed = removeProvider({ name, agentDir: configRoot() });
|
|
795
|
-
if (removed) {
|
|
796
|
-
ctx.ui.notify(`Removed provider '${name}'`, "info");
|
|
797
|
-
} else {
|
|
798
|
-
ctx.ui.notify(`Provider '${name}' not found`, "warning");
|
|
799
|
-
}
|
|
800
|
-
return;
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
if (sub === "add" || sub === "wizard") {
|
|
804
|
-
let name = parts[1];
|
|
805
|
-
let url = parts[2];
|
|
806
|
-
let key = parts[3] || "";
|
|
807
|
-
let isPrivate = cleanArgs.includes("--private") || !cleanArgs.includes("--public");
|
|
808
|
-
|
|
809
|
-
if ((!name || !url) && typeof ctx?.ui?.input === "function") {
|
|
810
|
-
try {
|
|
811
|
-
if (!name) {
|
|
812
|
-
name = await ctx.ui.input({
|
|
813
|
-
title: "Provider Name",
|
|
814
|
-
prompt: "Enter unique provider name (e.g. my-private-llm):",
|
|
815
|
-
placeholder: "my-private-llm",
|
|
816
|
-
});
|
|
817
|
-
}
|
|
818
|
-
if (!url) {
|
|
819
|
-
url = await ctx.ui.input({
|
|
820
|
-
title: "Endpoint URL",
|
|
821
|
-
prompt: "Enter endpoint baseUrl (e.g. https://api.openai.com/v1):",
|
|
822
|
-
placeholder: "https://api.openai.com/v1",
|
|
823
|
-
});
|
|
824
|
-
}
|
|
825
|
-
if (!key) {
|
|
826
|
-
key = (await ctx.ui.input({
|
|
827
|
-
title: "API Key",
|
|
828
|
-
prompt: "Enter API Key (leave blank if none):",
|
|
829
|
-
placeholder: "sk-...",
|
|
830
|
-
})) || "";
|
|
831
|
-
}
|
|
832
|
-
} catch {}
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
if (!name || !url) {
|
|
836
|
-
ctx.ui.notify("Usage: /provider add <name> <url> [key] [--private|--public]", "error");
|
|
837
|
-
return;
|
|
838
|
-
}
|
|
839
|
-
ctx.ui.notify(`Probing endpoint ${url}...`, "info");
|
|
840
|
-
const probed = await probeProvider({
|
|
841
|
-
baseUrl: url,
|
|
842
|
-
apiKey: key,
|
|
843
|
-
providerName: name,
|
|
844
|
-
});
|
|
845
|
-
|
|
846
|
-
if (!probed.ok) {
|
|
847
|
-
ctx.ui.notify(`Probe failed: ${probed.error}`, "error");
|
|
848
|
-
return;
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
saveProvider({
|
|
852
|
-
name,
|
|
853
|
-
providerConfig: {
|
|
854
|
-
baseUrl: probed.normalizedBaseUrl,
|
|
855
|
-
api: probed.api,
|
|
856
|
-
apiKey: key,
|
|
857
|
-
models: probed.models,
|
|
858
|
-
},
|
|
859
|
-
isPrivate,
|
|
860
|
-
agentDir: configRoot(),
|
|
861
|
-
});
|
|
862
1069
|
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
return;
|
|
868
|
-
}
|
|
869
|
-
|
|
870
|
-
ctx.ui.notify("Usage: /provider [ls | add <name> <url> [key] [--private] | rm <name>]", "info");
|
|
871
|
-
} catch (err) {
|
|
872
|
-
ctx.ui.notify(`Provider command error: ${err.message || err}`, "error");
|
|
873
|
-
}
|
|
874
|
-
},
|
|
1070
|
+
pi.registerCommand("provider", {
|
|
1071
|
+
description: "Provider control menu · ls | add | edit <name> | test <name> | rm <name>",
|
|
1072
|
+
getArgumentCompletions: prefix => providerCompletions(prefix, configRoot()),
|
|
1073
|
+
handler: (args, ctx) => handleProviderCommand(pi, ctx, args, configRoot()),
|
|
875
1074
|
});
|
|
876
1075
|
|
|
877
1076
|
pi.registerCommand("role", {
|
|
@@ -911,7 +1110,8 @@ export default function (pi) {
|
|
|
911
1110
|
}
|
|
912
1111
|
}
|
|
913
1112
|
const target = parts[1].toLowerCase();
|
|
914
|
-
return models.filter((m) => m.value.toLowerCase().startsWith(target))
|
|
1113
|
+
return models.filter((m) => m.value.toLowerCase().startsWith(target))
|
|
1114
|
+
.map((m) => ({ ...m, label: m.value, value: prefix.slice(0, prefix.length - parts[1].length) + m.value }));
|
|
915
1115
|
}
|
|
916
1116
|
}
|
|
917
1117
|
|
|
@@ -972,6 +1172,41 @@ export default function (pi) {
|
|
|
972
1172
|
},
|
|
973
1173
|
});
|
|
974
1174
|
|
|
1175
|
+
// Register in-session upgrade command (/upgrade [check|plugins])
|
|
1176
|
+
pi.registerCommand("upgrade", {
|
|
1177
|
+
description: "Check for and apply updates for OMP and plugins (/upgrade [check|plugins])",
|
|
1178
|
+
handler: async (args, ctx) => {
|
|
1179
|
+
const clean = (args || "").trim().toLowerCase();
|
|
1180
|
+
if (clean === "check") {
|
|
1181
|
+
ctx.ui.notify("Checking for OMP updates...", "info");
|
|
1182
|
+
try {
|
|
1183
|
+
const { exec } = await import("node:child_process");
|
|
1184
|
+
const { promisify } = await import("node:util");
|
|
1185
|
+
const execAsync = promisify(exec);
|
|
1186
|
+
const { stdout } = await execAsync("omp update --check");
|
|
1187
|
+
ctx.ui.notify(stdout.trim() || "Check complete.", "info");
|
|
1188
|
+
} catch (err) {
|
|
1189
|
+
ctx.ui.notify(`Check error: ${err.message}`, "error");
|
|
1190
|
+
}
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
const pluginsOnly = clean === "plugins";
|
|
1195
|
+
ctx.ui.notify(pluginsOnly ? "Upgrading all plugins..." : "Upgrading OMP core & plugins in background...", "info");
|
|
1196
|
+
try {
|
|
1197
|
+
const { exec } = await import("node:child_process");
|
|
1198
|
+
const { promisify } = await import("node:util");
|
|
1199
|
+
const execAsync = promisify(exec);
|
|
1200
|
+
const cmd = pluginsOnly ? "omp plugin upgrade" : "omp update -l";
|
|
1201
|
+
const { stdout, stderr } = await execAsync(cmd);
|
|
1202
|
+
const output = (stdout + "\n" + stderr).trim().split("\n").filter(Boolean).slice(-2).join("; ");
|
|
1203
|
+
ctx.ui.notify(`Update finished: ${output || "Success"}. Restart OMP to apply kernel changes.`, "info");
|
|
1204
|
+
} catch (err) {
|
|
1205
|
+
ctx.ui.notify(`Upgrade error: ${err.message}`, "error");
|
|
1206
|
+
}
|
|
1207
|
+
},
|
|
1208
|
+
});
|
|
1209
|
+
|
|
975
1210
|
// Launch non-blocking background auto-maintenance (debounced every 24h)
|
|
976
1211
|
try {
|
|
977
1212
|
scheduleAutoMaintenance(configRoot(), 4000);
|