Repository navigation
Expand file tree
/
Copy pathinit.ts
More file actions
197 lines (178 loc) · 8.34 KB
/
Copy pathinit.ts
File metadata and controls
197 lines (178 loc) · 8.34 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import * as readline from "node:readline";
import { constants as fsConstants, copyFileSync, existsSync, readFileSync, unlinkSync } from "node:fs";
import { injectCodexConfig } from "../codex/inject";
import { classifyOpenAiTierBackup, getConfigPath, getDefaultConfig, isValidProviderName, saveConfig } from "../config";
import { enrichProviderFromCatalog } from "../oauth/key-providers";
import { deriveInitProviders } from "../providers/derive";
import type { OcxConfig, OcxProviderConfig } from "../types";
function createPrompt(): { ask(question: string): Promise<string>; close(): void } {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return {
ask(question: string): Promise<string> {
return new Promise(resolve => rl.question(question, resolve));
},
close() { rl.close(); },
};
}
type InitKind = "forward" | "oauth" | "key" | "local";
export interface InitProvider {
id: string;
label: string;
adapter: string;
baseUrl: string;
kind: InitKind;
dashboardUrl?: string;
defaultModel?: string;
}
/**
* The full CLI provider menu, derived from the canonical provider registry so `ocx init`,
* the GUI picker, key-login catalog, OAuth seeds, and metadata aliases cannot drift.
*/
export function buildInitProviders(): InitProvider[] {
return deriveInitProviders();
}
const KIND_HEADING: Record<InitKind, string> = {
forward: "ChatGPT login",
oauth: "Account login (OAuth — then run: ocx login <id>)",
key: "API key (paste a key from the provider's dashboard)",
local: "Local servers (usually no key)",
};
function printMenu(providers: InitProvider[]): void {
console.log("Choose your default provider (you can add more later):");
let lastKind: InitKind | null = null;
providers.forEach((p, i) => {
if (p.kind !== lastKind) { console.log(`\n ${KIND_HEADING[p.kind]}:`); lastKind = p.kind; }
console.log(` ${String(i + 1).padStart(2)}. ${p.label}`);
});
console.log(`\n ${providers.length + 1}. custom (enter URL manually)`);
}
const envKeyFor = (id: string) => `${id.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_API_KEY`;
/** Post-init cleanup of `.pre-openai-tiers-v2.bak` with rollback preservation (issue #257). */
export function cleanupOpenAiTierBackupAfterInit(configPath = getConfigPath()): void {
const backup = `${configPath}.pre-openai-tiers-v2.bak`;
try {
if (!existsSync(backup)) return;
if (classifyOpenAiTierBackup(readFileSync(backup)) === "stale") {
unlinkSync(backup);
return;
}
// Publish the preserved snapshot with a no-replace copy (COPYFILE_EXCL) so a
// destination collision (frozen/rolled-back clock, pre-created file) can never
// silently overwrite another rollback snapshot; retry with a sequence suffix.
for (let attempt = 0; attempt < 16; attempt++) {
const preserved = `${configPath}.pre-openai-tiers-v1-rollback.${Date.now()}${attempt ? `-${attempt}` : ""}.bak`;
try {
copyFileSync(backup, preserved, fsConstants.COPYFILE_EXCL);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "EEXIST") continue;
throw error;
}
unlinkSync(backup);
console.warn(`⚠️ Kept your pre-migration config rollback snapshot at ${preserved}`);
return;
}
} catch { /* cleanup is best-effort; never block init on backup housekeeping */ }
}
export async function runInit(): Promise<void> {
const prompt = createPrompt();
console.log("\n🔧 opencodex (ocx) setup\n");
const providers = buildInitProviders();
printMenu(providers);
const choice = await prompt.ask("\nSelect default provider (number): ");
const idx = parseInt(choice, 10) - 1;
let providerName: string;
let providerConfig: OcxProviderConfig;
let oauthHint = false;
if (idx >= 0 && idx < providers.length) {
const p = providers[idx];
providerName = p.id;
console.log(`\n📡 ${p.label}`);
console.log(` Base URL: ${p.baseUrl}`);
if (p.kind === "forward") {
providerConfig = { adapter: p.adapter, baseUrl: p.baseUrl, authMode: "forward" };
console.log(" No API key needed — forwards your existing `codex login`.");
} else if (p.kind === "oauth") {
providerConfig = { adapter: p.adapter, baseUrl: p.baseUrl, authMode: "oauth", ...(p.defaultModel ? { defaultModel: p.defaultModel } : {}) };
oauthHint = true;
} else {
// key + local: collect a key (local usually blank).
if (p.dashboardUrl) console.log(` 🔑 Get your key: ${p.dashboardUrl}`);
// Template URL with placeholders (e.g. Cloudflare's {account_id}) needs a resolved value.
let baseUrl = p.baseUrl;
if (/\{[^}]*\}/.test(baseUrl)) {
const resolved = (await prompt.ask(` Your endpoint URL (${baseUrl}): `)).trim();
if (!resolved) {
console.error(" A resolved URL is required — replace the {placeholder} with your actual value.");
process.exit(1);
}
baseUrl = resolved;
}
const env = envKeyFor(p.id);
const hint = p.kind === "local" ? "API key (usually blank — press Enter): " : `API key (paste, or env var $${env}): `;
const apiKey = (await prompt.ask(`\n${hint}`)).trim();
const modelChoice = (await prompt.ask(`Default model${p.defaultModel ? ` [${p.defaultModel}]` : " (optional)"}: `)).trim();
const defaultModel = modelChoice || p.defaultModel;
providerConfig = {
adapter: p.adapter,
baseUrl,
...(p.kind === "key" ? { apiKey: apiKey || `\${${env}}` } : apiKey ? { apiKey } : {}),
...(defaultModel ? { defaultModel } : {}),
};
// Apply the catalog's models / vision classification (same enrichment as the GUI).
enrichProviderFromCatalog(p.id, providerConfig);
}
} else {
providerName = (await prompt.ask("Provider name: ")).trim();
if (!isValidProviderName(providerName)) {
console.error("Provider name must use letters, numbers, dot, underscore, or hyphen and cannot be a reserved object key.");
prompt.close();
process.exit(1);
}
const baseUrl = await prompt.ask("Base URL (e.g. http://localhost:11434/v1): ");
const adapter = await prompt.ask("Adapter [openai-chat]: ") || "openai-chat";
const apiKey = await prompt.ask("API key (optional): ");
const defaultModel = await prompt.ask("Default model: ");
providerConfig = {
adapter: adapter.trim(),
baseUrl: baseUrl.trim(),
...(apiKey.trim() ? { apiKey: apiKey.trim() } : {}),
...(defaultModel.trim() ? { defaultModel: defaultModel.trim() } : {}),
};
}
const portStr = await prompt.ask("\nProxy port [10100]: ");
const port = parseInt(portStr, 10) || 10100;
const config: OcxConfig = {
...getDefaultConfig(),
port,
providers: { [providerName]: providerConfig },
defaultProvider: providerName,
};
saveConfig(config);
// Init writes a fresh config, so a stale pre-migration backup from a previous
// installation would make the next `ocx start` crash on a stale-backup
// collision (issue #257). But only a STALE backup (unparseable, or already a
// post-migration v2 snapshot) may be deleted; a backup that still parses as a
// valid pre-migration (v1) config is a user-intentional rollback point and is
// preserved by renaming it out of the collision path (sol review 260722).
cleanupOpenAiTierBackupAfterInit();
console.log(`\n✅ Config saved to ~/.opencodex/config.json`);
if (oauthHint) console.log(`🔐 Authenticate this provider with: ocx login ${providerName}`);
const injectAnswer = await prompt.ask("Inject into Codex config.toml? [Y/n]: ");
if (injectAnswer.trim().toLowerCase() !== "n") {
console.log("Fetching available models from provider...");
const result = await injectCodexConfig(port, config);
console.log(result.success ? `✅ ${result.message}` : `⚠️ ${result.message}`);
}
const shimAnswer = await prompt.ask("Install Codex autostart shim? [Y/n]: ");
if (shimAnswer.trim().toLowerCase() !== "n") {
try {
const { installCodexShim } = await import("../codex/shim");
const result = installCodexShim();
console.log(result.installed ? `✅ ${result.message}` : `⚠️ ${result.message}`);
} catch (err) {
console.log(`⚠️ Codex autostart shim skipped: ${err instanceof Error ? err.message : String(err)}`);
}
}
console.log(`\n🚀 Setup complete! Run 'ocx start' to start the proxy.`);
prompt.close();
}