offrouter-cli 0.0.0

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.
Files changed (90) hide show
  1. package/dist/catalog-cache.d.ts +60 -0
  2. package/dist/catalog-cache.d.ts.map +1 -0
  3. package/dist/catalog-cache.js +113 -0
  4. package/dist/catalog-cache.js.map +1 -0
  5. package/dist/commands/config-error.d.ts +8 -0
  6. package/dist/commands/config-error.d.ts.map +1 -0
  7. package/dist/commands/config-error.js +22 -0
  8. package/dist/commands/config-error.js.map +1 -0
  9. package/dist/commands/detection.d.ts +55 -0
  10. package/dist/commands/detection.d.ts.map +1 -0
  11. package/dist/commands/detection.js +131 -0
  12. package/dist/commands/detection.js.map +1 -0
  13. package/dist/commands/doctor.d.ts +6 -0
  14. package/dist/commands/doctor.d.ts.map +1 -0
  15. package/dist/commands/doctor.js +369 -0
  16. package/dist/commands/doctor.js.map +1 -0
  17. package/dist/commands/hooks.d.ts +4 -0
  18. package/dist/commands/hooks.d.ts.map +1 -0
  19. package/dist/commands/hooks.js +86 -0
  20. package/dist/commands/hooks.js.map +1 -0
  21. package/dist/commands/init.d.ts +12 -0
  22. package/dist/commands/init.d.ts.map +1 -0
  23. package/dist/commands/init.js +38 -0
  24. package/dist/commands/init.js.map +1 -0
  25. package/dist/commands/install.d.ts +8 -0
  26. package/dist/commands/install.d.ts.map +1 -0
  27. package/dist/commands/install.js +267 -0
  28. package/dist/commands/install.js.map +1 -0
  29. package/dist/commands/login.d.ts +4 -0
  30. package/dist/commands/login.d.ts.map +1 -0
  31. package/dist/commands/login.js +25 -0
  32. package/dist/commands/login.js.map +1 -0
  33. package/dist/commands/mcp.d.ts +4 -0
  34. package/dist/commands/mcp.d.ts.map +1 -0
  35. package/dist/commands/mcp.js +27 -0
  36. package/dist/commands/mcp.js.map +1 -0
  37. package/dist/commands/models.d.ts +15 -0
  38. package/dist/commands/models.d.ts.map +1 -0
  39. package/dist/commands/models.js +124 -0
  40. package/dist/commands/models.js.map +1 -0
  41. package/dist/commands/output.d.ts +6 -0
  42. package/dist/commands/output.d.ts.map +1 -0
  43. package/dist/commands/output.js +7 -0
  44. package/dist/commands/output.js.map +1 -0
  45. package/dist/commands/profiles.d.ts +4 -0
  46. package/dist/commands/profiles.d.ts.map +1 -0
  47. package/dist/commands/profiles.js +46 -0
  48. package/dist/commands/profiles.js.map +1 -0
  49. package/dist/commands/proxy.d.ts +10 -0
  50. package/dist/commands/proxy.d.ts.map +1 -0
  51. package/dist/commands/proxy.js +53 -0
  52. package/dist/commands/proxy.js.map +1 -0
  53. package/dist/commands/route.d.ts +4 -0
  54. package/dist/commands/route.d.ts.map +1 -0
  55. package/dist/commands/route.js +123 -0
  56. package/dist/commands/route.js.map +1 -0
  57. package/dist/commands/status.d.ts +4 -0
  58. package/dist/commands/status.d.ts.map +1 -0
  59. package/dist/commands/status.js +86 -0
  60. package/dist/commands/status.js.map +1 -0
  61. package/dist/commands/update.d.ts +9 -0
  62. package/dist/commands/update.d.ts.map +1 -0
  63. package/dist/commands/update.js +44 -0
  64. package/dist/commands/update.js.map +1 -0
  65. package/dist/index.d.ts +25 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +137 -0
  68. package/dist/index.js.map +1 -0
  69. package/package.json +24 -0
  70. package/src/catalog-cache.test.ts +258 -0
  71. package/src/catalog-cache.ts +169 -0
  72. package/src/catalog-sample.json +30 -0
  73. package/src/cli.test.ts +1577 -0
  74. package/src/commands/config-error.ts +31 -0
  75. package/src/commands/detection.ts +209 -0
  76. package/src/commands/doctor.ts +503 -0
  77. package/src/commands/hooks.ts +125 -0
  78. package/src/commands/init.ts +59 -0
  79. package/src/commands/install.ts +438 -0
  80. package/src/commands/login.ts +33 -0
  81. package/src/commands/mcp.ts +35 -0
  82. package/src/commands/models.ts +168 -0
  83. package/src/commands/output.ts +11 -0
  84. package/src/commands/profiles.ts +58 -0
  85. package/src/commands/proxy.ts +87 -0
  86. package/src/commands/route.ts +160 -0
  87. package/src/commands/status.ts +111 -0
  88. package/src/commands/update.ts +62 -0
  89. package/src/index.ts +174 -0
  90. package/tsconfig.json +17 -0
