omp-config-crypt 0.6.3 → 0.6.5

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.
@@ -0,0 +1,744 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import {
5
+ configRoot,
6
+ MAX_FILE_SIZE,
7
+ ompHome,
8
+ parseJsonStrict,
9
+ parseYamlStrict,
10
+ pointerToTokens,
11
+ validateAssetFiles,
12
+ } from "./sync-files.js";
13
+
14
+ export { MAX_FILE_SIZE, parseYamlStrict, pointerToTokens };
15
+ import {
16
+ isExactSemver,
17
+ validateResourceId,
18
+ validateAssetPath,
19
+ } from "./sync-policy.js";
20
+
21
+ export const HOME_PLACEHOLDER = "{{OMP_HOME}}";
22
+
23
+ export const BLACKLIST_PATTERNS = [
24
+ /\.db$/,
25
+ /\.db-wal$/,
26
+ /\.db-shm$/,
27
+ /\.corrupt-/,
28
+ /\.local\./,
29
+ /\.local\//,
30
+ /(^|\/)local-/,
31
+ /^\.import-backup/,
32
+ /\/\.import-backup/,
33
+ /^\.rolled-back/,
34
+ /\/\.rolled-back/,
35
+ /(^|\/)\.git\//,
36
+ /(^|\/)cache\//,
37
+ /(^|\/)blobs\//,
38
+ /(^|\/)sessions\//,
39
+ /(^|\/)terminal-sessions\//,
40
+ /(^|\/)predict\//,
41
+ /(^|\/)node_modules\//,
42
+ /(^|\/)installation\//,
43
+ /(^|\/)providers\//,
44
+ /(^|\/)runtime\//,
45
+ /(^|\/)smoke\//,
46
+ /(^|\/)tools\/rea(\/|$)/,
47
+ /\.(zip|jar|apk|exe|dll|so|dylib|whl|tar|gz|7z)$/i,
48
+ ];
49
+
50
+ export function isBlacklisted(relPath) {
51
+ const norm = relPath.replace(/\\/g, "/");
52
+ return BLACKLIST_PATTERNS.some((rx) => rx.test(norm));
53
+ }
54
+
55
+ /**
56
+ * Whole-asset exclusions. BLACKLIST_PATTERNS guard individual FILES inside a bundle;
57
+ * these patterns exclude an entire asset directory from being a sync resource at all
58
+ * (inventory, menus, collect, archive). Keep the two lists separate: file-level patterns
59
+ * like /local-/ legitimately match asset names (e.g. tools/local-demo).
60
+ */
61
+ export const ASSET_EXCLUDE_PATTERNS = [
62
+ /(^|\/)tools\/rea(\/|$)/,
63
+ ];
64
+
65
+ export function isBlacklistedAssetPath(relPath) {
66
+ const norm = relPath.replace(/\\/g, "/");
67
+ return ASSET_EXCLUDE_PATTERNS.some((rx) => rx.test(norm));
68
+ }
69
+
70
+ /**
71
+ * Checks if a command exists in system PATH (lookpath / which equivalent).
72
+ */
73
+ export function isCommandInPath(cmd) {
74
+ if (!cmd || typeof cmd !== "string") return false;
75
+ if (cmd.includes("/") || cmd.includes("\\")) {
76
+ return fs.existsSync(cmd);
77
+ }
78
+ const pathEnv = process.env.PATH || "";
79
+ const sep = process.platform === "win32" ? ";" : ":";
80
+ const exts =
81
+ process.platform === "win32"
82
+ ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";").map((e) => e.toLowerCase())
83
+ : [""];
84
+
85
+ for (const dir of pathEnv.split(sep)) {
86
+ if (!dir) continue;
87
+ for (const ext of exts) {
88
+ const full = path.join(dir, cmd + ext);
89
+ try {
90
+ if (fs.existsSync(full) && fs.statSync(full).isFile()) {
91
+ return true;
92
+ }
93
+ } catch {}
94
+ }
95
+ }
96
+ return false;
97
+ }
98
+
99
+ /**
100
+ * Encodes segments into a JSON pointer.
101
+ */
102
+ export function tokensToPointer(tokens) {
103
+ return (
104
+ "/" +
105
+ tokens
106
+ .map((t) => String(t).replace(/~/g, "~0").replace(/\//g, "~1"))
107
+ .join("/")
108
+ );
109
+ }
110
+
111
+ /**
112
+ * Reads an asset directory/file ensuring no symlinks, blacklisted files, or oversized files.
113
+ * Returns sorted array of { path: archiveRel, data: base64, mode: number }.
114
+ */
115
+ export function readAssetBundle(baseDir, archivePrefix) {
116
+ const files = [];
117
+
118
+ function scan(currentDir, currentRel) {
119
+ if (!fs.existsSync(currentDir)) return;
120
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
121
+ for (const ent of entries) {
122
+ const relPath = currentRel ? `${currentRel}/${ent.name}` : ent.name;
123
+ const fullPath = path.join(currentDir, ent.name);
124
+ const lstat = fs.lstatSync(fullPath);
125
+
126
+ if (lstat.isSymbolicLink()) {
127
+ throw new Error(
128
+ `Asset '${archivePrefix}' cannot be bundled completely: contains symbolic link '${relPath}'`
129
+ );
130
+ }
131
+ if (isBlacklisted(relPath)) {
132
+ throw new Error(
133
+ `Asset '${archivePrefix}' cannot be bundled completely: contains blacklisted file '${relPath}'`
134
+ );
135
+ }
136
+
137
+ if (ent.isDirectory()) {
138
+ scan(fullPath, relPath);
139
+ } else if (ent.isFile()) {
140
+ if (lstat.size > MAX_FILE_SIZE) {
141
+ throw new Error(
142
+ `Asset '${archivePrefix}' cannot be bundled completely: file '${relPath}' (${lstat.size} B) exceeds 10 MiB limit`
143
+ );
144
+ }
145
+ const data = fs.readFileSync(fullPath).toString("base64");
146
+ const mode = lstat.mode & 0o777;
147
+ const archiveRel = `${archivePrefix}/${relPath}`.replace(/\\/g, "/");
148
+ files.push({ path: archiveRel, data, mode });
149
+ }
150
+ }
151
+ }
152
+
153
+ const stat = fs.lstatSync(baseDir);
154
+ if (stat.isSymbolicLink()) {
155
+ throw new Error(
156
+ `Asset '${archivePrefix}' cannot be bundled: root is a symbolic link`
157
+ );
158
+ }
159
+ if (stat.isDirectory()) {
160
+ scan(baseDir, "");
161
+ } else if (stat.isFile()) {
162
+ if (stat.size > MAX_FILE_SIZE) {
163
+ throw new Error(
164
+ `Asset '${archivePrefix}' exceeds 10 MiB limit`
165
+ );
166
+ }
167
+ const data = fs.readFileSync(baseDir).toString("base64");
168
+ const mode = stat.mode & 0o777;
169
+ files.push({ path: archivePrefix, data, mode });
170
+ }
171
+
172
+ // Sort files strictly by path
173
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
174
+ return files;
175
+ }
176
+
177
+ /**
178
+ * Inventories all local resources and their classifications.
179
+ * Returns array of:
180
+ * {
181
+ * id: string,
182
+ * category: "provider" | "mcp" | "setting" | "plugin" | "asset",
183
+ * name: string,
184
+ * sourceRel: string,
185
+ * isPrivate?: boolean,
186
+ * value?: any
187
+ * }
188
+ */
189
+ export function inventoryResources(root = configRoot()) {
190
+ const resources = [];
191
+ const agentDir = root;
192
+ const ompDir = ompHome(root);
193
+
194
+ // 1. Providers
195
+ // Read models.yml / models.yaml
196
+ let yamlFile = "models.yml";
197
+ let yamlPath = path.join(agentDir, "models.yml");
198
+ if (!fs.existsSync(yamlPath)) {
199
+ const yamlAlt = path.join(agentDir, "models.yaml");
200
+ if (fs.existsSync(yamlAlt)) {
201
+ yamlFile = "models.yaml";
202
+ yamlPath = yamlAlt;
203
+ }
204
+ }
205
+
206
+ let yamlProviders = {};
207
+ if (fs.existsSync(yamlPath)) {
208
+ try {
209
+ const doc = parseYamlStrict(fs.readFileSync(yamlPath, "utf8"), yamlFile);
210
+ const provs = doc.get("providers");
211
+ if (provs && typeof provs.toJSON === "function") {
212
+ yamlProviders = provs.toJSON() || {};
213
+ } else if (provs && typeof provs === "object") {
214
+ yamlProviders = provs;
215
+ }
216
+ } catch (err) {
217
+ throw new Error(`Failed to parse ${yamlFile}: ${err.message}`);
218
+ }
219
+ }
220
+
221
+ // Read models.local.json
222
+ const localJsonPath = path.join(agentDir, "models.local.json");
223
+ let localJsonProviders = {};
224
+ if (fs.existsSync(localJsonPath)) {
225
+ const parsed = parseJsonStrict(fs.readFileSync(localJsonPath, "utf8"), "models.local.json");
226
+ if (parsed?.providers && typeof parsed.providers === "object" && !Array.isArray(parsed.providers)) {
227
+ localJsonProviders = parsed.providers;
228
+ }
229
+ }
230
+
231
+ const allProviderNames = new Set([
232
+ ...Object.keys(yamlProviders),
233
+ ...Object.keys(localJsonProviders),
234
+ ]);
235
+
236
+ for (const name of Array.from(allProviderNames).sort()) {
237
+ const yamlCfg = Object.hasOwn(yamlProviders, name) ? yamlProviders[name] : null;
238
+ const localCfg = Object.hasOwn(localJsonProviders, name) ? localJsonProviders[name] : null;
239
+ const inLocal = localCfg !== null;
240
+ const inYaml = yamlCfg !== null;
241
+ const yamlPrivate = yamlCfg?.private === true;
242
+
243
+ const isPrivate = inLocal || yamlPrivate;
244
+ const effectiveCfg = (isPrivate && localCfg !== null) ? localCfg : (yamlCfg !== null ? yamlCfg : localCfg);
245
+
246
+ resources.push({
247
+ id: `provider:${name}`,
248
+ category: "provider",
249
+ name,
250
+ sourceRel: inLocal ? "models.local.json" : yamlFile,
251
+ isPrivate,
252
+ value: effectiveCfg,
253
+ });
254
+ }
255
+
256
+ // 2. MCP Servers
257
+ const mcpPath = path.join(agentDir, "mcp.json");
258
+ if (fs.existsSync(mcpPath)) {
259
+ const mcpData = parseJsonStrict(fs.readFileSync(mcpPath, "utf8"), "mcp.json");
260
+ if (mcpData?.mcpServers && typeof mcpData.mcpServers === "object" && !Array.isArray(mcpData.mcpServers)) {
261
+ for (const name of Object.keys(mcpData.mcpServers)) {
262
+ const cfg = mcpData.mcpServers[name];
263
+ if (typeof cfg !== "object" || cfg === null || Array.isArray(cfg)) {
264
+ throw new Error(`Invalid MCP server '${name}': value must be an object`);
265
+ }
266
+ resources.push({
267
+ id: `mcp:${name}`,
268
+ category: "mcp",
269
+ name,
270
+ sourceRel: "mcp.json",
271
+ isPrivate: false,
272
+ value: cfg,
273
+ });
274
+ }
275
+ }
276
+ }
277
+
278
+ // 3. Settings in config.yml / config.yaml
279
+ let configFileName = "config.yml";
280
+ let configFilePath = path.join(agentDir, "config.yml");
281
+ if (!fs.existsSync(configFilePath)) {
282
+ const configAlt = path.join(agentDir, "config.yaml");
283
+ if (fs.existsSync(configAlt)) {
284
+ configFileName = "config.yaml";
285
+ configFilePath = configAlt;
286
+ }
287
+ }
288
+
289
+ if (fs.existsSync(configFilePath)) {
290
+ try {
291
+ const doc = parseYamlStrict(
292
+ fs.readFileSync(configFilePath, "utf8"),
293
+ configFileName
294
+ );
295
+ const json = doc.toJSON() || {};
296
+
297
+ function collectLeaves(obj, tokens = []) {
298
+ if (
299
+ obj === null ||
300
+ typeof obj !== "object" ||
301
+ Array.isArray(obj)
302
+ ) {
303
+ const ptr = tokensToPointer(tokens);
304
+ resources.push({
305
+ id: `setting:${ptr}`,
306
+ category: "setting",
307
+ name: ptr,
308
+ sourceRel: configFileName,
309
+ isPrivate: false,
310
+ value: obj,
311
+ });
312
+ return;
313
+ }
314
+ for (const [k, v] of Object.entries(obj)) {
315
+ collectLeaves(v, [...tokens, k]);
316
+ }
317
+ }
318
+
319
+ collectLeaves(json);
320
+ } catch (err) {
321
+ throw new Error(`Failed to parse ${configFileName}: ${err.message}`);
322
+ }
323
+ }
324
+
325
+ // 4. Skills (agent/skills and managed-skills)
326
+ const skillsBase = path.join(agentDir, "skills");
327
+ if (fs.existsSync(skillsBase)) {
328
+ const entries = fs.readdirSync(skillsBase, { withFileTypes: true });
329
+ for (const ent of entries) {
330
+ if (ent.isDirectory()) {
331
+ const skillMd = path.join(skillsBase, ent.name, "SKILL.md");
332
+ if (fs.existsSync(skillMd)) {
333
+ resources.push({
334
+ id: `asset:skills/${ent.name}`,
335
+ category: "asset",
336
+ name: `skills/${ent.name}`,
337
+ sourceRel: `skills/${ent.name}`,
338
+ isPrivate: false,
339
+ });
340
+ }
341
+ }
342
+ }
343
+ }
344
+
345
+ const managedSkillsBase = path.join(agentDir, "managed-skills");
346
+ if (fs.existsSync(managedSkillsBase)) {
347
+ const entries = fs.readdirSync(managedSkillsBase, { withFileTypes: true });
348
+ for (const ent of entries) {
349
+ if (ent.isDirectory()) {
350
+ const skillMd = path.join(managedSkillsBase, ent.name, "SKILL.md");
351
+ if (fs.existsSync(skillMd)) {
352
+ resources.push({
353
+ id: `asset:managed-skills/${ent.name}`,
354
+ category: "asset",
355
+ name: `managed-skills/${ent.name}`,
356
+ sourceRel: `managed-skills/${ent.name}`,
357
+ isPrivate: false,
358
+ });
359
+ }
360
+ }
361
+ }
362
+ }
363
+
364
+ // 5. Extensions, Tools, Hooks, Top-level Files
365
+ // Extensions in agent/extensions
366
+ const agentExtDir = path.join(agentDir, "extensions");
367
+ if (fs.existsSync(agentExtDir)) {
368
+ for (const ent of fs.readdirSync(agentExtDir, { withFileTypes: true })) {
369
+ resources.push({
370
+ id: `asset:extensions/${ent.name}`,
371
+ category: "asset",
372
+ name: `extensions/${ent.name}`,
373
+ sourceRel: `extensions/${ent.name}`,
374
+ isPrivate: false,
375
+ });
376
+ }
377
+ }
378
+
379
+ // Tools in ompHome/tools
380
+ const toolsDir = path.join(ompDir, "tools");
381
+ if (fs.existsSync(toolsDir)) {
382
+ for (const ent of fs.readdirSync(toolsDir, { withFileTypes: true })) {
383
+ resources.push({
384
+ id: `asset:tools/${ent.name}`,
385
+ category: "asset",
386
+ name: `tools/${ent.name}`,
387
+ sourceRel: `tools/${ent.name}`,
388
+ isPrivate: false,
389
+ });
390
+ }
391
+ }
392
+
393
+ // Hooks in ompHome/hooks
394
+ const hooksDir = path.join(ompDir, "hooks");
395
+ if (fs.existsSync(hooksDir)) {
396
+ for (const ent of fs.readdirSync(hooksDir, { withFileTypes: true })) {
397
+ resources.push({
398
+ id: `asset:hooks/${ent.name}`,
399
+ category: "asset",
400
+ name: `hooks/${ent.name}`,
401
+ sourceRel: `hooks/${ent.name}`,
402
+ isPrivate: false,
403
+ });
404
+ }
405
+ }
406
+
407
+ // Top level instruction files
408
+ for (const docFile of ["AGENTS.md", "STYLE.md", "RULES.md"]) {
409
+ const p = path.join(agentDir, docFile);
410
+ if (fs.existsSync(p)) {
411
+ resources.push({
412
+ id: `asset:${docFile}`,
413
+ category: "asset",
414
+ name: docFile,
415
+ sourceRel: docFile,
416
+ isPrivate: false,
417
+ });
418
+ }
419
+ }
420
+
421
+ // 6. Plugins
422
+ const pluginsDir = path.join(ompDir, "plugins");
423
+ const pluginPkgPath = path.join(pluginsDir, "package.json");
424
+ if (fs.existsSync(pluginPkgPath)) {
425
+ const pkg = parseJsonStrict(fs.readFileSync(pluginPkgPath, "utf8"), "plugins/package.json");
426
+ const lockPath = path.join(pluginsDir, "omp-plugins.lock.json");
427
+ let lockData = {};
428
+ if (fs.existsSync(lockPath)) {
429
+ lockData = parseJsonStrict(fs.readFileSync(lockPath, "utf8"), "omp-plugins.lock.json") || {};
430
+ }
431
+ const dependencies = pkg.dependencies && typeof pkg.dependencies === "object" ? pkg.dependencies : {};
432
+ for (const pkgName of Object.keys(dependencies)) {
433
+ const versionSpec = dependencies[pkgName];
434
+ if (pkgName === "omp-config-crypt") continue;
435
+ const lockEntry = lockData.plugins && Object.hasOwn(lockData.plugins, pkgName) ? lockData.plugins[pkgName] : undefined;
436
+ resources.push({
437
+ id: `plugin:${pkgName}`,
438
+ category: "plugin",
439
+ name: pkgName,
440
+ sourceRel: "plugins/package.json",
441
+ isPrivate: false,
442
+ value: {
443
+ name: pkgName,
444
+ versionSpec,
445
+ lockVersion: lockEntry?.version,
446
+ enabled: lockEntry?.enabled !== false,
447
+ },
448
+ });
449
+ }
450
+ }
451
+
452
+ // Whole-asset exclusions (e.g. tools/rea) are not sync resources at all: they can
453
+ // never bundle (blacklisted internals), so offering them breaks collect/archive/push.
454
+ // The per-file blacklist still guards files INSIDE every other asset.
455
+ return resources.filter((item) => item.category !== "asset" || !isBlacklistedAssetPath(item.name));
456
+ }
457
+
458
+ /**
459
+ * Reads a single resource value by ID from the filesystem.
460
+ */
461
+ export function readResource(root = configRoot(), id) {
462
+ const { prefix, name } = validateResourceId(id);
463
+ const agentDir = root;
464
+ const ompDir = ompHome(root);
465
+
466
+ if (prefix === "provider") {
467
+ const localJsonPath = path.join(agentDir, "models.local.json");
468
+ let localCfg = null;
469
+ if (fs.existsSync(localJsonPath)) {
470
+ const json = parseJsonStrict(fs.readFileSync(localJsonPath, "utf8"), "models.local.json");
471
+ localCfg = json?.providers && Object.hasOwn(json.providers, name) ? json.providers[name] : null;
472
+ }
473
+
474
+ let yamlCfg = null;
475
+ const yamlFile = fs.existsSync(path.join(agentDir, "models.yml")) ? "models.yml" : "models.yaml";
476
+ const yamlPath = path.join(agentDir, yamlFile);
477
+ if (fs.existsSync(yamlPath)) {
478
+ const doc = parseYamlStrict(fs.readFileSync(yamlPath, "utf8"), yamlFile);
479
+ const provs = doc.get("providers");
480
+ if (provs && typeof provs.get === "function") {
481
+ const node = provs.get(name);
482
+ if (node !== undefined) yamlCfg = typeof node?.toJSON === "function" ? node.toJSON() : node;
483
+ }
484
+ }
485
+
486
+ for (const [label, value] of [["models.local.json", localCfg], [yamlFile, yamlCfg]]) {
487
+ if (value !== null && (typeof value !== "object" || Array.isArray(value))) {
488
+ throw new Error(`Invalid provider '${name}' in ${label}: value must be an object`);
489
+ }
490
+ }
491
+ const isPrivate = localCfg !== null || yamlCfg?.private === true;
492
+ const value = isPrivate && localCfg !== null ? localCfg : (yamlCfg !== null ? yamlCfg : localCfg);
493
+ if (value === null) return null;
494
+ return { id, isPrivate, value };
495
+ }
496
+
497
+ if (prefix === "mcp") {
498
+ const mcpPath = path.join(agentDir, "mcp.json");
499
+ if (!fs.existsSync(mcpPath)) return null;
500
+ const data = parseJsonStrict(fs.readFileSync(mcpPath, "utf8"), "mcp.json");
501
+ const server = data?.mcpServers && Object.hasOwn(data.mcpServers, name) ? data.mcpServers[name] : null;
502
+ if (server === null) return null;
503
+ if (typeof server !== "object" || Array.isArray(server)) {
504
+ throw new Error(`Invalid MCP server '${name}': value must be an object`);
505
+ }
506
+ return { id, isPrivate: false, value: server };
507
+ }
508
+
509
+ if (prefix === "setting") {
510
+ const configFile = fs.existsSync(path.join(agentDir, "config.yml")) ? "config.yml" : "config.yaml";
511
+ const configFilePath = path.join(agentDir, configFile);
512
+ if (!fs.existsSync(configFilePath)) return null;
513
+ const doc = parseYamlStrict(fs.readFileSync(configFilePath, "utf8"), configFile);
514
+ const tokens = pointerToTokens(name);
515
+ const valNode = doc.getIn(tokens);
516
+ if (valNode === undefined) return null;
517
+ const value = typeof valNode?.toJSON === "function" ? valNode.toJSON() : valNode;
518
+ return { id, isPrivate: false, value };
519
+ }
520
+
521
+ if (prefix === "plugin") {
522
+ const pluginsDir = path.join(ompDir, "plugins");
523
+ const pkgPath = path.join(pluginsDir, "package.json");
524
+ if (!fs.existsSync(pkgPath)) return null;
525
+ const pkg = parseJsonStrict(fs.readFileSync(pkgPath, "utf8"), "plugins/package.json");
526
+ const versionSpec = pkg?.dependencies && Object.hasOwn(pkg.dependencies, name) ? pkg.dependencies[name] : undefined;
527
+ if (versionSpec === undefined) return null;
528
+
529
+ const installedPkgPath = path.join(pluginsDir, "node_modules", ...name.split("/"), "package.json");
530
+ let installedVersion = null;
531
+ if (fs.existsSync(installedPkgPath)) {
532
+ const installed = parseJsonStrict(fs.readFileSync(installedPkgPath, "utf8"), `${name} package.json`);
533
+ installedVersion = installed.version;
534
+ }
535
+
536
+ const lockPath = path.join(pluginsDir, "omp-plugins.lock.json");
537
+ let lockData = {};
538
+ if (fs.existsSync(lockPath)) {
539
+ lockData = parseJsonStrict(fs.readFileSync(lockPath, "utf8"), "omp-plugins.lock.json") || {};
540
+ }
541
+ const lockEntry = lockData.plugins && Object.hasOwn(lockData.plugins, name) ? lockData.plugins[name] : undefined;
542
+
543
+ return {
544
+ id,
545
+ isPrivate: false,
546
+ value: {
547
+ name,
548
+ versionSpec,
549
+ installedVersion,
550
+ lockVersion: lockEntry?.version,
551
+ enabled: lockEntry?.enabled !== false,
552
+ },
553
+ };
554
+ }
555
+
556
+ if (prefix === "asset") {
557
+ const archiveRel = name;
558
+ const diskPath = archiveRel.startsWith("tools/") || archiveRel.startsWith("hooks/")
559
+ ? path.join(ompDir, archiveRel)
560
+ : path.join(agentDir, archiveRel);
561
+ if (!fs.existsSync(diskPath)) return null;
562
+ return { id, isPrivate: false, value: readAssetBundle(diskPath, archiveRel) };
563
+ }
564
+
565
+ return null;
566
+ }
567
+
568
+ function cloneJson(value) {
569
+ if (Array.isArray(value)) return value.map(cloneJson);
570
+ if (!value || typeof value !== "object") return value;
571
+ const copy = {};
572
+ for (const key of Object.keys(value)) {
573
+ Object.defineProperty(copy, key, {
574
+ value: cloneJson(value[key]),
575
+ enumerable: true,
576
+ configurable: true,
577
+ writable: true,
578
+ });
579
+ }
580
+ return copy;
581
+ }
582
+
583
+ function normalizedSlashes(value) {
584
+ return value.replace(/\\/g, "/");
585
+ }
586
+
587
+ function samePortablePath(a, b) {
588
+ return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
589
+ }
590
+
591
+ function isAbsoluteHostPath(value) {
592
+ return typeof value === "string" &&
593
+ (path.isAbsolute(value) || /^[a-zA-Z]:[/\\]/.test(value) || value.startsWith("/") || value.startsWith("\\\\"));
594
+ }
595
+
596
+ function mapHomePath(id, value, field) {
597
+ if (!isAbsoluteHostPath(value)) return value;
598
+ const home = normalizedSlashes(os.homedir()).replace(/\/+$/, "");
599
+ const candidate = normalizedSlashes(value);
600
+ if (samePortablePath(candidate, home)) return HOME_PLACEHOLDER;
601
+ if (candidate.length > home.length && samePortablePath(candidate.slice(0, home.length), home) &&
602
+ candidate[home.length] === "/") {
603
+ return HOME_PLACEHOLDER + candidate.slice(home.length);
604
+ }
605
+ throw new Error(`Resource '${id}' field '${field}' contains an absolute path outside HOME; it must be self-contained before publishing`);
606
+ }
607
+
608
+ function containsAbsolutePath(value) {
609
+ if (typeof value === "string") return isAbsoluteHostPath(value);
610
+ if (Array.isArray(value)) return value.some(containsAbsolutePath);
611
+ if (value && typeof value === "object") return Object.values(value).some(containsAbsolutePath);
612
+ return false;
613
+ }
614
+
615
+ /**
616
+ * Returns the sole canonical representation used for export, comparison, and baselines.
617
+ */
618
+ export function canonicalResourceValue(id, value, root = configRoot()) {
619
+ const { prefix, name } = validateResourceId(id);
620
+
621
+ if (prefix === "plugin") {
622
+ let version;
623
+ if (Object.hasOwn(value, "versionSpec")) {
624
+ // npm-style registry ranges (e.g. ^1.0.0) can never equal an installed version,
625
+ // so the portable truth is the exact installed version. Non-registry sources
626
+ // (file:, link:, git, aliases) must not be published as registry versions.
627
+ const spec = value.versionSpec;
628
+ const registryBased =
629
+ typeof spec === "string" &&
630
+ !spec.includes(":") &&
631
+ !spec.startsWith("/") &&
632
+ !spec.startsWith("./") &&
633
+ !spec.startsWith("../") &&
634
+ !/^[0-9a-f]{40}$/i.test(spec);
635
+ const exact = isExactSemver(spec) ? spec : registryBased ? value.installedVersion : undefined;
636
+ if (!isExactSemver(exact)) {
637
+ throw new Error(`Plugin '${name}' declaration is not an exact semver registry version`);
638
+ }
639
+ if (!isExactSemver(value.installedVersion) || value.installedVersion !== exact) {
640
+ throw new Error(`Plugin '${name}' must be installed at exactly its declared version`);
641
+ }
642
+ if (value.lockVersion !== undefined && value.lockVersion !== null && value.lockVersion !== exact) {
643
+ throw new Error(`Plugin '${name}' lock version conflicts with its declared version`);
644
+ }
645
+ version = exact;
646
+ } else {
647
+ if (!isExactSemver(value.version)) {
648
+ throw new Error(`Plugin '${name}' version is not exact SemVer`);
649
+ }
650
+ if (value.installedVersion !== undefined && value.installedVersion !== null &&
651
+ (!isExactSemver(value.installedVersion) || value.installedVersion !== value.version)) {
652
+ throw new Error(`Plugin '${name}' installed version conflicts with its declared version`);
653
+ }
654
+ version = value.version;
655
+ }
656
+ if (typeof value.enabled !== "boolean") {
657
+ throw new Error(`Plugin '${name}' enabled flag must be boolean`);
658
+ }
659
+ return { name, version, enabled: value.enabled };
660
+ }
661
+
662
+ if (prefix === "mcp") {
663
+ const copy = cloneJson(value);
664
+ if (Object.hasOwn(copy, "cwd")) copy.cwd = mapHomePath(id, copy.cwd, "cwd");
665
+ if (Object.hasOwn(copy, "command")) copy.command = mapHomePath(id, copy.command, "command");
666
+ if (Array.isArray(copy.args)) {
667
+ copy.args = copy.args.map((arg, index) => mapHomePath(id, arg, `args[${index}]`));
668
+ }
669
+ return copy;
670
+ }
671
+
672
+ if (prefix === "setting") {
673
+ if (name === "/shellPath") return mapHomePath(id, value, "value");
674
+ if (name.startsWith("/extensions") && containsAbsolutePath(value)) {
675
+ throw new Error(`Resource '${id}' contains an absolute path; extensions must use the native scanner`);
676
+ }
677
+ return cloneJson(value);
678
+ }
679
+
680
+ if (prefix === "provider") {
681
+ const copy = cloneJson(value);
682
+ delete copy.private;
683
+ return copy;
684
+ }
685
+
686
+ if (prefix === "asset") {
687
+ validateAssetFiles(name, value);
688
+ return value
689
+ .map((file) => ({ path: file.path, data: file.data, mode: file.mode }))
690
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
691
+ }
692
+
693
+ return cloneJson(value);
694
+ }
695
+
696
+ /**
697
+ * Sanitizes a resource value for public export.
698
+ */
699
+ export function sanitizeResourceForExport(id, value, root = configRoot()) {
700
+ return canonicalResourceValue(id, value, root);
701
+ }
702
+
703
+ /**
704
+ * Restores a resource value for target environment import.
705
+ * - Replaces {{OMP_HOME}} with target os.homedir().
706
+ * - Checks PATH command prerequisites for MCP.
707
+ */
708
+ export function restoreResourceForImport(id, value, root = configRoot()) {
709
+ const { prefix, name } = validateResourceId(id);
710
+ const home = os.homedir();
711
+ const prerequisites = [];
712
+
713
+ function restoreHomeBoundary(str) {
714
+ if (typeof str !== "string" || !str.startsWith(HOME_PLACEHOLDER)) return str;
715
+ const suffix = str.slice(HOME_PLACEHOLDER.length);
716
+ if (suffix && suffix[0] !== "/" && suffix[0] !== "\\") return str;
717
+ if (!suffix) return home;
718
+ const parts = suffix.split(/[\\/]/).filter(Boolean);
719
+ return path.join(home, ...parts);
720
+ }
721
+
722
+ if (prefix === "mcp") {
723
+ const copy = cloneJson(value);
724
+ if (Object.hasOwn(copy, "cwd")) copy.cwd = restoreHomeBoundary(copy.cwd);
725
+ if (Object.hasOwn(copy, "command")) {
726
+ copy.command = restoreHomeBoundary(copy.command);
727
+ if (!copy.command.includes("/") && !copy.command.includes("\\")) {
728
+ if (!isCommandInPath(copy.command)) {
729
+ prerequisites.push(
730
+ `MCP server '${id}': command '${copy.command}' is not found in local system PATH`
731
+ );
732
+ }
733
+ }
734
+ }
735
+ if (Array.isArray(copy.args)) copy.args = copy.args.map(restoreHomeBoundary);
736
+ return { value: copy, prerequisites };
737
+ }
738
+
739
+ if (prefix === "setting" && name === "/shellPath") {
740
+ return { value: restoreHomeBoundary(value), prerequisites };
741
+ }
742
+
743
+ return { value: cloneJson(value), prerequisites };
744
+ }