omp-config-crypt 0.4.1 → 0.5.1

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.4.0)
1
+ # omp-config-crypt (v0.5.0)
2
2
 
3
3
  Universal, zero-repair cross-platform configuration encryption and synchronization engine for `omp` (Oh My Pi).
4
4
 
@@ -52,6 +52,15 @@ npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN"
52
52
  npx omp-config-crypt rollback
53
53
  ```
54
54
 
55
+ # Provider Auto-Probing & Management (Public / Private)
56
+ npx omp-config-crypt provider add my-provider --url "https://api.openai.com/v1" --key "sk-..." --role smol --private
57
+
58
+ # List all configured providers & role bindings
59
+ npx omp-config-crypt provider list
60
+
61
+ # Bind a model role (default, smol, plan, slow, web)
62
+ npx omp-config-crypt role set smol my-provider/gpt-4o-mini
63
+
55
64
  ---
56
65
 
57
66
  ## In-OMP Slash Commands
package/bin/omp-sync.js CHANGED
@@ -18,6 +18,13 @@ import {
18
18
  rollback,
19
19
  parseSpec,
20
20
  rehydratePlugins,
21
+ probeProvider,
22
+ saveProvider,
23
+ removeProvider,
24
+ listProviders,
25
+ getRoles,
26
+ setRole,
27
+ VALID_ROLES,
21
28
  } from "../index.js";
22
29
 
23
30
  function printHelp() {
@@ -34,6 +41,11 @@ Commands:
34
41
  pull <gist:id|url> Download and restore configs from Gist or HTTP URL
35
42
  rollback Revert the most recent config restore from its backup
36
43
  rehydrate Rehydrate and repair locked/linked plugins in ~/.omp/plugins
44
+ provider add <name> Auto-probe and add an LLM provider (public or private)
45
+ provider ls / list List configured providers, models and active role bindings
46
+ provider rm <name> Remove a provider from public or private store
47
+ role set <role> <ref> Bind role (default/smol/plan/slow/web) to provider/model
48
+ role ls / list List active model role mappings
37
49
 
38
50
  Options:
39
51
  -p, --pass <passphrase> Decryption/Encryption passphrase (or OMP_CONFIG_PASS)
@@ -43,6 +55,14 @@ Options:
43
55
  -h, --help Show this help message
44
56
  --no-rehydrate Skip automatic plugin rehydration on import/pull
45
57
  --rehydrate Enforce plugin rehydration (default: true)
58
+ -u, --url <url> Endpoint URL for provider (e.g. https://api.openai.com/v1)
59
+ -k, --key <key> Provider API Key
60
+ --api <type> API type: openai-completions (default) | anthropic-messages
61
+ -m, --model <id> Model ID to select/bind
62
+ --role <role> Auto-bind role upon adding (default, smol, plan, slow, web)
63
+ --private Save as private (local-only, unsynced, non-overwritten) [default]
64
+ --public Save as public (synced across machines via models.yml)
65
+ -y, --yes Non-interactive mode (use defaults without prompting)
46
66
 
47
67
  Environment Variables:
48
68
  OMP_CONFIG_PASS Passphrase for non-interactive automation
@@ -64,6 +84,14 @@ function parseCliArgs(argv) {
64
84
  dryRun: false,
65
85
  rehydrate: true,
66
86
  help: false,
87
+ url: null,
88
+ key: null,
89
+ api: "openai-completions",
90
+ model: null,
91
+ role: null,
92
+ isPrivate: null,
93
+ nonInteractive: false,
94
+ positional: [],
67
95
  };
68
96
 
69
97
  const positional = [];
@@ -83,12 +111,38 @@ function parseCliArgs(argv) {
83
111
  options.token = args[++i];
84
112
  } else if (a === "-r" || a === "--root") {
85
113
  options.root = args[++i];
114
+ } else if (a === "-u" || a === "--url") {
115
+ options.url = args[++i];
116
+ } else if (a === "-k" || a === "--key") {
117
+ options.key = args[++i];
118
+ } else if (a === "--api") {
119
+ options.api = args[++i];
120
+ } else if (a === "-m" || a === "--model") {
121
+ options.model = args[++i];
122
+ } else if (a === "--role") {
123
+ options.role = args[++i];
124
+ } else if (a === "--private") {
125
+ options.isPrivate = true;
126
+ } else if (a === "--public") {
127
+ options.isPrivate = false;
128
+ } else if (a === "-y" || a === "--yes" || a === "--non-interactive") {
129
+ options.nonInteractive = true;
86
130
  } else if (a.startsWith("--pass=")) {
87
131
  options.pass = a.slice(7);
88
132
  } else if (a.startsWith("--token=")) {
89
133
  options.token = a.slice(8);
90
134
  } else if (a.startsWith("--root=")) {
91
135
  options.root = a.slice(7);
136
+ } else if (a.startsWith("--url=")) {
137
+ options.url = a.slice(6);
138
+ } else if (a.startsWith("--key=")) {
139
+ options.key = a.slice(6);
140
+ } else if (a.startsWith("--api=")) {
141
+ options.api = a.slice(6);
142
+ } else if (a.startsWith("--model=")) {
143
+ options.model = a.slice(8);
144
+ } else if (a.startsWith("--role=")) {
145
+ options.role = a.slice(7);
92
146
  } else {
93
147
  positional.push(a);
94
148
  }
@@ -96,6 +150,7 @@ function parseCliArgs(argv) {
96
150
 
97
151
  options.command = positional[0] || null;
98
152
  options.target = positional[1] || null;
153
+ options.positional = positional;
99
154
  return options;
100
155
  }
101
156
 
@@ -177,7 +232,7 @@ async function main() {
177
232
 
178
233
  case "push": {
179
234
  if (!options.target) {
180
- throw new Error("Usage: omp-sync push <gist:new|gist:<id>|https://...> [options]");
235
+ throw new Error("Usage: omp-sync push <gist:id|new|https://url> [options]");
181
236
  }
182
237
  const target = parseSpec(options.target);
183
238
  const pass = await resolvePass(options.pass);
@@ -186,14 +241,20 @@ async function main() {
186
241
  target.kind === "gist"
187
242
  ? await pushGist(target.id, pass, root, token)
188
243
  : await pushHttp(target.url, pass, root, token);
189
- const dest = res.url ? `${res.url} (id: ${res.id})` : res.url;
190
- console.log(`[push] Pushed ${res.files} files (${res.bytes} bytes) -> ${dest}`);
244
+
245
+ console.log(`[push] Successfully pushed ${res.files} files (${res.bytes} bytes).`);
246
+ if (res.url) {
247
+ console.log(`[url] Gist URL: ${res.url}`);
248
+ }
249
+ if (res.id) {
250
+ console.log(`[id] Gist ID: ${res.id}`);
251
+ }
191
252
  break;
192
253
  }
193
254
 
194
255
  case "pull": {
195
256
  if (!options.target) {
196
- throw new Error("Usage: omp-sync pull <gist:<id>|https://...> [options]");
257
+ throw new Error("Usage: omp-sync pull <gist:id|https://url> [options]");
197
258
  }
198
259
  const target = parseSpec(options.target);
199
260
  const pass = await resolvePass(options.pass);
@@ -227,6 +288,7 @@ async function main() {
227
288
  console.log(`[rollback] Successfully rolled back ${res.files} files from snapshot ${res.rolledBackFrom}`);
228
289
  break;
229
290
  }
291
+
230
292
  case "rehydrate": {
231
293
  const res = rehydratePlugins(root, { dryRun: options.dryRun });
232
294
  console.log(
@@ -240,6 +302,223 @@ async function main() {
240
302
  break;
241
303
  }
242
304
 
305
+ case "provider": {
306
+ const sub = (options.target || "list").toLowerCase();
307
+ if (sub === "list" || sub === "ls") {
308
+ const providers = listProviders({ agentDir: root });
309
+ if (providers.length === 0) {
310
+ console.log("No providers configured in public or private stores.");
311
+ break;
312
+ }
313
+ const roles = getRoles(root);
314
+ console.log("Configured Providers:");
315
+ for (const p of providers) {
316
+ const tier = p.isPrivate
317
+ ? "\x1b[33m[PRIVATE (local-only, unsynced)]\x1b[0m"
318
+ : "\x1b[32m[PUBLIC (synced)]\x1b[0m";
319
+ const boundRoles = Object.entries(roles)
320
+ .filter(([_, ref]) => ref.startsWith(`${p.name}/`))
321
+ .map(([r, ref]) => `${r} -> ${ref.split("/")[1]}`);
322
+ const roleStr = boundRoles.length > 0 ? ` (Active: ${boundRoles.join(", ")})` : "";
323
+ console.log(` • ${p.name} ${tier}: ${p.baseUrl} (${p.api}, ${p.models.length} models)${roleStr}`);
324
+ for (const m of p.models.slice(0, 5)) {
325
+ const flags = [
326
+ m.reasoning ? "reasoning" : null,
327
+ m.input?.includes("image") ? "vision" : null,
328
+ `${m.contextWindow / 1000}k ctx`,
329
+ ]
330
+ .filter(Boolean)
331
+ .join(", ");
332
+ console.log(` - ${m.id} [${flags}]`);
333
+ }
334
+ if (p.models.length > 5) {
335
+ console.log(` ... and ${p.models.length - 5} more models`);
336
+ }
337
+ }
338
+ break;
339
+ }
340
+
341
+ if (sub === "remove" || sub === "rm") {
342
+ const name = options.positional[2];
343
+ if (!name) {
344
+ throw new Error("Usage: omp-sync provider remove <name>");
345
+ }
346
+ const removed = removeProvider({ name, agentDir: root });
347
+ if (removed) {
348
+ console.log(`[provider] ✓ Removed provider '${name}'`);
349
+ } else {
350
+ console.log(`[provider] Provider '${name}' not found.`);
351
+ }
352
+ break;
353
+ }
354
+
355
+ if (sub === "add") {
356
+ let name = options.positional[2];
357
+ if (!name) {
358
+ if (process.stdin.isTTY && !options.nonInteractive) {
359
+ name = await promptText("Enter a unique provider name (e.g. my-private-llm): ");
360
+ }
361
+ if (!name) {
362
+ throw new Error("Usage: omp-sync provider add <name> [options]");
363
+ }
364
+ }
365
+
366
+ let url = options.url;
367
+ if (!url) {
368
+ if (process.stdin.isTTY && !options.nonInteractive) {
369
+ url = await promptText("Enter endpoint baseUrl (e.g. https://api.openai.com/v1): ");
370
+ } else {
371
+ throw new Error("Missing --url parameter for provider");
372
+ }
373
+ }
374
+
375
+ let key = options.key;
376
+ if (key === null) {
377
+ if (process.stdin.isTTY && !options.nonInteractive) {
378
+ key = await promptText("Enter API Key (press Enter if none): ");
379
+ } else {
380
+ key = "";
381
+ }
382
+ }
383
+
384
+ let isPrivate = options.isPrivate;
385
+ if (isPrivate === null) {
386
+ if (process.stdin.isTTY && !options.nonInteractive) {
387
+ const ans = await promptText("Is this provider private (local-only, unsynced)? [Y/n]: ");
388
+ isPrivate = !/^n/i.test(ans.trim());
389
+ } else {
390
+ isPrivate = true; // Default to private for safety
391
+ }
392
+ }
393
+
394
+ console.log(`[probe] Probing endpoint ${url}...`);
395
+ const probed = await probeProvider({
396
+ baseUrl: url,
397
+ apiKey: key,
398
+ api: options.api,
399
+ testModelId: options.model,
400
+ providerName: name,
401
+ });
402
+
403
+ if (!probed.ok) {
404
+ console.error(`[probe] ✗ Probe failed: ${probed.error}`);
405
+ if (!options.model) {
406
+ throw new Error("Probe failed and no fallback --model specified. Aborted.");
407
+ }
408
+ } else {
409
+ console.log(`[probe] ✓ Endpoint verified: ${probed.normalizedBaseUrl} (${probed.api})`);
410
+ console.log(`[probe] ✓ Discovered ${probed.models.length} model(s)`);
411
+ }
412
+
413
+ let chosenModel = options.model;
414
+ if (!chosenModel && probed.ok && probed.models.length > 0 && process.stdin.isTTY && !options.nonInteractive) {
415
+ console.log("\nDiscovered models:");
416
+ const displayList = probed.models.slice(0, 8);
417
+ displayList.forEach((m, idx) => {
418
+ const flags = [
419
+ m.reasoning ? "reasoning" : null,
420
+ m.input?.includes("image") ? "vision" : null,
421
+ `${m.contextWindow / 1000}k ctx`,
422
+ ]
423
+ .filter(Boolean)
424
+ .join(", ");
425
+ console.log(` [${idx + 1}] ${m.id} (${flags})`);
426
+ });
427
+ const sel = await promptText(`Select primary model [1-${displayList.length}, default 1]: `);
428
+ const selIdx = parseInt(sel, 10);
429
+ if (!isNaN(selIdx) && selIdx >= 1 && selIdx <= displayList.length) {
430
+ chosenModel = displayList[selIdx - 1].id;
431
+ } else {
432
+ chosenModel = displayList[0].id;
433
+ }
434
+ }
435
+
436
+ let roleToBind = options.role;
437
+ if (!roleToBind && process.stdin.isTTY && !options.nonInteractive) {
438
+ console.log("\nBind this model to an OMP role? (optional)");
439
+ console.log(" [1] default (primary chat & orchestration)");
440
+ console.log(" [2] smol (fast/subagent & tool execution)");
441
+ console.log(" [3] plan (high-context architectural planning)");
442
+ console.log(" [4] slow (deep reasoning / hard debug)");
443
+ console.log(" [0] Skip (no binding)");
444
+ const roleAns = await promptText("Select role [0-4, default 0]: ");
445
+ const roleMap = { "1": "default", "2": "smol", "3": "plan", "4": "slow" };
446
+ if (roleMap[roleAns.trim()]) {
447
+ roleToBind = roleMap[roleAns.trim()];
448
+ }
449
+ }
450
+
451
+ const models = probed.ok && probed.models.length > 0
452
+ ? probed.models
453
+ : [{ id: options.model || "custom-model", name: `${name} custom model`, contextWindow: 128000, maxTokens: 32000 }];
454
+
455
+ saveProvider({
456
+ name,
457
+ providerConfig: {
458
+ baseUrl: probed.ok ? probed.normalizedBaseUrl : url,
459
+ api: probed.ok ? probed.api : options.api,
460
+ apiKey: key,
461
+ models,
462
+ },
463
+ isPrivate,
464
+ agentDir: root,
465
+ });
466
+
467
+ console.log(
468
+ `[provider] ✓ Provider '${name}' saved to ${
469
+ isPrivate ? "PRIVATE store (models.local.json)" : "PUBLIC store (models.yml)"
470
+ }`
471
+ );
472
+
473
+ if (roleToBind) {
474
+ const modelToBind = chosenModel || models[0]?.id;
475
+ setRole(roleToBind, `${name}/${modelToBind}`, { agentDir: root, validate: false });
476
+ console.log(`[role] ✓ Role '${roleToBind}' bound to ${name}/${modelToBind}`);
477
+ }
478
+ break;
479
+ }
480
+
481
+ throw new Error(`Unknown provider subcommand: ${sub}. Allowed: add, list, remove.`);
482
+ }
483
+
484
+ case "role": {
485
+ const sub = (options.target || "list").toLowerCase();
486
+ if (sub === "list" || sub === "ls") {
487
+ const roles = getRoles(root);
488
+ console.log("Current Model Roles:");
489
+ for (const r of VALID_ROLES) {
490
+ console.log(` ${r.padEnd(8)}: ${roles[r] || "(not set)"}`);
491
+ }
492
+ break;
493
+ }
494
+
495
+ if (sub === "set") {
496
+ const roleName = options.positional[2];
497
+ const modelRef = options.positional[3];
498
+ if (!roleName || !modelRef) {
499
+ throw new Error("Usage: omp-sync role set <default|smol|plan|slow|web> <provider/model>");
500
+ }
501
+ setRole(roleName, modelRef, { agentDir: root });
502
+ console.log(`[role] ✓ Role '${roleName}' set to '${modelRef}'`);
503
+ break;
504
+ }
505
+
506
+ // Shortcut: omp-sync role <roleName> <modelRef>
507
+ if (VALID_ROLES.includes(sub)) {
508
+ const modelRef = options.positional[2];
509
+ if (!modelRef) {
510
+ const roles = getRoles(root);
511
+ console.log(`${sub}: ${roles[sub] || "(not set)"}`);
512
+ } else {
513
+ setRole(sub, modelRef, { agentDir: root });
514
+ console.log(`[role] ✓ Role '${sub}' set to '${modelRef}'`);
515
+ }
516
+ break;
517
+ }
518
+
519
+ throw new Error(`Unknown role subcommand: ${sub}. Allowed: list, set.`);
520
+ }
521
+
243
522
  default:
244
523
  console.error(`Unknown command: ${options.command}`);
245
524
  printHelp();
package/index.js CHANGED
@@ -21,6 +21,23 @@ export {
21
21
  savePluginLinks,
22
22
  detectMissingPlugins,
23
23
  };
24
+ export {
25
+ probeProvider,
26
+ inferModelCapabilities,
27
+ filterChatModels,
28
+ } from "./src/prober.js";
29
+ export {
30
+ saveProvider,
31
+ removeProvider,
32
+ listProviders,
33
+ getProvider,
34
+ readPublicProviders,
35
+ writePublicProviders,
36
+ readPrivateProviders,
37
+ writePrivateProviders,
38
+ ensureLocalExtension,
39
+ } from "./src/provider-store.js";
40
+ export { getRoles, setRole, VALID_ROLES } from "./src/role-manager.js";
24
41
 
25
42
  const MAGIC = Buffer.from("OMPCFG1\0", "latin1");
26
43
  const HOME_PLACEHOLDER = "{{OMP_HOME}}";
@@ -45,6 +62,7 @@ const BLACKLIST_PATTERNS = [
45
62
  /\.corrupt-/,
46
63
  /\.local\./,
47
64
  /\.local\//,
65
+ /(^|\/)local-/,
48
66
  /^\.import-backup/,
49
67
  /\/\.import-backup/,
50
68
  /^\.rolled-back/,
@@ -610,4 +628,150 @@ export default function (pi) {
610
628
  }
611
629
  },
612
630
  });
631
+ pi.registerCommand("provider", {
632
+ description: "Manage LLM providers (/provider ls | add <name> <url> <key> | rm <name>)",
633
+ handler: async (args, ctx) => {
634
+ const cleanArgs = (args || "").trim();
635
+ const parts = cleanArgs.split(/\s+/).filter(Boolean);
636
+ const sub = parts[0] || "ls";
637
+
638
+ try {
639
+ if (sub === "ls" || sub === "list") {
640
+ const list = listProviders({ agentDir: configRoot() });
641
+ if (list.length === 0) {
642
+ ctx.ui.notify("No providers configured in public or private stores.", "info");
643
+ return;
644
+ }
645
+ const roles = getRoles(configRoot());
646
+ const lines = list.map((p) => {
647
+ const tier = p.isPrivate ? "PRIVATE (local-only)" : "PUBLIC (synced)";
648
+ const boundRoles = Object.entries(roles)
649
+ .filter(([_, ref]) => ref.startsWith(`${p.name}/`))
650
+ .map(([r]) => r);
651
+ const roleStr = boundRoles.length > 0 ? ` [roles: ${boundRoles.join(",")}]` : "";
652
+ return `${p.name} (${tier}, ${p.models.length} models)${roleStr}`;
653
+ });
654
+ ctx.ui.notify(`Providers:\n${lines.join("\n")}`, "info");
655
+ return;
656
+ }
657
+
658
+ if (sub === "rm" || sub === "remove") {
659
+ const name = parts[1];
660
+ if (!name) {
661
+ ctx.ui.notify("Usage: /provider rm <name>", "error");
662
+ return;
663
+ }
664
+ const removed = removeProvider({ name, agentDir: configRoot() });
665
+ if (removed) {
666
+ ctx.ui.notify(`Removed provider '${name}'`, "info");
667
+ } else {
668
+ ctx.ui.notify(`Provider '${name}' not found`, "warning");
669
+ }
670
+ return;
671
+ }
672
+
673
+ if (sub === "add" || sub === "wizard") {
674
+ let name = parts[1];
675
+ let url = parts[2];
676
+ let key = parts[3] || "";
677
+ let isPrivate = cleanArgs.includes("--private") || !cleanArgs.includes("--public");
678
+
679
+ if ((!name || !url) && typeof ctx?.ui?.input === "function") {
680
+ try {
681
+ if (!name) {
682
+ name = await ctx.ui.input({
683
+ title: "Provider Name",
684
+ prompt: "Enter unique provider name (e.g. my-private-llm):",
685
+ placeholder: "my-private-llm",
686
+ });
687
+ }
688
+ if (!url) {
689
+ url = await ctx.ui.input({
690
+ title: "Endpoint URL",
691
+ prompt: "Enter endpoint baseUrl (e.g. https://api.openai.com/v1):",
692
+ placeholder: "https://api.openai.com/v1",
693
+ });
694
+ }
695
+ if (!key) {
696
+ key = (await ctx.ui.input({
697
+ title: "API Key",
698
+ prompt: "Enter API Key (leave blank if none):",
699
+ placeholder: "sk-...",
700
+ })) || "";
701
+ }
702
+ } catch {}
703
+ }
704
+
705
+ if (!name || !url) {
706
+ ctx.ui.notify("Usage: /provider add <name> <url> [key] [--private|--public]", "error");
707
+ return;
708
+ }
709
+ ctx.ui.notify(`Probing endpoint ${url}...`, "info");
710
+ const probed = await probeProvider({
711
+ baseUrl: url,
712
+ apiKey: key,
713
+ providerName: name,
714
+ });
715
+
716
+ if (!probed.ok) {
717
+ ctx.ui.notify(`Probe failed: ${probed.error}`, "error");
718
+ return;
719
+ }
720
+
721
+ saveProvider({
722
+ name,
723
+ providerConfig: {
724
+ baseUrl: probed.normalizedBaseUrl,
725
+ api: probed.api,
726
+ apiKey: key,
727
+ models: probed.models,
728
+ },
729
+ isPrivate,
730
+ agentDir: configRoot(),
731
+ });
732
+
733
+ ctx.ui.notify(
734
+ `Added ${isPrivate ? "private" : "public"} provider '${name}' with ${probed.models.length} model(s) at ${probed.normalizedBaseUrl}`,
735
+ "info"
736
+ );
737
+ return;
738
+ }
739
+
740
+ ctx.ui.notify("Usage: /provider [ls | add <name> <url> [key] [--private] | rm <name>]", "info");
741
+ } catch (err) {
742
+ ctx.ui.notify(`Provider command error: ${err.message || err}`, "error");
743
+ }
744
+ },
745
+ });
746
+
747
+ pi.registerCommand("role", {
748
+ description: "Manage model roles (/role ls | <role> <provider/model>)",
749
+ handler: async (args, ctx) => {
750
+ const cleanArgs = (args || "").trim();
751
+ const parts = cleanArgs.split(/\s+/).filter(Boolean);
752
+
753
+ try {
754
+ if (!cleanArgs || parts[0] === "ls" || parts[0] === "list") {
755
+ const roles = getRoles(configRoot());
756
+ const str = Object.entries(roles)
757
+ .map(([r, m]) => `${r}: ${m}`)
758
+ .join(", ");
759
+ ctx.ui.notify(`Model Roles: ${str || "none"}`, "info");
760
+ return;
761
+ }
762
+
763
+ const role = parts[0];
764
+ const modelRef = parts[1];
765
+ if (!role || !modelRef) {
766
+ ctx.ui.notify("Usage: /role <default|smol|plan|slow|web> <provider/model>", "error");
767
+ return;
768
+ }
769
+
770
+ setRole(role, modelRef, { agentDir: configRoot() });
771
+ ctx.ui.notify(`Set role '${role}' -> ${modelRef}`, "info");
772
+ } catch (err) {
773
+ ctx.ui.notify(`Role command error: ${err.message || err}`, "error");
774
+ }
775
+ },
776
+ });
613
777
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/prober.js ADDED
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Provider & Model Auto-Probing and Capability Discovery Engine
3
+ */
4
+
5
+ const NON_CHAT_PATTERNS = [
6
+ /embed/i,
7
+ /rerank/i,
8
+ /tts/i,
9
+ /whisper/i,
10
+ /audio/i,
11
+ /voice/i,
12
+ /moderation/i,
13
+ /dall-e/i,
14
+ /flux/i,
15
+ /midjourney/i,
16
+ /stable-diffusion/i,
17
+ /upscale/i,
18
+ /realtime/i,
19
+ ];
20
+
21
+ /**
22
+ * Filter out non-conversational models from raw provider catalog.
23
+ */
24
+ export function filterChatModels(rawModels) {
25
+ if (!Array.isArray(rawModels)) return [];
26
+ return rawModels.filter((m) => {
27
+ const id = typeof m === "string" ? m : m?.id;
28
+ if (!id || typeof id !== "string") return false;
29
+ return !NON_CHAT_PATTERNS.some((pattern) => pattern.test(id));
30
+ });
31
+ }
32
+
33
+ /**
34
+ * Infer model capabilities, context window, max tokens, modalities and reasoning flags.
35
+ */
36
+ export function inferModelCapabilities(modelId, providerHint = "") {
37
+ const id = modelId.toLowerCase();
38
+
39
+ // Reasoning detection
40
+ const isReasoning =
41
+ /(thinking|reasoner|reasoning|deepseek-r1|\br1\b|\bo1\b|\bo3\b|-high\b|-thought\b)/i.test(id);
42
+
43
+ // Vision / Multimodal detection
44
+ const isVision =
45
+ /(vision|\bvl\b|omni|\b4o\b|flash|gemini|claude|sonnet|opus|qwen-vl|glm-4v)/i.test(id);
46
+
47
+ // Context window heuristics
48
+ let contextWindow = 128000;
49
+ if (/gemini-1\.5|gemini-2\.0|gemini-3\.0|gemini-3\.5|gemini-3\.8/i.test(id)) {
50
+ contextWindow = /pro/i.test(id) ? 1000000 : 256000;
51
+ } else if (/claude-3/i.test(id)) {
52
+ contextWindow = 200000;
53
+ } else if (/kimi|moonshot/i.test(id)) {
54
+ contextWindow = 256000;
55
+ } else if (/deepseek/i.test(id)) {
56
+ contextWindow = 128000;
57
+ } else if (/qwen/i.test(id)) {
58
+ contextWindow = /32b|72b|128k/i.test(id) ? 131072 : 65536;
59
+ } else if (/glm-4/i.test(id)) {
60
+ contextWindow = 128000;
61
+ }
62
+
63
+ // Max output tokens heuristics
64
+ let maxTokens = 32000;
65
+ if (/claude-3-5|claude-3-7/i.test(id)) {
66
+ maxTokens = 8192;
67
+ } else if (/gpt-4o/i.test(id)) {
68
+ maxTokens = 16384;
69
+ } else if (/qwen/i.test(id)) {
70
+ maxTokens = 8192;
71
+ } else if (contextWindow <= 65536) {
72
+ maxTokens = Math.min(maxTokens, 8192);
73
+ }
74
+
75
+ // Formatting display name
76
+ const name = `${modelId}${providerHint ? ` (${providerHint})` : ""}`;
77
+
78
+ const spec = {
79
+ id: modelId,
80
+ name,
81
+ input: isVision ? ["text", "image"] : ["text"],
82
+ contextWindow,
83
+ maxTokens,
84
+ };
85
+
86
+ if (isReasoning) {
87
+ spec.reasoning = true;
88
+ }
89
+
90
+ // Compat flags for quirky providers
91
+ if (/kimi|moonshot/i.test(id) || /kimi/i.test(providerHint)) {
92
+ spec.compat = {
93
+ supportsForcedToolChoice: false,
94
+ };
95
+ }
96
+
97
+ return spec;
98
+ }
99
+
100
+ /**
101
+ * Probe an endpoint to find the working baseUrl, API flavor, and available models.
102
+ */
103
+ export async function probeProvider({
104
+ baseUrl,
105
+ apiKey,
106
+ api = "openai-completions",
107
+ testModelId,
108
+ providerName = "",
109
+ timeout = 10000,
110
+ }) {
111
+ let cleanUrl = (baseUrl || "").trim().replace(/\/+$/, "");
112
+ if (!cleanUrl) {
113
+ return { ok: false, error: "Missing baseUrl" };
114
+ }
115
+
116
+ const controller = new AbortController();
117
+ const timer = setTimeout(() => controller.abort(), timeout);
118
+
119
+ try {
120
+ if (api === "anthropic-messages") {
121
+ // Probe Anthropic endpoint
122
+ const res = await testAnthropic(cleanUrl, apiKey, controller.signal);
123
+ clearTimeout(timer);
124
+ if (res.ok) {
125
+ const models = (res.models && res.models.length > 0)
126
+ ? res.models.map((m) => inferModelCapabilities(m.id || m, providerName))
127
+ : [inferModelCapabilities(testModelId || "claude-3-7-sonnet-20250219", providerName)];
128
+ return {
129
+ ok: true,
130
+ normalizedBaseUrl: res.normalizedUrl,
131
+ api: "anthropic-messages",
132
+ models,
133
+ probedVia: res.probedVia,
134
+ };
135
+ }
136
+ return { ok: false, error: res.error || "Anthropic endpoint unreachable" };
137
+ }
138
+
139
+ // Default to openai-completions probe
140
+ // 1. Try /models endpoints first (with and without /v1)
141
+ const hasV1 = /\/v1$/i.test(cleanUrl);
142
+ const candidateUrls = hasV1
143
+ ? [cleanUrl, cleanUrl.replace(/\/v1$/i, "")]
144
+ : [cleanUrl, `${cleanUrl}/v1`];
145
+
146
+ for (const url of candidateUrls) {
147
+ const modelsEndpoint = `${url}/models`;
148
+ try {
149
+ const res = await fetch(modelsEndpoint, {
150
+ method: "GET",
151
+ headers: {
152
+ Authorization: `Bearer ${apiKey}`,
153
+ Accept: "application/json",
154
+ },
155
+ signal: controller.signal,
156
+ });
157
+
158
+ if (res.status === 200) {
159
+ const json = await res.json();
160
+ const rawList = Array.isArray(json?.data) ? json.data : Array.isArray(json) ? json : [];
161
+ const filtered = filterChatModels(rawList);
162
+ if (filtered.length > 0) {
163
+ clearTimeout(timer);
164
+ // In OMP, openai-completions appends /chat/completions.
165
+ // If models endpoint was at ${url}/models, the baseUrl must be ${url}.
166
+ return {
167
+ ok: true,
168
+ normalizedBaseUrl: url,
169
+ api: "openai-completions",
170
+ models: filtered.map((m) => inferModelCapabilities(m.id || m, providerName)),
171
+ probedVia: "models_endpoint",
172
+ };
173
+ }
174
+ }
175
+ } catch {}
176
+ }
177
+
178
+ // 2. If /models failed or returned 404, probe chat/completions directly
179
+ for (const url of candidateUrls) {
180
+ const chatEndpoint = `${url}/chat/completions`;
181
+ const modelToTest = testModelId || "test-probe";
182
+ try {
183
+ const res = await fetch(chatEndpoint, {
184
+ method: "POST",
185
+ headers: {
186
+ Authorization: `Bearer ${apiKey}`,
187
+ "Content-Type": "application/json",
188
+ },
189
+ body: JSON.stringify({
190
+ model: modelToTest,
191
+ messages: [{ role: "user", content: "hi" }],
192
+ max_tokens: 1,
193
+ }),
194
+ signal: controller.signal,
195
+ });
196
+
197
+ // 200 = Success; 400/404 with error JSON about model not found also confirms the endpoint exists!
198
+ if (res.status === 200 || res.status === 400 || res.status === 404) {
199
+ let isJsonError = false;
200
+ try {
201
+ const errJson = await res.json();
202
+ // If it returned structured error, the endpoint is indeed an active OpenAI API!
203
+ if (errJson?.error) isJsonError = true;
204
+ } catch {}
205
+
206
+ if (res.status === 200 || isJsonError) {
207
+ clearTimeout(timer);
208
+ const models = testModelId
209
+ ? [inferModelCapabilities(testModelId, providerName)]
210
+ : [];
211
+ return {
212
+ ok: true,
213
+ normalizedBaseUrl: url,
214
+ api: "openai-completions",
215
+ models,
216
+ probedVia: "chat_completions",
217
+ };
218
+ }
219
+ }
220
+ } catch {}
221
+ }
222
+
223
+ clearTimeout(timer);
224
+ return {
225
+ ok: false,
226
+ error: `Could not verify OpenAI endpoint at ${cleanUrl}. Both /models and /chat/completions failed.`,
227
+ };
228
+ } catch (err) {
229
+ clearTimeout(timer);
230
+ return { ok: false, error: err.name === "AbortError" ? "Probe timed out" : err.message };
231
+ }
232
+ }
233
+
234
+ async function testAnthropic(cleanUrl, apiKey, signal) {
235
+ const candidateUrls = [cleanUrl, `${cleanUrl}/v1`].filter((u, i, a) => a.indexOf(u) === i);
236
+ for (const url of candidateUrls) {
237
+ try {
238
+ const endpoint = `${url}/messages`;
239
+ const res = await fetch(endpoint, {
240
+ method: "POST",
241
+ headers: {
242
+ "x-api-key": apiKey,
243
+ "anthropic-version": "2023-06-01",
244
+ "Content-Type": "application/json",
245
+ },
246
+ body: JSON.stringify({
247
+ model: "claude-3-haiku-20240307",
248
+ messages: [{ role: "user", content: "hi" }],
249
+ max_tokens: 1,
250
+ }),
251
+ signal,
252
+ });
253
+
254
+ if (res.status === 200 || res.status === 400) {
255
+ return { ok: true, normalizedUrl: url, probedVia: "messages_endpoint" };
256
+ }
257
+ } catch {}
258
+ }
259
+ return { ok: false, error: "Anthropic /messages endpoint failed" };
260
+ }
@@ -0,0 +1,365 @@
1
+ /**
2
+ * Dual-Tier Provider Storage Manager
3
+ *
4
+ * Segregates public (synced) configurations in `models.yml` from
5
+ * private/host-specific (unsynced, non-overwritten) configurations in `models.local.json`.
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import os from "node:os";
11
+
12
+ export function getAgentDir(customRoot) {
13
+ return customRoot || process.env.OMP_CFG_ROOT || path.join(os.homedir(), ".omp", "agent");
14
+ }
15
+
16
+ export function getOmpDir(customRoot) {
17
+ return path.dirname(getAgentDir(customRoot));
18
+ }
19
+
20
+ const LOCAL_LOADER_SCRIPT = `import fs from "node:fs";
21
+ import path from "node:path";
22
+ import os from "node:os";
23
+
24
+ export default function (pi) {
25
+ const agentDir = process.env.OMP_CFG_ROOT || path.join(os.homedir(), ".omp", "agent");
26
+ const localPath = path.join(agentDir, "models.local.json");
27
+ if (!fs.existsSync(localPath)) return;
28
+ try {
29
+ const data = JSON.parse(fs.readFileSync(localPath, "utf8"));
30
+ for (const [name, cfg] of Object.entries(data.providers || {})) {
31
+ pi.registerProvider(name, cfg);
32
+ }
33
+ } catch (err) {
34
+ console.error("[local-models] Failed to load private providers:", err);
35
+ }
36
+ }
37
+ `;
38
+
39
+ /**
40
+ * Ensures ~/.omp/extensions/local-models.js exists so private models are ambiently registered.
41
+ */
42
+ export function ensureLocalExtension(ompDir) {
43
+ const extDir = path.join(ompDir, "extensions");
44
+ if (!fs.existsSync(extDir)) {
45
+ fs.mkdirSync(extDir, { recursive: true });
46
+ }
47
+ const extPath = path.join(extDir, "local-models.js");
48
+ if (!fs.existsSync(extPath)) {
49
+ fs.writeFileSync(extPath, LOCAL_LOADER_SCRIPT, "utf8");
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Parse OMP models.yml providers mapping.
55
+ */
56
+ export function parseYamlModels(str) {
57
+ if (!str || typeof str !== "string") return {};
58
+ const lines = str.split("\n");
59
+ const providers = {};
60
+ let curProvider = null;
61
+ let curModel = null;
62
+ let inModels = false;
63
+ let inCompat = false;
64
+
65
+ for (const rawLine of lines) {
66
+ const trimmed = rawLine.trim();
67
+ if (!trimmed || trimmed.startsWith("#")) continue;
68
+ const indent = rawLine.search(/\S/);
69
+
70
+ if (trimmed === "providers:") {
71
+ continue;
72
+ }
73
+
74
+ if (indent === 2 && trimmed.endsWith(":")) {
75
+ const pName = trimmed.slice(0, -1).trim();
76
+ curProvider = { models: [] };
77
+ providers[pName] = curProvider;
78
+ inModels = false;
79
+ inCompat = false;
80
+ continue;
81
+ }
82
+
83
+ if (curProvider && indent === 4) {
84
+ inModels = false;
85
+ inCompat = false;
86
+ if (trimmed === "models:") {
87
+ inModels = true;
88
+ continue;
89
+ }
90
+ const colonIdx = trimmed.indexOf(":");
91
+ if (colonIdx > 0) {
92
+ const key = trimmed.slice(0, colonIdx).trim();
93
+ let val = trimmed.slice(colonIdx + 1).trim();
94
+ if (val === "true") val = true;
95
+ else if (val === "false") val = false;
96
+ curProvider[key] = val;
97
+ }
98
+ continue;
99
+ }
100
+
101
+ if (curProvider && inModels) {
102
+ if (trimmed.startsWith("- ")) {
103
+ curModel = {};
104
+ curProvider.models.push(curModel);
105
+ inCompat = false;
106
+ const rest = trimmed.slice(2).trim();
107
+ if (rest) {
108
+ const colonIdx = rest.indexOf(":");
109
+ if (colonIdx > 0) {
110
+ const k = rest.slice(0, colonIdx).trim();
111
+ let v = rest.slice(colonIdx + 1).trim();
112
+ if (v === "true") v = true;
113
+ else if (v === "false") v = false;
114
+ else if (/^\d+$/.test(v)) v = parseInt(v, 10);
115
+ curModel[k] = v;
116
+ }
117
+ }
118
+ continue;
119
+ }
120
+
121
+ if (curModel && indent >= 6) {
122
+ if (trimmed === "compat:") {
123
+ inCompat = true;
124
+ curModel.compat = {};
125
+ continue;
126
+ }
127
+ if (inCompat && indent >= 8) {
128
+ const colonIdx = trimmed.indexOf(":");
129
+ if (colonIdx > 0) {
130
+ const k = trimmed.slice(0, colonIdx).trim();
131
+ let v = trimmed.slice(colonIdx + 1).trim();
132
+ if (v === "true") v = true;
133
+ else if (v === "false") v = false;
134
+ else if (/^\d+$/.test(v)) v = parseInt(v, 10);
135
+ curModel.compat[k] = v;
136
+ }
137
+ continue;
138
+ }
139
+
140
+ const colonIdx = trimmed.indexOf(":");
141
+ if (colonIdx > 0) {
142
+ const k = trimmed.slice(0, colonIdx).trim();
143
+ let v = trimmed.slice(colonIdx + 1).trim();
144
+ if (v.startsWith("[") && v.endsWith("]")) {
145
+ v = v
146
+ .slice(1, -1)
147
+ .split(",")
148
+ .map((s) => s.trim().replace(/^['"]|['"]$/g, ""));
149
+ } else if (v === "true") v = true;
150
+ else if (v === "false") v = false;
151
+ else if (/^\d+$/.test(v)) v = parseInt(v, 10);
152
+ curModel[k] = v;
153
+ }
154
+ }
155
+ }
156
+ }
157
+
158
+ return providers;
159
+ }
160
+
161
+ /**
162
+ * Format providers object back to standard YAML.
163
+ */
164
+ export function formatYamlModels(providers) {
165
+ let out = "providers:\n";
166
+ for (const [name, cfg] of Object.entries(providers || {})) {
167
+ out += ` ${name}:\n`;
168
+ if (cfg.baseUrl) out += ` baseUrl: ${cfg.baseUrl}\n`;
169
+ if (cfg.api) out += ` api: ${cfg.api}\n`;
170
+ if (cfg.apiKey) out += ` apiKey: ${cfg.apiKey}\n`;
171
+ if (cfg.authHeader !== undefined) out += ` authHeader: ${cfg.authHeader}\n`;
172
+ if (Array.isArray(cfg.models) && cfg.models.length > 0) {
173
+ out += ` models:\n`;
174
+ for (const m of cfg.models) {
175
+ out += ` - id: ${m.id}\n`;
176
+ if (m.name) out += ` name: ${m.name}\n`;
177
+ if (m.reasoning) out += ` reasoning: true\n`;
178
+ if (m.input) {
179
+ const inp = Array.isArray(m.input) ? `[${m.input.join(",")}]` : m.input;
180
+ out += ` input: ${inp}\n`;
181
+ }
182
+ if (m.contextWindow) out += ` contextWindow: ${m.contextWindow}\n`;
183
+ if (m.maxTokens) out += ` maxTokens: ${m.maxTokens}\n`;
184
+ if (m.compat && typeof m.compat === "object") {
185
+ out += ` compat:\n`;
186
+ for (const [k, v] of Object.entries(m.compat)) {
187
+ out += ` ${k}: ${v}\n`;
188
+ }
189
+ }
190
+ }
191
+ }
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /**
197
+ * Read public providers from models.yml.
198
+ */
199
+ export function readPublicProviders(agentDir) {
200
+ const filePath = path.join(agentDir, "models.yml");
201
+ if (!fs.existsSync(filePath)) {
202
+ const yamlAlt = path.join(agentDir, "models.yaml");
203
+ if (!fs.existsSync(yamlAlt)) return {};
204
+ return parseYamlModels(fs.readFileSync(yamlAlt, "utf8"));
205
+ }
206
+ return parseYamlModels(fs.readFileSync(filePath, "utf8"));
207
+ }
208
+
209
+ /**
210
+ * Write public providers to models.yml.
211
+ */
212
+ export function writePublicProviders(agentDir, providers) {
213
+ if (!fs.existsSync(agentDir)) {
214
+ fs.mkdirSync(agentDir, { recursive: true });
215
+ }
216
+ const filePath = path.join(agentDir, "models.yml");
217
+ const content = formatYamlModels(providers);
218
+ fs.writeFileSync(filePath, content, "utf8");
219
+ }
220
+
221
+ /**
222
+ * Read private providers from models.local.json.
223
+ */
224
+ export function readPrivateProviders(agentDir) {
225
+ const filePath = path.join(agentDir, "models.local.json");
226
+ if (!fs.existsSync(filePath)) return {};
227
+ try {
228
+ const json = JSON.parse(fs.readFileSync(filePath, "utf8"));
229
+ return json.providers || {};
230
+ } catch {
231
+ return {};
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Write private providers to models.local.json.
237
+ */
238
+ export function writePrivateProviders(agentDir, providers) {
239
+ if (!fs.existsSync(agentDir)) {
240
+ fs.mkdirSync(agentDir, { recursive: true });
241
+ }
242
+ const filePath = path.join(agentDir, "models.local.json");
243
+ fs.writeFileSync(filePath, JSON.stringify({ providers }, null, 2), "utf8");
244
+ }
245
+
246
+ /**
247
+ * Save a provider into either public or private store.
248
+ */
249
+ export function saveProvider({
250
+ name,
251
+ providerConfig,
252
+ isPrivate = false,
253
+ agentDir = getAgentDir(),
254
+ }) {
255
+ if (!name || typeof name !== "string") {
256
+ throw new Error("Provider name is required");
257
+ }
258
+
259
+ const cleanConfig = {
260
+ baseUrl: providerConfig.baseUrl,
261
+ api: providerConfig.api || "openai-completions",
262
+ apiKey: providerConfig.apiKey || "",
263
+ authHeader: providerConfig.authHeader !== undefined ? providerConfig.authHeader : true,
264
+ models: Array.isArray(providerConfig.models) ? providerConfig.models : [],
265
+ };
266
+
267
+ const ompDir = getOmpDir(agentDir);
268
+
269
+ if (isPrivate) {
270
+ const priv = readPrivateProviders(agentDir);
271
+ priv[name] = cleanConfig;
272
+ writePrivateProviders(agentDir, priv);
273
+ ensureLocalExtension(ompDir);
274
+
275
+ // If it existed in public, remove from public to prevent duplicate
276
+ const pub = readPublicProviders(agentDir);
277
+ if (pub[name]) {
278
+ delete pub[name];
279
+ writePublicProviders(agentDir, pub);
280
+ }
281
+ } else {
282
+ const pub = readPublicProviders(agentDir);
283
+ pub[name] = cleanConfig;
284
+ writePublicProviders(agentDir, pub);
285
+
286
+ // If it existed in private, remove from private
287
+ const priv = readPrivateProviders(agentDir);
288
+ if (priv[name]) {
289
+ delete priv[name];
290
+ writePrivateProviders(agentDir, priv);
291
+ }
292
+ }
293
+
294
+ return { name, isPrivate, providerConfig: cleanConfig };
295
+ }
296
+
297
+ /**
298
+ * Remove a provider from both stores.
299
+ */
300
+ export function removeProvider({ name, agentDir = getAgentDir() }) {
301
+ let removed = false;
302
+
303
+ const pub = readPublicProviders(agentDir);
304
+ if (pub[name]) {
305
+ delete pub[name];
306
+ writePublicProviders(agentDir, pub);
307
+ removed = true;
308
+ }
309
+
310
+ const priv = readPrivateProviders(agentDir);
311
+ if (priv[name]) {
312
+ delete priv[name];
313
+ writePrivateProviders(agentDir, priv);
314
+ removed = true;
315
+ }
316
+
317
+ return removed;
318
+ }
319
+
320
+ /**
321
+ * List all providers across both tiers.
322
+ */
323
+ export function listProviders({ agentDir = getAgentDir() } = {}) {
324
+ const pub = readPublicProviders(agentDir);
325
+ const priv = readPrivateProviders(agentDir);
326
+
327
+ const list = [];
328
+ for (const [name, cfg] of Object.entries(pub)) {
329
+ list.push({
330
+ name,
331
+ isPrivate: false,
332
+ baseUrl: cfg.baseUrl,
333
+ api: cfg.api,
334
+ apiKey: cfg.apiKey,
335
+ models: cfg.models || [],
336
+ });
337
+ }
338
+ for (const [name, cfg] of Object.entries(priv)) {
339
+ list.push({
340
+ name,
341
+ isPrivate: true,
342
+ baseUrl: cfg.baseUrl,
343
+ api: cfg.api,
344
+ apiKey: cfg.apiKey,
345
+ models: cfg.models || [],
346
+ });
347
+ }
348
+
349
+ return list;
350
+ }
351
+
352
+ /**
353
+ * Get details for a single provider.
354
+ */
355
+ export function getProvider(name, { agentDir = getAgentDir() } = {}) {
356
+ const priv = readPrivateProviders(agentDir);
357
+ if (priv[name]) {
358
+ return { name, isPrivate: true, ...priv[name] };
359
+ }
360
+ const pub = readPublicProviders(agentDir);
361
+ if (pub[name]) {
362
+ return { name, isPrivate: false, ...pub[name] };
363
+ }
364
+ return null;
365
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Role Assignment & Model Binding Manager
3
+ *
4
+ * Manages modelRoles mappings (default, smol, plan, slow, web) in ~/.omp/agent/config.yml
5
+ * with validation against public and private provider stores.
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { getAgentDir, listProviders } from "./provider-store.js";
11
+
12
+ export const VALID_ROLES = ["default", "smol", "plan", "slow", "web"];
13
+
14
+ /**
15
+ * Read current modelRoles from config.yml.
16
+ */
17
+ export function getRoles(agentDir = getAgentDir()) {
18
+ const configFile = path.join(agentDir, "config.yml");
19
+ if (!fs.existsSync(configFile)) {
20
+ const alt = path.join(agentDir, "config.yaml");
21
+ if (!fs.existsSync(alt)) return {};
22
+ return parseRolesFromYaml(fs.readFileSync(alt, "utf8"));
23
+ }
24
+ return parseRolesFromYaml(fs.readFileSync(configFile, "utf8"));
25
+ }
26
+
27
+ function parseRolesFromYaml(yamlStr) {
28
+ const lines = yamlStr.split("\n");
29
+ const roles = {};
30
+ let inRoles = false;
31
+
32
+ for (const line of lines) {
33
+ const trimmed = line.trim();
34
+ if (!trimmed || trimmed.startsWith("#")) continue;
35
+
36
+ if (trimmed === "modelRoles:") {
37
+ inRoles = true;
38
+ continue;
39
+ }
40
+
41
+ if (inRoles) {
42
+ if (line.length > 0 && !line.startsWith(" ") && !line.startsWith("\t")) {
43
+ break; // Out of modelRoles section
44
+ }
45
+ const match = trimmed.match(/^([a-zA-Z0-9_-]+):\s*(.*)$/);
46
+ if (match) {
47
+ roles[match[1]] = match[2].trim().replace(/^['"]|['"]$/g, "");
48
+ }
49
+ }
50
+ }
51
+
52
+ return roles;
53
+ }
54
+
55
+ /**
56
+ * Surgically update a role in config.yml while preserving all other comments and structure.
57
+ */
58
+ export function updateRoleInYaml(yamlStr, role, modelRef) {
59
+ const lines = yamlStr.split("\n");
60
+ let inRoles = false;
61
+ let foundRole = false;
62
+ const newLines = [];
63
+
64
+ for (let i = 0; i < lines.length; i++) {
65
+ const line = lines[i];
66
+ const trimmed = line.trim();
67
+
68
+ if (trimmed === "modelRoles:") {
69
+ inRoles = true;
70
+ newLines.push(line);
71
+ continue;
72
+ }
73
+
74
+ if (inRoles) {
75
+ if (line.length > 0 && !line.startsWith(" ") && !line.startsWith("\t")) {
76
+ if (!foundRole) {
77
+ newLines.push(` ${role}: ${modelRef}`);
78
+ foundRole = true;
79
+ }
80
+ inRoles = false;
81
+ newLines.push(line);
82
+ continue;
83
+ }
84
+
85
+ const match = line.match(/^(\s*)([a-zA-Z0-9_-]+):(.*)$/);
86
+ if (match) {
87
+ const currentRole = match[2];
88
+ if (currentRole === role) {
89
+ newLines.push(`${match[1]}${role}: ${modelRef}`);
90
+ foundRole = true;
91
+ continue;
92
+ }
93
+ }
94
+ }
95
+
96
+ newLines.push(line);
97
+ }
98
+
99
+ if (inRoles && !foundRole) {
100
+ newLines.push(` ${role}: ${modelRef}`);
101
+ foundRole = true;
102
+ }
103
+
104
+ if (!foundRole) {
105
+ return `modelRoles:\n ${role}: ${modelRef}\n` + yamlStr;
106
+ }
107
+
108
+ return newLines.join("\n");
109
+ }
110
+
111
+ /**
112
+ * Set a model role in config.yml.
113
+ */
114
+ export function setRole(roleName, modelRef, { agentDir = getAgentDir(), validate = true } = {}) {
115
+ const role = (roleName || "").trim().toLowerCase();
116
+ if (!VALID_ROLES.includes(role)) {
117
+ throw new Error(`Invalid role '${roleName}'. Must be one of: ${VALID_ROLES.join(", ")}`);
118
+ }
119
+
120
+ const targetRef = (modelRef || "").trim();
121
+ if (!targetRef) {
122
+ throw new Error("Model reference cannot be empty (e.g. 'provider/model-id')");
123
+ }
124
+
125
+ if (validate && targetRef.includes("/")) {
126
+ const [pName, mId] = targetRef.split("/");
127
+ const providers = listProviders({ agentDir });
128
+ const match = providers.find((p) => p.name === pName);
129
+ if (!match) {
130
+ throw new Error(`Provider '${pName}' is not configured in public or private stores.`);
131
+ }
132
+ const hasModel = match.models.some((m) => m.id === mId);
133
+ if (!hasModel && match.models.length > 0) {
134
+ throw new Error(
135
+ `Model '${mId}' not found under provider '${pName}'. Available: ${match.models.map((m) => m.id).join(", ")}`
136
+ );
137
+ }
138
+ }
139
+
140
+ const configFile = path.join(agentDir, "config.yml");
141
+ let existingContent = "";
142
+ if (fs.existsSync(configFile)) {
143
+ existingContent = fs.readFileSync(configFile, "utf8");
144
+ }
145
+
146
+ const updatedContent = updateRoleInYaml(existingContent, role, targetRef);
147
+ fs.writeFileSync(configFile, updatedContent, "utf8");
148
+
149
+ return { role, modelRef: targetRef, updated: true };
150
+ }