@@ -0,0 +1,438 @@
1
+ /**
2
+ * CLI install / uninstall for harness plugins (Claude / Codex V1).
3
+ */
4
+ import type { Command } from "commander";
5
+ import { loadConfig } from "offrouter-core";
6
+ import {
7
+ formatInstallDiffText as formatClaudeDiff,
8
+ installClaudeProfile,
9
+ listAllowlistedPersonalClaudeProfiles,
10
+ rollbackClaudeProfile,
11
+ type ClaudeInstallResult,
12
+ type ClaudeRollbackResult,
13
+ } from "offrouter-adapter-claude";
14
+ import {
15
+ formatInstallDiffText as formatCodexDiff,
16
+ installCodexProfile,
17
+ listAllowlistedPersonalCodexProfiles,
18
+ rollbackCodexProfile,
19
+ type CodexInstallResult,
20
+ type CodexRollbackResult,
21
+ } from "offrouter-adapter-codex";
22
+ import {
23
+ formatInstallDiffText as formatGeminiDiff,
24
+ installGeminiProfile,
25
+ listAllowlistedPersonalGeminiProfiles,
26
+ rollbackGeminiProfile,
27
+ type GeminiInstallResult,
28
+ type GeminiRollbackResult,
29
+ } from "offrouter-adapter-gemini";
30
+ import {
31
+ formatInstallDiffText as formatGrokDiff,
32
+ installGrokProfile,
33
+ listAllowlistedPersonalGrokProfiles,
34
+ rollbackGrokProfile,
35
+ type GrokInstallResult,
36
+ type GrokRollbackResult,
37
+ } from "offrouter-adapter-grok";
38
+ import type { CommandContext } from "./init.js";
39
+ import { writeJson, writeText } from "./output.js";
40
+ import { honestyForHarness } from "./detection.js";
41
+ import { formatConfigError } from "./config-error.js";
42
+
43
+ type HarnessKind = "claude" | "codex" | "gemini" | "grok";
44
+
45
+ type InstallResultUnion =
46
+ | ClaudeInstallResult
47
+ | CodexInstallResult
48
+ | GeminiInstallResult
49
+ | GrokInstallResult;
50
+ type RollbackResultUnion =
51
+ | ClaudeRollbackResult
52
+ | CodexRollbackResult
53
+ | GeminiRollbackResult
54
+ | GrokRollbackResult;
55
+
56
+ function assertHarness(harness: string): HarnessKind {
57
+ if (
58
+ harness !== "claude" &&
59
+ harness !== "codex" &&
60
+ harness !== "gemini" &&
61
+ harness !== "grok"
62
+ ) {
63
+ throw new Error(
64
+ `Unsupported harness "${harness}". V1 install currently supports: claude, codex, gemini, grok`,
65
+ );
66
+ }
67
+ return harness;
68
+ }
69
+
70
+ function harnessLabel(kind: HarnessKind): string {
71
+ if (kind === "codex") return "Codex";
72
+ if (kind === "gemini") return "Gemini";
73
+ if (kind === "grok") return "Grok";
74
+ return "Claude";
75
+ }
76
+
77
+ function allowlistedPersonalProfiles(
78
+ kind: HarnessKind,
79
+ config: Parameters<typeof listAllowlistedPersonalClaudeProfiles>[0],
80
+ ): string[] {
81
+ if (kind === "codex") return listAllowlistedPersonalCodexProfiles(config);
82
+ if (kind === "gemini") return listAllowlistedPersonalGeminiProfiles(config);
83
+ if (kind === "grok") return listAllowlistedPersonalGrokProfiles(config);
84
+ return listAllowlistedPersonalClaudeProfiles(config);
85
+ }
86
+
87
+ async function installOne(
88
+ kind: HarnessKind,
89
+ args: {
90
+ profile: string;
91
+ config: Parameters<typeof installClaudeProfile>[0]["config"];
92
+ env: NodeJS.ProcessEnv;
93
+ dryRun: boolean;
94
+ },
95
+ ): Promise<InstallResultUnion> {
96
+ if (kind === "codex") {
97
+ return installCodexProfile(args);
98
+ }
99
+ if (kind === "gemini") {
100
+ return installGeminiProfile(args);
101
+ }
102
+ if (kind === "grok") {
103
+ return installGrokProfile(args);
104
+ }
105
+ return installClaudeProfile(args);
106
+ }
107
+
108
+ async function rollbackOne(
109
+ kind: HarnessKind,
110
+ args: {
111
+ profile: string;
112
+ env: NodeJS.ProcessEnv;
113
+ dryRun: boolean;
114
+ },
115
+ ): Promise<RollbackResultUnion> {
116
+ if (kind === "codex") {
117
+ return rollbackCodexProfile(args);
118
+ }
119
+ if (kind === "gemini") {
120
+ return rollbackGeminiProfile(args);
121
+ }
122
+ if (kind === "grok") {
123
+ return rollbackGrokProfile(args);
124
+ }
125
+ return rollbackClaudeProfile(args);
126
+ }
127
+
128
+ function formatDiff(
129
+ kind: HarnessKind,
130
+ results: InstallResultUnion[],
131
+ headline?: string,
132
+ ): string {
133
+ if (kind === "codex") {
134
+ return formatCodexDiff(
135
+ results as unknown as CodexInstallResult[],
136
+ headline,
137
+ );
138
+ }
139
+ if (kind === "gemini") {
140
+ return formatGeminiDiff(
141
+ results as unknown as GeminiInstallResult[],
142
+ headline,
143
+ );
144
+ }
145
+ if (kind === "grok") {
146
+ return formatGrokDiff(results as unknown as GrokInstallResult[], headline);
147
+ }
148
+ return formatClaudeDiff(
149
+ results as unknown as ClaudeInstallResult[],
150
+ headline,
151
+ );
152
+ }
153
+
154
+ function resultExitCode(results: Array<{ ok: boolean }>): number {
155
+ return results.every((r) => r.ok) ? 0 : 1;
156
+ }
157
+
158
+ export function registerInstallCommand(
159
+ program: Command,
160
+ ctx: () => CommandContext,
161
+ ): void {
162
+ const install = program
163
+ .command("install")
164
+ .description(
165
+ "Install OffRouter into an allowlisted personal harness profile",
166
+ )
167
+ .option(
168
+ "--all-personal",
169
+ "Install into every allowlisted personal harness profile (Claude or Codex)",
170
+ false,
171
+ )
172
+ .option("--dry-run", "Show planned file changes without writing", false)
173
+ .option("--json", "Emit JSON", false)
174
+ .argument("[harness]", "Harness kind (V1: claude, codex)", "claude")
175
+ .option(
176
+ "--profile <profile>",
177
+ "Target profile id (e.g. claude-personal, codex-personal). Required unless --all-personal.",
178
+ )
179
+ .action(
180
+ async (
181
+ harness: string,
182
+ opts: {
183
+ profile?: string;
184
+ allPersonal?: boolean;
185
+ dryRun?: boolean;
186
+ json?: boolean;
187
+ },
188
+ ) => {
189
+ const { env, cwd, stdout, stderr } = ctx();
190
+ let kind: HarnessKind = "claude";
191
+ try {
192
+ kind = assertHarness(harness);
193
+ const config = await loadConfig({ env, workspaceDir: cwd });
194
+ const dryRun = Boolean(opts.dryRun);
195
+ const allPersonal = Boolean(opts.allPersonal);
196
+ const profile = opts.profile?.trim();
197
+
198
+ if (allPersonal && profile) {
199
+ throw new Error(
200
+ "Use either --profile <id> or --all-personal, not both.",
201
+ );
202
+ }
203
+
204
+ if (!allPersonal && !profile) {
205
+ throw new Error(
206
+ "Provide --profile <id> or --all-personal. Example: offrouter install claude --profile claude-personal --dry-run",
207
+ );
208
+ }
209
+
210
+ const targets = allPersonal
211
+ ? allowlistedPersonalProfiles(kind, config)
212
+ : [profile!];
213
+
214
+ const honesty = honestyForHarness(kind);
215
+ const label = harnessLabel(kind);
216
+
217
+ if (targets.length === 0) {
218
+ const empty: InstallResultUnion[] = [];
219
+ if (opts.json) {
220
+ writeJson(stdout, {
221
+ honesty,
222
+ dryRun,
223
+ harness: kind,
224
+ results: empty,
225
+ message: `No allowlisted personal ${label} profiles found for install.`,
226
+ });
227
+ return;
228
+ }
229
+ writeText(stdout, honesty);
230
+ writeText(
231
+ stdout,
232
+ `No allowlisted personal ${label} profiles found for install.`,
233
+ );
234
+ return;
235
+ }
236
+
237
+ const results: InstallResultUnion[] = [];
238
+ for (const target of targets) {
239
+ results.push(
240
+ await installOne(kind, { profile: target, config, env, dryRun }),
241
+ );
242
+ }
243
+
244
+ if (opts.json) {
245
+ writeJson(stdout, {
246
+ honesty,
247
+ dryRun,
248
+ harness: kind,
249
+ results,
250
+ });
251
+ } else {
252
+ writeText(stdout, honesty);
253
+ const headline = allPersonal
254
+ ? `Install matrix (allowlisted personal ${label} profiles):`
255
+ : undefined;
256
+ writeText(stdout, formatDiff(kind, results, headline).trimEnd());
257
+ }
258
+
259
+ if (resultExitCode(results) !== 0) {
260
+ const failed = results.filter((r) => !r.ok);
261
+ const msg = failed.map((r) => r.message).join("; ");
262
+ // Commander exitOverride path
263
+ const err = new Error(msg) as Error & { exitCode?: number };
264
+ err.exitCode = 1;
265
+ throw err;
266
+ }
267
+ } catch (err) {
268
+ if (
269
+ err &&
270
+ typeof err === "object" &&
271
+ "exitCode" in err &&
272
+ typeof (err as { exitCode: unknown }).exitCode === "number"
273
+ ) {
274
+ throw err;
275
+ }
276
+ const formatted = formatConfigError(err);
277
+ const honesty = honestyForHarness(kind);
278
+ if (opts.json) {
279
+ writeJson(stdout, {
280
+ honesty,
281
+ error: formatted,
282
+ });
283
+ const e = new Error(formatted.message) as Error & {
284
+ exitCode?: number;
285
+ };
286
+ e.exitCode = 1;
287
+ throw e;
288
+ }
289
+ writeText(stderr, formatted.message);
290
+ const e = new Error(formatted.message) as Error & {
291
+ exitCode?: number;
292
+ };
293
+ e.exitCode = 1;
294
+ throw e;
295
+ }
296
+ },
297
+ );
298
+
299
+ // Silence unused local if tree-shaking complains; keep reference stable.
300
+ void install;
301
+ }
302
+
303
+ export function registerUninstallCommand(
304
+ program: Command,
305
+ ctx: () => CommandContext,
306
+ ): void {
307
+ program
308
+ .command("uninstall")
309
+ .description("Uninstall / roll back OffRouter from a harness profile")
310
+ .argument("[harness]", "Harness kind (V1: claude, codex)", "claude")
311
+ .option(
312
+ "--profile <profile>",
313
+ "Target profile id (e.g. claude-personal, codex-personal)",
314
+ )
315
+ .option(
316
+ "--all-personal",
317
+ "Uninstall from every allowlisted personal harness profile that has install state",
318
+ false,
319
+ )
320
+ .option("--dry-run", "Show planned rollback without writing", false)
321
+ .option("--json", "Emit JSON", false)
322
+ .action(
323
+ async (
324
+ harness: string,
325
+ opts: {
326
+ profile?: string;
327
+ allPersonal?: boolean;
328
+ dryRun?: boolean;
329
+ json?: boolean;
330
+ },
331
+ ) => {
332
+ const { env, cwd, stdout, stderr } = ctx();
333
+ let kind: HarnessKind = "claude";
334
+ try {
335
+ kind = assertHarness(harness);
336
+ const config = await loadConfig({ env, workspaceDir: cwd });
337
+ const dryRun = Boolean(opts.dryRun);
338
+ const allPersonal = Boolean(opts.allPersonal);
339
+ const profile = opts.profile?.trim();
340
+
341
+ if (allPersonal && profile) {
342
+ throw new Error(
343
+ "Use either --profile <id> or --all-personal, not both.",
344
+ );
345
+ }
346
+
347
+ if (!allPersonal && !profile) {
348
+ throw new Error(
349
+ "Provide --profile <id> or --all-personal. Example: offrouter uninstall claude --profile claude-personal",
350
+ );
351
+ }
352
+
353
+ const targets = allPersonal
354
+ ? allowlistedPersonalProfiles(kind, config)
355
+ : [profile!];
356
+
357
+ const results: RollbackResultUnion[] = [];
358
+ for (const target of targets) {
359
+ results.push(
360
+ await rollbackOne(kind, { profile: target, env, dryRun }),
361
+ );
362
+ }
363
+
364
+ // Map rollback results into install-result-like text blocks.
365
+ const asInstallish: InstallResultUnion[] = results.map((r) => ({
366
+ ok: r.ok,
367
+ dryRun: r.dryRun,
368
+ profile: r.profile,
369
+ profileDir: r.profileDir,
370
+ changes: r.changes,
371
+ message: r.message,
372
+ errorCode: r.ok
373
+ ? undefined
374
+ : r.errorCode === "no_install_state"
375
+ ? "install_error"
376
+ : "install_error",
377
+ }));
378
+
379
+ const honesty = honestyForHarness(kind);
380
+
381
+ if (opts.json) {
382
+ writeJson(stdout, {
383
+ honesty,
384
+ dryRun,
385
+ harness: kind,
386
+ results,
387
+ });
388
+ } else {
389
+ writeText(stdout, honesty);
390
+ writeText(
391
+ stdout,
392
+ formatDiff(kind, asInstallish, "Uninstall / rollback:").trimEnd(),
393
+ );
394
+ }
395
+
396
+ // Missing state on --all-personal is soft; invalid state/errors fail.
397
+ const hardFailures = results.filter(
398
+ (r) =>
399
+ !r.ok && (!allPersonal || r.errorCode !== "no_install_state"),
400
+ );
401
+ if (hardFailures.length > 0) {
402
+ const msg = hardFailures.map((r) => r.message).join("; ");
403
+ const err = new Error(msg) as Error & { exitCode?: number };
404
+ err.exitCode = 1;
405
+ throw err;
406
+ }
407
+ } catch (err) {
408
+ if (
409
+ err &&
410
+ typeof err === "object" &&
411
+ "exitCode" in err &&
412
+ typeof (err as { exitCode: unknown }).exitCode === "number"
413
+ ) {
414
+ throw err;
415
+ }
416
+ const formatted = formatConfigError(err);
417
+ const honesty = honestyForHarness(kind);
418
+ if (opts.json) {
419
+ writeJson(stdout, {
420
+ honesty,
421
+ error: formatted,
422
+ });
423
+ const e = new Error(formatted.message) as Error & {
424
+ exitCode?: number;
425
+ };
426
+ e.exitCode = 1;
427
+ throw e;
428
+ }
429
+ writeText(stderr, formatted.message);
430
+ const e = new Error(formatted.message) as Error & {
431
+ exitCode?: number;
432
+ };
433
+ e.exitCode = 1;
434
+ throw e;
435
+ }
436
+ },
437
+ );
438
+ }
@@ -0,0 +1,33 @@
1
+ import type { Command } from "commander";
2
+ import { V1_HONESTY_LINE } from "./detection.js";
3
+ import { writeJson, writeText } from "./output.js";
4
+ import type { CommandContext } from "./init.js";
5
+
6
+ export function registerLoginCommand(
7
+ program: Command,
8
+ ctx: () => CommandContext,
9
+ ): void {
10
+ program
11
+ .command("login")
12
+ .description(
13
+ "Guide official provider login / token-helper flows (no credential scraping)",
14
+ )
15
+ .argument("[provider]", "Provider id (optional)")
16
+ .option("--json", "Emit JSON", false)
17
+ .action(async (provider: string | undefined, opts: { json?: boolean }) => {
18
+ const { stdout } = ctx();
19
+ const payload = {
20
+ honesty: V1_HONESTY_LINE,
21
+ provider: provider ?? null,
22
+ status: "not_implemented",
23
+ message:
24
+ "Login uses official provider login, token-helper, OAuth, or user-provided API key surfaces only. Provider adapters land in a later milestone.",
25
+ };
26
+ if (opts.json) {
27
+ writeJson(stdout, payload);
28
+ return;
29
+ }
30
+ writeText(stdout, V1_HONESTY_LINE);
31
+ writeText(stdout, payload.message);
32
+ });
33
+ }
@@ -0,0 +1,35 @@
1
+ import type { Command } from "commander";
2
+ import { runMcpCli } from "offrouter-mcp";
3
+ import type { CommandContext } from "./init.js";
4
+
5
+ export function registerMcpCommand(
6
+ program: Command,
7
+ ctx: () => CommandContext,
8
+ ): void {
9
+ const mcp = program
10
+ .command("mcp")
11
+ .description("OffRouter MCP stdio server bridges");
12
+
13
+ mcp
14
+ .command("serve")
15
+ .description(
16
+ "Start the OffRouter MCP stdio server (route/delegate/status tools)",
17
+ )
18
+ .action(async (_opts: unknown, command: Command) => {
19
+ const { env, cwd, stdout, stderr } = ctx();
20
+ // Forward only unknown/passthrough args after `serve`; Commander already
21
+ // handled --help before invoking this action.
22
+ const forwarded = command.args ?? [];
23
+ const code = await runMcpCli(forwarded, {
24
+ env,
25
+ cwd,
26
+ stdout,
27
+ stderr,
28
+ });
29
+ if (code !== 0) {
30
+ const err = new Error(`MCP server exited with code ${code}`);
31
+ (err as { exitCode?: number }).exitCode = code;
32
+ throw err;
33
+ }
34
+ });
35
+ }
@@ -0,0 +1,168 @@
1
+ import type { Command } from "commander";
2
+ import { loadConfig, BUILTIN_PROVIDERS } from "offrouter-core";
3
+ import { formatConfigError, type CliConfigError } from "./config-error.js";
4
+ import { writeJson, writeText } from "./output.js";
5
+ import type { CommandContext } from "./init.js";
6
+ import { readCatalogCache, resolveCacheDir } from "../catalog-cache.js";
7
+ import type { CachedModelFamily } from "../catalog-cache.js";
8
+
9
+ /**
10
+ * A single model entry in the merged output.
11
+ * source: "builtin" from core package, "cached" from remote catalog, "config" from profile config.
12
+ */
13
+ export interface ModelEntry {
14
+ providerId: string;
15
+ modelId: string;
16
+ displayName?: string;
17
+ family?: string;
18
+ source: "builtin" | "cached" | "config";
19
+ }
20
+
21
+ function builtinToEntries(): ModelEntry[] {
22
+ const entries: ModelEntry[] = [];
23
+ for (const provider of BUILTIN_PROVIDERS) {
24
+ for (const model of provider.knownModels) {
25
+ entries.push({
26
+ providerId: provider.providerId,
27
+ modelId: model.modelId,
28
+ displayName: model.displayName,
29
+ family: model.family,
30
+ source: "builtin",
31
+ });
32
+ }
33
+ }
34
+ return entries;
35
+ }
36
+
37
+ function cachedToEntries(cached: { families: CachedModelFamily[] }): ModelEntry[] {
38
+ return cached.families.map((f) => ({
39
+ providerId: f.providerId,
40
+ modelId: f.modelId,
41
+ displayName: f.displayName,
42
+ family: f.family,
43
+ source: "cached" as const,
44
+ }));
45
+ }
46
+
47
+ /**
48
+ * Merge builtin and cached model entries.
49
+ * Cached models with the same (providerId, modelId) override builtin entries.
50
+ * Config provider entries are appended separately.
51
+ */
52
+ function mergeModels(
53
+ builtin: ModelEntry[],
54
+ cached: ModelEntry[],
55
+ config: ModelEntry[],
56
+ ): ModelEntry[] {
57
+ // Build a set of (providerId,modelId) from cached entries that override builtin
58
+ const cachedKeys = new Set<string>();
59
+ for (const entry of cached) {
60
+ cachedKeys.add(`${entry.providerId}:${entry.modelId}`);
61
+ }
62
+
63
+ // Filter builtin entries that are not overridden by cached
64
+ const merged = builtin.filter(
65
+ (b) => !cachedKeys.has(`${b.providerId}:${b.modelId}`),
66
+ );
67
+
68
+ // Add all cached entries
69
+ merged.push(...cached);
70
+
71
+ // Add config entries (providers from config.toml)
72
+ // Config entries with same (providerId, modelId) override both builtin and cached
73
+ const mergedKeys = new Set<string>();
74
+ for (const entry of merged) {
75
+ mergedKeys.add(`${entry.providerId}:${entry.modelId}`);
76
+ }
77
+ for (const entry of config) {
78
+ if (!mergedKeys.has(`${entry.providerId}:${entry.modelId}`)) {
79
+ merged.push(entry);
80
+ }
81
+ }
82
+
83
+ return merged;
84
+ }
85
+
86
+ export function registerModelsCommand(
87
+ program: Command,
88
+ ctx: () => CommandContext,
89
+ ): void {
90
+ program
91
+ .command("models")
92
+ .description(
93
+ "List known models from builtin catalog, cached remote catalog, and config",
94
+ )
95
+ .option("--json", "Emit JSON", false)
96
+ .action(async (opts: { json?: boolean }) => {
97
+ const { env, cwd, stdout } = ctx();
98
+
99
+ // 1. Builtin models from offrouter-core
100
+ const builtinEntries = builtinToEntries();
101
+
102
+ // 2. Cached models from remote catalog (if available)
103
+ let cachedEntries: ModelEntry[] = [];
104
+ const cacheDir = resolveCacheDir(env);
105
+ const cachedData = readCatalogCache(cacheDir);
106
+ if (cachedData) {
107
+ cachedEntries = cachedToEntries(cachedData);
108
+ }
109
+
110
+ // 3. Config providers
111
+ let configEntries: ModelEntry[] = [];
112
+ let configError: CliConfigError | null = null;
113
+ try {
114
+ const config = await loadConfig({ env, workspaceDir: cwd });
115
+ configEntries = Object.keys(config.providers)
116
+ .sort()
117
+ .map((providerId) => ({
118
+ providerId,
119
+ modelId: "*",
120
+ source: "config" as const,
121
+ }));
122
+ } catch (err) {
123
+ configError = formatConfigError(err);
124
+ }
125
+
126
+ // Merge: cached overrides builtin (same providerId+modelId), config appended
127
+ const models = mergeModels(builtinEntries, cachedEntries, configEntries);
128
+
129
+ if (opts.json) {
130
+ writeJson(stdout, {
131
+ models,
132
+ builtinCount: builtinEntries.length,
133
+ cachedCount: cachedEntries.length,
134
+ configCount: configEntries.length,
135
+ configError,
136
+ });
137
+ return;
138
+ }
139
+ if (configError) {
140
+ writeText(stdout, `Config error: ${configError.message}`);
141
+ return;
142
+ }
143
+ if (models.length === 0) {
144
+ writeText(
145
+ stdout,
146
+ "No models available.",
147
+ );
148
+ return;
149
+ }
150
+ // Group by source for display
151
+ const builtinModels = models.filter((m) => m.source === "builtin");
152
+ const cachedModels = models.filter((m) => m.source === "cached");
153
+ const configProviderIds = models.filter((m) => m.source === "config");
154
+
155
+ writeText(stdout, `Models (${models.length} total):`);
156
+ writeText(stdout, ` Built-in: ${builtinModels.length} models`);
157
+ writeText(stdout, ` Cached: ${cachedModels.length} models`);
158
+ writeText(stdout, ` Config providers: ${configProviderIds.length}`);
159
+ writeText(stdout, "");
160
+ for (const m of models) {
161
+ const name = m.displayName ? `${m.displayName} (${m.modelId})` : m.modelId;
162
+ writeText(
163
+ stdout,
164
+ ` ${m.providerId}/${name} (${m.source})`,
165
+ );
166
+ }
167
+ });
168
+ }
@@ -0,0 +1,11 @@
1
+ export interface IoStreams {
2
+ write(chunk: string): boolean | void;
3
+ }
4
+
5
+ export function writeJson(stream: IoStreams, value: unknown): void {
6
+ stream.write(`${JSON.stringify(value, null, 2)}\n`);
7
+ }
8
+
9
+ export function writeText(stream: IoStreams, text: string): void {
10
+ stream.write(text.endsWith("\n") ? text : `${text}\n`);
11
+ }