File size: 3,796 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import { DEFAULT_DISPLAY_BASE_URL } from "@/shared/hooks";

export interface CustomCliAliasMapping {
  alias: string;
  model: string;
}

export interface CustomCliConfigInput {
  cliName: string;
  baseUrl: string;
  apiKey: string;
  defaultModel?: string;
  aliasMappings?: CustomCliAliasMapping[];
}

export function normalizeOpenAiBaseUrl(baseUrl: string): string {
  const trimmed = (baseUrl || DEFAULT_DISPLAY_BASE_URL).trim().replace(/\/+$/, "");
  return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
}

export function slugifyCliCommand(cliName: string): string {
  const normalized = cliName
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
  return normalized || "my-cli";
}

export function buildAliasEnvVar(alias: string): string | null {
  const normalized = alias
    .trim()
    .replace(/[^a-zA-Z0-9]+/g, "_")
    .replace(/^_+|_+$/g, "")
    .toUpperCase();

  if (!normalized) return null;
  return `OMNIROUTE_MODEL_${normalized}`;
}

function getValidMappings(aliasMappings: CustomCliAliasMapping[] = []): CustomCliAliasMapping[] {
  return aliasMappings.filter(
    (mapping) => mapping.alias.trim().length > 0 && mapping.model.trim().length > 0
  );
}

export function buildCustomCliEnvScript({

  cliName,

  baseUrl,

  apiKey,

  defaultModel = "",

  aliasMappings = [],

}: CustomCliConfigInput): string {
  const normalizedBaseUrl = normalizeOpenAiBaseUrl(baseUrl);
  const resolvedName = cliName.trim() || "Custom CLI";
  const resolvedCommand = slugifyCliCommand(resolvedName);
  const resolvedDefaultModel = defaultModel.trim();
  const mappings = getValidMappings(aliasMappings);

  const lines = [
    `# ${resolvedName} -> OmniRoute (OpenAI-compatible)`,
    `export OPENAI_BASE_URL="${normalizedBaseUrl}"`,
    `export OPENAI_API_KEY="${apiKey}"`,
  ];

  if (resolvedDefaultModel) {
    lines.push(`export OPENAI_MODEL="${resolvedDefaultModel}"`);
  }

  if (mappings.length > 0) {
    lines.push("", "# Optional alias mappings for wrapper scripts");
    mappings.forEach((mapping) => {
      const envVar = buildAliasEnvVar(mapping.alias);
      if (!envVar) return;
      lines.push(`export ${envVar}="${mapping.model.trim()}"`);
    });
  }

  lines.push("", "# Raw chat completions endpoint", `# ${normalizedBaseUrl}/chat/completions`, "");

  const exampleCommand = [
    resolvedCommand,
    '--base-url "$OPENAI_BASE_URL"',
    '--api-key "$OPENAI_API_KEY"',
    resolvedDefaultModel ? '--model "$OPENAI_MODEL"' : "",
  ]
    .filter(Boolean)
    .join(" ");

  lines.push("# Example invocation", exampleCommand);

  const firstAliasEnv = buildAliasEnvVar(mappings[0]?.alias ?? "");
  if (firstAliasEnv) {
    lines.push(`# Alias example: ${resolvedCommand} --model "\${${firstAliasEnv}:-$OPENAI_MODEL}"`);
  }

  return lines.join("\n");
}

export function buildCustomCliJsonConfig({

  cliName,

  baseUrl,

  apiKey,

  defaultModel = "",

  aliasMappings = [],

}: CustomCliConfigInput): string {
  const normalizedBaseUrl = normalizeOpenAiBaseUrl(baseUrl);
  const resolvedName = cliName.trim() || "Custom CLI";
  const resolvedDefaultModel = defaultModel.trim();
  const mappings = getValidMappings(aliasMappings);

  const config = {
    name: resolvedName,
    provider: {
      type: "openai",
      baseURL: normalizedBaseUrl,
      apiKey,
      ...(resolvedDefaultModel ? { model: resolvedDefaultModel } : {}),
    },
    ...(mappings.length > 0
      ? {
          modelAliases: Object.fromEntries(
            mappings.map((mapping) => [mapping.alias.trim(), mapping.model.trim()])
          ),
        }
      : {}),
  };

  return JSON.stringify(config, null, 2);
}