Repository navigation
Expand file tree
/
Copy pathinit.ts
More file actions
296 lines (275 loc) · 13 KB
/
Copy pathinit.ts
File metadata and controls
296 lines (275 loc) · 13 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import * as readline from "node:readline";
import { modelSelectionGuidance } from "./model-selection-guidance";
import { initializeProviderModelSelection } from "../providers/initial-model-selection";
import { existsSync, readFileSync, unlinkSync } from "node:fs";
import { injectCodexConfig } from "../codex/inject";
import { classifyOpenAiTierBackup, ConfigMutationLockError, getConfigPath, getDefaultConfig, initializePersistedConfigIfMissing, isValidProviderName, observeInitialConfigState, preserveOpenAiTierRollbackSnapshot } from "../config";
import { InitialConfigPublicationError } from "../config/initialize";
import { redactUserPath } from "../lib/redact";
import { enrichProviderFromCatalog } from "../oauth/key-providers";
import { deriveInitProviders } from "../providers/derive";
import { pinSponsorsWithinKind } from "../providers/sponsor-order";
import type { OcxConfig, OcxProviderConfig } from "../types";
/** Parse a setup TCP port; only an empty answer selects the default. */
export function parseInitPort(raw: string): number | null {
const text = raw.trim();
if (!text) return 10100;
const value = /^\d+$/.test(text) ? Number(text) : NaN;
return Number.isInteger(value) && value >= 1 && value <= 65535 ? value : null;
}
class InitCancelledError extends Error {
constructor(readonly exitCode: 1 | 130) {
super(exitCode === 130 ? "Setup cancelled." : "stdin reached EOF while waiting for input. Re-run `ocx init` in an interactive terminal.");
}
}
function createPrompt(): { ask(question: string): Promise<string>; throwIfCancelled(): void; close(): void } {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
let closed = false;
let cancellation: InitCancelledError | undefined;
const => {
cancellation = new InitCancelledError(130);
rl.close();
};
rl.on("SIGINT", onInterrupt);
process.on("SIGINT", onInterrupt);
rl.on("close", () => {
closed = true;
cancellation ??= new InitCancelledError(1);
process.off("SIGINT", onInterrupt);
rl.off("SIGINT", onInterrupt);
});
return {
ask(question: string): Promise<string> {
return new Promise((resolve, reject) => {
if (closed) {
reject(cancellation ?? new InitCancelledError(1));
return;
}
const => {
reject(cancellation ?? new InitCancelledError(1));
};
rl.once("close", onClose);
rl.question(question, answer => {
rl.off("close", onClose);
resolve(answer);
});
});
},
throwIfCancelled() {
if (cancellation) throw cancellation;
},
close() {
if (!closed) 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;
}
const preserved = preserveOpenAiTierRollbackSnapshot(configPath);
console.warn(`⚠️ Kept your pre-migration config rollback snapshot at ${preserved}`);
} catch { /* cleanup is best-effort; never block init on backup housekeeping */ }
}
/** Create a first configuration interactively, preserving existing files and refusing invalid input. */
export async function runInit(): Promise<void> {
const initial = observeInitialConfigState();
if (initial === "exists") {
console.log(`Keeping existing config at ${redactUserPath(getConfigPath())}. Use \`ocx config\` or the dashboard to update it.`);
return;
}
if (initial === "invalid") {
console.error(`Cannot initialize ${redactUserPath(getConfigPath())}: existing config is invalid, unreadable, or not a regular file. It has been preserved.`);
process.exitCode = 1;
return;
}
const prompt = createPrompt();
let configCreated = false;
try {
console.log("\n🔧 opencodex (ocx) setup\n");
const providers = pinSponsorsWithinKind(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.");
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() } : {}),
};
}
// A mistyped port re-asks instead of discarding every earlier answer; EOF and SIGINT
// still reject the pending question with InitCancelledError.
let port: number | null;
do {
port = parseInitPort(await prompt.ask("\nProxy port [10100]: "));
if (port === null) console.error("Proxy port must be a whole decimal number from 1 to 65535. Please try again.");
} while (port === null);
initializeProviderModelSelection(providerName, providerConfig);
const config: OcxConfig = {
...getDefaultConfig(),
port,
providers: { [providerName]: providerConfig },
defaultProvider: providerName,
modelDiscovery: { newModelPolicy: "off" },
};
prompt.throwIfCancelled();
const outcome = initializePersistedConfigIfMissing(config);
if (outcome !== "created") {
console.error("Config appeared or changed while setup was running; keeping it and stopping setup.");
process.exitCode = 1;
return;
}
configCreated = true;
// 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 ${redactUserPath(getConfigPath())}`);
if (oauthHint) console.log(`🔐 Authenticate this provider with: ocx login ${providerName}`);
const injectAnswer = await prompt.ask("Inject into Codex config.toml? [Y/n]: ");
prompt.throwIfCancelled();
if (injectAnswer.trim().toLowerCase() !== "n") {
console.log("Fetching available models from provider...");
const result = await injectCodexConfig(port, config, {
beforeClientWrite: () => prompt.throwIfCancelled(),
}).catch(error => {
// The injection/lock boundary may wrap the guard's cancellation error.
prompt.throwIfCancelled();
throw error;
});
prompt.throwIfCancelled();
console.log(result.success ? `✅ ${result.message}` : `⚠️ ${result.message}`);
}
const shimAnswer = await prompt.ask("Install Codex autostart shim? [Y/n]: ");
prompt.throwIfCancelled();
if (shimAnswer.trim().toLowerCase() !== "n") {
try {
const { installCodexShimAsync } = await import("../codex/shim");
prompt.throwIfCancelled();
const result = await installCodexShimAsync();
console.log(result.installed ? `✅ ${result.message}` : `⚠️ ${result.message}`);
} catch (err) {
if (err instanceof InitCancelledError) throw err;
console.log(`⚠️ Cod
4F30
ex autostart shim skipped: ${err instanceof Error ? err.message : String(err)}`);
}
}
console.log(`\n🚀 Setup complete! Run 'ocx start' to start the proxy.`);
// Said after the autostart choice, because the choice is what decides whether it applies.
// Setup otherwise ends on a success line while leaving a restart dependency unmentioned.
try {
const { collectStartupHealth, injectedRoutingRestartWarningLines } = await import("../codex/autostart-health");
for (const line of injectedRoutingRestartWarningLines(collectStartupHealth(config))) console.log(line);
} catch {
// A diagnostic that cannot be computed must not fail a completed setup.
}
for (const line of modelSelectionGuidance(providerName)) console.log(line);
} catch (error) {
if (error instanceof InitCancelledError) {
console.error(`\n❌ ${error.message}${configCreated ? " The created config has been kept." : ""}`);
process.exitCode = error.exitCode;
} else {
const message = error instanceof InitialConfigPublicationError
? `${error.message}${error.publication !== "not-published" ? " Config may already exist; inspect it before retrying." : ""}${error.residualTemp ? " A temporary file could not be removed; inspect the config directory." : ""}`
: error instanceof ConfigMutationLockError
? "Config initialization could not acquire its write lock. Retry when the other config operation finishes."
: `Setup did not finish.${configCreated ? " The created config has been kept." : " Check the config directory and setup inputs before retrying."}`;
console.error(`\n❌ ${message}`);
process.exitCode = 1;
}
} finally {
prompt.close();
}
}