@liberseek/boft-cli 0.1.1 → 0.4.4
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 +13 -237
- package/bin/boft.js +435 -0
- package/bin/codexhost.js +435 -0
- package/package.json +30 -32
- package/dist/api.d.ts +0 -93
- package/dist/api.d.ts.map +0 -1
- package/dist/api.js +0 -248
- package/dist/api.js.map +0 -1
- package/dist/cli.d.ts +0 -19
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js +0 -743
- package/dist/cli.js.map +0 -1
- package/dist/codex.d.ts +0 -70
- package/dist/codex.d.ts.map +0 -1
- package/dist/codex.js +0 -664
- package/dist/codex.js.map +0 -1
- package/dist/config.d.ts +0 -14
- package/dist/config.d.ts.map +0 -1
- package/dist/config.js +0 -105
- package/dist/config.js.map +0 -1
- package/dist/index.d.ts +0 -3
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -4
- package/dist/index.js.map +0 -1
- package/dist/output.d.ts +0 -11
- package/dist/output.d.ts.map +0 -1
- package/dist/output.js +0 -87
- package/dist/output.js.map +0 -1
- package/dist/platforms.d.ts +0 -63
- package/dist/platforms.d.ts.map +0 -1
- package/dist/platforms.js +0 -568
- package/dist/platforms.js.map +0 -1
- package/dist/prompt.d.ts +0 -4
- package/dist/prompt.d.ts.map +0 -1
- package/dist/prompt.js +0 -49
- package/dist/prompt.js.map +0 -1
- package/dist/redact.d.ts +0 -3
- package/dist/redact.d.ts.map +0 -1
- package/dist/redact.js +0 -23
- package/dist/redact.js.map +0 -1
- package/dist/types.d.ts +0 -116
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -2
- package/dist/types.js.map +0 -1
- package/dist/validate.d.ts +0 -6
- package/dist/validate.d.ts.map +0 -1
- package/dist/validate.js +0 -47
- package/dist/validate.js.map +0 -1
- package/docs/HTTP_CONTRACT.md +0 -121
package/dist/codex.js
DELETED
|
@@ -1,664 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { spawn } from 'node:child_process';
|
|
3
|
-
import { chmod, mkdir, readFile, rename, stat, unlink, writeFile, } from 'node:fs/promises';
|
|
4
|
-
import { homedir } from 'node:os';
|
|
5
|
-
import { dirname, join } from 'node:path';
|
|
6
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
7
|
-
import * as TOML from '@decimalturn/toml-patch';
|
|
8
|
-
import { configDirectoryPath, normalizeBaseUrl } from './config.js';
|
|
9
|
-
const CODEX_PROVIDER_ID = 'OpenAI';
|
|
10
|
-
const LEGACY_CODEX_PROVIDER_ID = 'boft';
|
|
11
|
-
const CODEX_MODEL = 'gpt-5.4';
|
|
12
|
-
const DEFAULT_PROFILE = 'default';
|
|
13
|
-
const MANAGED_BLOCK_START = '# >>> BOFT CLI managed provider';
|
|
14
|
-
const MANAGED_BLOCK_END = '# <<< BOFT CLI managed provider';
|
|
15
|
-
export function resolveCodexPaths(env = process.env) {
|
|
16
|
-
const codexHome = env.CODEX_HOME?.trim() || join(homedir(), '.codex');
|
|
17
|
-
const storageDirectory = join(configDirectoryPath(env), 'codex');
|
|
18
|
-
return {
|
|
19
|
-
codexHome,
|
|
20
|
-
configPath: join(codexHome, 'config.toml'),
|
|
21
|
-
authPath: join(codexHome, 'auth.json'),
|
|
22
|
-
storageDirectory,
|
|
23
|
-
credentialsPath: join(storageDirectory, 'credentials.json'),
|
|
24
|
-
helperPath: join(storageDirectory, 'codex-auth-helper.mjs'),
|
|
25
|
-
manifestPath: join(storageDirectory, 'manifest.json'),
|
|
26
|
-
backupsDirectory: join(storageDirectory, 'backups'),
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
export async function setupCodex(input) {
|
|
30
|
-
const env = input.env ?? process.env;
|
|
31
|
-
const paths = resolveCodexPaths(env);
|
|
32
|
-
const apiKey = validateSecret(input.apiKey, 'BOFT API Key');
|
|
33
|
-
const endpoint = normalizeBaseUrl(input.endpoint);
|
|
34
|
-
const model = CODEX_MODEL;
|
|
35
|
-
const reviewModel = CODEX_MODEL;
|
|
36
|
-
const providerName = 'BANK OF TOKEN';
|
|
37
|
-
await ensureCodexHome(paths, env, Boolean(input.dryRun));
|
|
38
|
-
if (!input.dryRun)
|
|
39
|
-
await ensurePrivateDirectory(paths.storageDirectory);
|
|
40
|
-
const existingConfig = await readOptionalText(paths.configPath) ?? '';
|
|
41
|
-
const parsed = parseToml(existingConfig, paths.configPath);
|
|
42
|
-
const currentManifest = await readManifest(paths.manifestPath);
|
|
43
|
-
if (currentManifest?.provider_id === LEGACY_CODEX_PROVIDER_ID) {
|
|
44
|
-
throw new Error('Legacy BOFT Codex setup detected. Run `boft rollback codex` before configuring Codex again.');
|
|
45
|
-
}
|
|
46
|
-
const stripped = stripManagedProviderBlock(existingConfig, CODEX_PROVIDER_ID);
|
|
47
|
-
if (currentManifest !== undefined && !stripped.found) {
|
|
48
|
-
throw new Error('BOFT Codex manifest exists but its managed provider block is missing');
|
|
49
|
-
}
|
|
50
|
-
if (currentManifest === undefined && stripped.found) {
|
|
51
|
-
throw new Error('BOFT-managed Codex provider block exists without a manifest; refusing to overwrite it');
|
|
52
|
-
}
|
|
53
|
-
const previous = captureManagedState(parsed, CODEX_PROVIDER_ID);
|
|
54
|
-
const updated = cloneRecord(parseToml(stripped.content, paths.configPath));
|
|
55
|
-
updated.model_provider = CODEX_PROVIDER_ID;
|
|
56
|
-
updated.model = model;
|
|
57
|
-
updated.review_model = reviewModel;
|
|
58
|
-
updated.model_reasoning_effort = 'xhigh';
|
|
59
|
-
updated.disable_response_storage = true;
|
|
60
|
-
updated.network_access = 'enabled';
|
|
61
|
-
updated.windows_wsl_setup_acknowledged = true;
|
|
62
|
-
updated.model_context_window = 1_000_000;
|
|
63
|
-
updated.model_auto_compact_token_limit = 900_000;
|
|
64
|
-
removeProvider(updated, CODEX_PROVIDER_ID);
|
|
65
|
-
const provider = {
|
|
66
|
-
name: providerName,
|
|
67
|
-
base_url: endpoint,
|
|
68
|
-
wire_api: 'responses',
|
|
69
|
-
requires_openai_auth: true,
|
|
70
|
-
};
|
|
71
|
-
if (input.websocket)
|
|
72
|
-
provider.supports_websockets = true;
|
|
73
|
-
if (input.websocket) {
|
|
74
|
-
ensureNestedRecord(updated, 'features').responses_websockets_v2 = true;
|
|
75
|
-
}
|
|
76
|
-
else if (currentManifest && isDeepStrictEqual(previous.websocket_feature, currentManifest.applied.websocket_feature)) {
|
|
77
|
-
restoreFeatureSnapshot(updated, currentManifest.previous.websocket_feature);
|
|
78
|
-
}
|
|
79
|
-
const baseConfig = TOML.patch(stripped.content, updated);
|
|
80
|
-
const nextConfig = appendManagedProviderBlock(baseConfig, provider, CODEX_PROVIDER_ID);
|
|
81
|
-
const verified = parseToml(nextConfig, paths.configPath);
|
|
82
|
-
const applied = captureManagedState(verified, CODEX_PROVIDER_ID);
|
|
83
|
-
const result = {
|
|
84
|
-
configured: !input.dryRun,
|
|
85
|
-
dry_run: Boolean(input.dryRun),
|
|
86
|
-
active: true,
|
|
87
|
-
provider: CODEX_PROVIDER_ID,
|
|
88
|
-
model,
|
|
89
|
-
endpoint,
|
|
90
|
-
websocket: Boolean(input.websocket),
|
|
91
|
-
config_path: paths.configPath,
|
|
92
|
-
credentials_path: paths.authPath,
|
|
93
|
-
restart_required: !input.dryRun,
|
|
94
|
-
};
|
|
95
|
-
if (input.dryRun)
|
|
96
|
-
return result;
|
|
97
|
-
const backupId = backupIdentifier();
|
|
98
|
-
const backupPath = join(paths.backupsDirectory, backupId);
|
|
99
|
-
await createBackup(paths, backupPath);
|
|
100
|
-
const auth = await nextCodexAuth(paths.authPath, apiKey);
|
|
101
|
-
const manifest = {
|
|
102
|
-
version: 1,
|
|
103
|
-
provider_id: CODEX_PROVIDER_ID,
|
|
104
|
-
profile: DEFAULT_PROFILE,
|
|
105
|
-
created_at: new Date().toISOString(),
|
|
106
|
-
backup_id: backupId,
|
|
107
|
-
config_path: paths.configPath,
|
|
108
|
-
auth_key_hash: secretHash(apiKey),
|
|
109
|
-
previous,
|
|
110
|
-
applied,
|
|
111
|
-
};
|
|
112
|
-
try {
|
|
113
|
-
await atomicWrite(paths.authPath, `${JSON.stringify(auth, null, 2)}\n`, 0o600);
|
|
114
|
-
await atomicWrite(paths.configPath, ensureTrailingNewline(nextConfig), 0o600);
|
|
115
|
-
await atomicWrite(paths.manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 0o600);
|
|
116
|
-
}
|
|
117
|
-
catch (error) {
|
|
118
|
-
await restoreBackup(paths, backupPath, true).catch(() => undefined);
|
|
119
|
-
throw new Error(`Unable to configure Codex: ${errorMessage(error)}`);
|
|
120
|
-
}
|
|
121
|
-
return { ...result, backup_path: backupPath };
|
|
122
|
-
}
|
|
123
|
-
export async function codexStatus(env = process.env) {
|
|
124
|
-
const paths = resolveCodexPaths(env);
|
|
125
|
-
const configText = await readOptionalText(paths.configPath);
|
|
126
|
-
const parsed = configText === undefined ? {} : parseToml(configText, paths.configPath);
|
|
127
|
-
const manifest = await readManifest(paths.manifestPath);
|
|
128
|
-
const providerId = manifest?.provider_id ?? CODEX_PROVIDER_ID;
|
|
129
|
-
const provider = asRecord(nestedRecord(parsed, 'model_providers')?.[providerId]);
|
|
130
|
-
const legacy = providerId === LEGACY_CODEX_PROVIDER_ID;
|
|
131
|
-
const credentialsPresent = legacy
|
|
132
|
-
? Boolean((await readStoredCredentials(paths.credentialsPath))?.profiles[DEFAULT_PROFILE]?.api_key)
|
|
133
|
-
: Boolean((await readCodexAuth(paths.authPath))?.OPENAI_API_KEY);
|
|
134
|
-
return {
|
|
135
|
-
configured: manifest !== undefined && provider !== undefined,
|
|
136
|
-
active: parsed.model_provider === providerId,
|
|
137
|
-
provider_present: provider !== undefined,
|
|
138
|
-
credentials_present: credentialsPresent,
|
|
139
|
-
helper_present: legacy ? await pathExists(paths.helperPath) : undefined,
|
|
140
|
-
model: typeof parsed.model === 'string' ? parsed.model : undefined,
|
|
141
|
-
endpoint: typeof provider?.base_url === 'string' ? provider.base_url : undefined,
|
|
142
|
-
websocket: provider?.supports_websockets === true,
|
|
143
|
-
config_path: paths.configPath,
|
|
144
|
-
credentials_path: legacy ? paths.credentialsPath : paths.authPath,
|
|
145
|
-
backup_path: manifest ? join(paths.backupsDirectory, manifest.backup_id) : undefined,
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
export async function doctorCodex(env = process.env, installation) {
|
|
149
|
-
const status = await codexStatus(env);
|
|
150
|
-
const detected = installation ?? await detectCodexInstallation(env);
|
|
151
|
-
const issues = [];
|
|
152
|
-
if (!detected.detected)
|
|
153
|
-
issues.push('Codex CLI was not found in PATH');
|
|
154
|
-
if (!status.provider_present)
|
|
155
|
-
issues.push('BOFT Codex provider is missing');
|
|
156
|
-
if (!status.active)
|
|
157
|
-
issues.push('BOFT is not the active Codex provider');
|
|
158
|
-
if (!status.credentials_present)
|
|
159
|
-
issues.push('BOFT Codex credentials are missing');
|
|
160
|
-
if (status.helper_present === false)
|
|
161
|
-
issues.push('BOFT Codex authentication helper is missing');
|
|
162
|
-
if (process.platform !== 'win32') {
|
|
163
|
-
await checkOwnerOnlyMode(status.credentials_path, 0o077, 'credential file', issues);
|
|
164
|
-
if (status.helper_present !== undefined) {
|
|
165
|
-
await checkOwnerOnlyMode(resolveCodexPaths(env).helperPath, 0o077, 'authentication helper', issues);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
return {
|
|
169
|
-
...status,
|
|
170
|
-
healthy: issues.length === 0,
|
|
171
|
-
issues,
|
|
172
|
-
codex_detected: detected.detected,
|
|
173
|
-
codex_version: detected.version,
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
export async function detectCodexInstallation(env = process.env) {
|
|
177
|
-
return new Promise((resolve) => {
|
|
178
|
-
const child = spawn('codex', ['--version'], {
|
|
179
|
-
env,
|
|
180
|
-
shell: process.platform === 'win32',
|
|
181
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
182
|
-
windowsHide: true,
|
|
183
|
-
});
|
|
184
|
-
let stdout = '';
|
|
185
|
-
let stderr = '';
|
|
186
|
-
const timer = setTimeout(() => child.kill(), 5_000);
|
|
187
|
-
child.stdout?.on('data', (chunk) => {
|
|
188
|
-
if (stdout.length < 4096)
|
|
189
|
-
stdout += String(chunk);
|
|
190
|
-
});
|
|
191
|
-
child.stderr?.on('data', (chunk) => {
|
|
192
|
-
if (stderr.length < 4096)
|
|
193
|
-
stderr += String(chunk);
|
|
194
|
-
});
|
|
195
|
-
child.once('error', () => {
|
|
196
|
-
clearTimeout(timer);
|
|
197
|
-
resolve({ detected: false });
|
|
198
|
-
});
|
|
199
|
-
child.once('close', (code) => {
|
|
200
|
-
clearTimeout(timer);
|
|
201
|
-
const version = `${stdout}\n${stderr}`.trim().split(/\r?\n/, 1)[0]?.trim();
|
|
202
|
-
resolve(code === 0 ? { detected: true, ...(version ? { version } : {}) } : { detected: false });
|
|
203
|
-
});
|
|
204
|
-
});
|
|
205
|
-
}
|
|
206
|
-
export async function rollbackCodex(env = process.env) {
|
|
207
|
-
const paths = resolveCodexPaths(env);
|
|
208
|
-
const manifest = await readManifest(paths.manifestPath);
|
|
209
|
-
if (!manifest)
|
|
210
|
-
return { restored: false, config_path: paths.configPath };
|
|
211
|
-
if (manifest.config_path !== paths.configPath) {
|
|
212
|
-
throw new Error(`Codex configuration moved from ${manifest.config_path}; refusing automatic rollback`);
|
|
213
|
-
}
|
|
214
|
-
const configText = await readOptionalText(paths.configPath) ?? '';
|
|
215
|
-
const parsed = parseToml(configText, paths.configPath);
|
|
216
|
-
const current = captureManagedState(parsed, manifest.provider_id);
|
|
217
|
-
if (!managedStateMatches(current, manifest.applied)) {
|
|
218
|
-
throw new Error('BOFT-managed Codex settings changed after setup; refusing to overwrite them during rollback');
|
|
219
|
-
}
|
|
220
|
-
const stripped = stripManagedProviderBlock(configText, manifest.provider_id);
|
|
221
|
-
if (!stripped.found)
|
|
222
|
-
throw new Error('BOFT-managed Codex provider block is missing');
|
|
223
|
-
const restoredData = cloneRecord(parseToml(stripped.content, paths.configPath));
|
|
224
|
-
restoreManagedState(restoredData, manifest.previous);
|
|
225
|
-
removeProvider(restoredData, manifest.provider_id);
|
|
226
|
-
const previousProvider = manifest.previous.provider.exists
|
|
227
|
-
? asRecord(manifest.previous.provider.value)
|
|
228
|
-
: undefined;
|
|
229
|
-
const backupPath = join(paths.backupsDirectory, manifest.backup_id);
|
|
230
|
-
const previousManaged = await backupFileExisted(backupPath, 'manifest');
|
|
231
|
-
if (previousProvider && !previousManaged) {
|
|
232
|
-
ensureNestedRecord(restoredData, 'model_providers')[manifest.provider_id] = previousProvider;
|
|
233
|
-
}
|
|
234
|
-
const restoredBaseConfig = TOML.patch(stripped.content, restoredData);
|
|
235
|
-
const restoredConfig = previousProvider && previousManaged
|
|
236
|
-
? appendManagedProviderBlock(restoredBaseConfig, previousProvider, manifest.provider_id)
|
|
237
|
-
: restoredBaseConfig;
|
|
238
|
-
parseToml(restoredConfig, paths.configPath);
|
|
239
|
-
const authRestoration = manifest.provider_id === CODEX_PROVIDER_ID && manifest.auth_key_hash
|
|
240
|
-
? await prepareCodexAuthRestoration(paths, backupPath, manifest.auth_key_hash)
|
|
241
|
-
: undefined;
|
|
242
|
-
await atomicWrite(paths.configPath, ensureTrailingNewline(restoredConfig), 0o600);
|
|
243
|
-
await restoreBackup(paths, backupPath, false, authRestoration === undefined);
|
|
244
|
-
if (authRestoration)
|
|
245
|
-
await applyCodexAuthRestoration(paths.authPath, authRestoration);
|
|
246
|
-
return { restored: true, config_path: paths.configPath };
|
|
247
|
-
}
|
|
248
|
-
export async function removeCodex(env = process.env) {
|
|
249
|
-
let rollbacks = 0;
|
|
250
|
-
while (await readManifest(resolveCodexPaths(env).manifestPath)) {
|
|
251
|
-
const result = await rollbackCodex(env);
|
|
252
|
-
if (!result.restored)
|
|
253
|
-
break;
|
|
254
|
-
rollbacks += 1;
|
|
255
|
-
if (rollbacks >= 100)
|
|
256
|
-
throw new Error('Refusing to process more than 100 Codex rollback layers');
|
|
257
|
-
}
|
|
258
|
-
return { removed: rollbacks > 0, rollbacks };
|
|
259
|
-
}
|
|
260
|
-
export async function readCodexApiKey(profile = DEFAULT_PROFILE, env = process.env) {
|
|
261
|
-
const paths = resolveCodexPaths(env);
|
|
262
|
-
const manifest = await readManifest(paths.manifestPath);
|
|
263
|
-
const apiKey = manifest?.provider_id === LEGACY_CODEX_PROVIDER_ID
|
|
264
|
-
? (await readStoredCredentials(paths.credentialsPath))?.profiles[profile]?.api_key
|
|
265
|
-
: (await readCodexAuth(paths.authPath))?.OPENAI_API_KEY;
|
|
266
|
-
if (typeof apiKey !== 'string' || !apiKey) {
|
|
267
|
-
throw new Error(`No BOFT Codex credentials found for profile ${profile}`);
|
|
268
|
-
}
|
|
269
|
-
return validateSecret(apiKey, 'Stored BOFT API Key');
|
|
270
|
-
}
|
|
271
|
-
function parseToml(value, path) {
|
|
272
|
-
try {
|
|
273
|
-
const parsed = TOML.parse(value || '');
|
|
274
|
-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
275
|
-
throw new Error('root must be a table');
|
|
276
|
-
return parsed;
|
|
277
|
-
}
|
|
278
|
-
catch (error) {
|
|
279
|
-
throw new Error(`Unable to parse Codex TOML at ${path}: ${errorMessage(error)}`);
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
function captureManagedState(data, providerId) {
|
|
283
|
-
return {
|
|
284
|
-
model_provider: snapshot(data, 'model_provider'),
|
|
285
|
-
model: snapshot(data, 'model'),
|
|
286
|
-
review_model: snapshot(data, 'review_model'),
|
|
287
|
-
model_reasoning_effort: snapshot(data, 'model_reasoning_effort'),
|
|
288
|
-
disable_response_storage: snapshot(data, 'disable_response_storage'),
|
|
289
|
-
network_access: snapshot(data, 'network_access'),
|
|
290
|
-
windows_wsl_setup_acknowledged: snapshot(data, 'windows_wsl_setup_acknowledged'),
|
|
291
|
-
model_context_window: snapshot(data, 'model_context_window'),
|
|
292
|
-
model_auto_compact_token_limit: snapshot(data, 'model_auto_compact_token_limit'),
|
|
293
|
-
provider: snapshot(nestedRecord(data, 'model_providers') ?? {}, providerId),
|
|
294
|
-
websocket_feature: snapshot(nestedRecord(data, 'features') ?? {}, 'responses_websockets_v2'),
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
function restoreManagedState(data, state) {
|
|
298
|
-
restoreSnapshot(data, 'model_provider', state.model_provider);
|
|
299
|
-
restoreSnapshot(data, 'model', state.model);
|
|
300
|
-
restoreSnapshot(data, 'review_model', state.review_model);
|
|
301
|
-
restoreOptionalSnapshot(data, 'model_reasoning_effort', state.model_reasoning_effort);
|
|
302
|
-
restoreOptionalSnapshot(data, 'disable_response_storage', state.disable_response_storage);
|
|
303
|
-
restoreOptionalSnapshot(data, 'network_access', state.network_access);
|
|
304
|
-
restoreOptionalSnapshot(data, 'windows_wsl_setup_acknowledged', state.windows_wsl_setup_acknowledged);
|
|
305
|
-
restoreOptionalSnapshot(data, 'model_context_window', state.model_context_window);
|
|
306
|
-
restoreOptionalSnapshot(data, 'model_auto_compact_token_limit', state.model_auto_compact_token_limit);
|
|
307
|
-
restoreFeatureSnapshot(data, state.websocket_feature);
|
|
308
|
-
}
|
|
309
|
-
function managedStateMatches(current, applied) {
|
|
310
|
-
for (const key of Object.keys(applied)) {
|
|
311
|
-
if (applied[key] !== undefined && !isDeepStrictEqual(current[key], applied[key]))
|
|
312
|
-
return false;
|
|
313
|
-
}
|
|
314
|
-
return true;
|
|
315
|
-
}
|
|
316
|
-
function restoreOptionalSnapshot(data, key, value) {
|
|
317
|
-
if (value !== undefined)
|
|
318
|
-
restoreSnapshot(data, key, value);
|
|
319
|
-
}
|
|
320
|
-
function restoreFeatureSnapshot(data, value) {
|
|
321
|
-
const features = nestedRecord(data, 'features');
|
|
322
|
-
if (value.exists)
|
|
323
|
-
restoreSnapshot(features ?? ensureNestedRecord(data, 'features'), 'responses_websockets_v2', value);
|
|
324
|
-
else if (features)
|
|
325
|
-
delete features.responses_websockets_v2;
|
|
326
|
-
}
|
|
327
|
-
function appendManagedProviderBlock(config, provider, providerId) {
|
|
328
|
-
const format = TOML.TomlFormat.default();
|
|
329
|
-
format.inlineTableStart = 3;
|
|
330
|
-
const serialized = TOML.stringify({ model_providers: { [providerId]: provider } }, format);
|
|
331
|
-
const parentHeader = '[model_providers]\n\n';
|
|
332
|
-
if (!serialized.startsWith(parentHeader))
|
|
333
|
-
throw new Error('Unable to serialize BOFT Codex provider');
|
|
334
|
-
const providerTables = serialized.slice(parentHeader.length).trimEnd();
|
|
335
|
-
const base = config.trimEnd();
|
|
336
|
-
return `${base ? `${base}\n\n` : ''}${MANAGED_BLOCK_START}\n${providerTables}\n${MANAGED_BLOCK_END}\n`;
|
|
337
|
-
}
|
|
338
|
-
function stripManagedProviderBlock(config, providerId) {
|
|
339
|
-
const start = config.indexOf(MANAGED_BLOCK_START);
|
|
340
|
-
if (start < 0)
|
|
341
|
-
return { content: config, found: false };
|
|
342
|
-
const secondStart = config.indexOf(MANAGED_BLOCK_START, start + MANAGED_BLOCK_START.length);
|
|
343
|
-
const end = config.indexOf(MANAGED_BLOCK_END, start + MANAGED_BLOCK_START.length);
|
|
344
|
-
const providerHeader = `[model_providers.${providerId}]`;
|
|
345
|
-
const providerStart = config.indexOf(providerHeader, start + MANAGED_BLOCK_START.length);
|
|
346
|
-
if (secondStart >= 0 || end < 0 || providerStart < 0 || providerStart > end) {
|
|
347
|
-
throw new Error('BOFT Codex managed provider block is malformed');
|
|
348
|
-
}
|
|
349
|
-
const afterEnd = end + MANAGED_BLOCK_END.length;
|
|
350
|
-
// TOML editors may insert new root keys after the leading ownership comment.
|
|
351
|
-
// Preserve anything between that comment and our first owned table.
|
|
352
|
-
const insertedRootContent = config
|
|
353
|
-
.slice(start + MANAGED_BLOCK_START.length, providerStart)
|
|
354
|
-
.replace(/^\r?\n/, '')
|
|
355
|
-
.trim();
|
|
356
|
-
const beforeMarker = config.slice(0, start).trimEnd();
|
|
357
|
-
const before = [beforeMarker, insertedRootContent].filter(Boolean).join('\n');
|
|
358
|
-
const after = config.slice(afterEnd).replace(/^\r?\n/, '').trimStart();
|
|
359
|
-
return {
|
|
360
|
-
content: `${before}${before && after ? '\n\n' : ''}${after}`,
|
|
361
|
-
found: true,
|
|
362
|
-
};
|
|
363
|
-
}
|
|
364
|
-
function snapshot(record, key) {
|
|
365
|
-
return Object.prototype.hasOwnProperty.call(record, key)
|
|
366
|
-
? { exists: true, value: cloneValue(record[key]) }
|
|
367
|
-
: { exists: false };
|
|
368
|
-
}
|
|
369
|
-
function restoreSnapshot(record, key, value) {
|
|
370
|
-
if (value.exists)
|
|
371
|
-
record[key] = cloneValue(value.value);
|
|
372
|
-
else
|
|
373
|
-
delete record[key];
|
|
374
|
-
}
|
|
375
|
-
function nestedRecord(record, key) {
|
|
376
|
-
return asRecord(record[key]);
|
|
377
|
-
}
|
|
378
|
-
function ensureNestedRecord(record, key) {
|
|
379
|
-
const existing = asRecord(record[key]);
|
|
380
|
-
if (existing)
|
|
381
|
-
return existing;
|
|
382
|
-
const created = {};
|
|
383
|
-
record[key] = created;
|
|
384
|
-
return created;
|
|
385
|
-
}
|
|
386
|
-
function removeProvider(record, providerId) {
|
|
387
|
-
const providers = nestedRecord(record, 'model_providers');
|
|
388
|
-
if (!providers)
|
|
389
|
-
return;
|
|
390
|
-
delete providers[providerId];
|
|
391
|
-
if (Object.keys(providers).length === 0)
|
|
392
|
-
delete record.model_providers;
|
|
393
|
-
}
|
|
394
|
-
function asRecord(value) {
|
|
395
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
396
|
-
}
|
|
397
|
-
function cloneRecord(value) {
|
|
398
|
-
return structuredClone(value);
|
|
399
|
-
}
|
|
400
|
-
function cloneValue(value) {
|
|
401
|
-
return value === undefined ? undefined : structuredClone(value);
|
|
402
|
-
}
|
|
403
|
-
async function ensureCodexHome(paths, env, dryRun) {
|
|
404
|
-
if (env.CODEX_HOME?.trim() && !await pathExists(paths.codexHome)) {
|
|
405
|
-
throw new Error(`CODEX_HOME does not exist: ${paths.codexHome}`);
|
|
406
|
-
}
|
|
407
|
-
if (!dryRun)
|
|
408
|
-
await mkdir(paths.codexHome, { recursive: true, mode: 0o700 });
|
|
409
|
-
}
|
|
410
|
-
async function ensurePrivateDirectory(path) {
|
|
411
|
-
await mkdir(path, { recursive: true, mode: 0o700 });
|
|
412
|
-
if (process.platform !== 'win32')
|
|
413
|
-
await chmod(path, 0o700);
|
|
414
|
-
}
|
|
415
|
-
async function atomicWrite(path, content, mode) {
|
|
416
|
-
const directory = dirname(path);
|
|
417
|
-
await ensurePrivateDirectory(directory);
|
|
418
|
-
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
419
|
-
try {
|
|
420
|
-
await writeFile(temporary, content, { mode, flag: 'wx' });
|
|
421
|
-
await rename(temporary, path);
|
|
422
|
-
if (process.platform !== 'win32')
|
|
423
|
-
await chmod(path, mode);
|
|
424
|
-
}
|
|
425
|
-
catch (error) {
|
|
426
|
-
await unlink(temporary).catch(() => undefined);
|
|
427
|
-
throw error;
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
async function createBackup(paths, backupPath) {
|
|
431
|
-
await ensurePrivateDirectory(paths.backupsDirectory);
|
|
432
|
-
await ensurePrivateDirectory(backupPath);
|
|
433
|
-
const files = {
|
|
434
|
-
config: paths.configPath,
|
|
435
|
-
auth: paths.authPath,
|
|
436
|
-
credentials: paths.credentialsPath,
|
|
437
|
-
helper: paths.helperPath,
|
|
438
|
-
manifest: paths.manifestPath,
|
|
439
|
-
};
|
|
440
|
-
const index = { version: 1, files: {} };
|
|
441
|
-
for (const [name, source] of Object.entries(files)) {
|
|
442
|
-
const content = await readOptionalBuffer(source);
|
|
443
|
-
index.files[name] = { existed: content !== undefined };
|
|
444
|
-
if (content !== undefined)
|
|
445
|
-
await atomicWrite(join(backupPath, name), content, 0o600);
|
|
446
|
-
}
|
|
447
|
-
await atomicWrite(join(backupPath, 'index.json'), `${JSON.stringify(index, null, 2)}\n`, 0o600);
|
|
448
|
-
}
|
|
449
|
-
async function restoreBackup(paths, backupPath, includeConfig, includeAuth = true) {
|
|
450
|
-
const rawIndex = await readFile(join(backupPath, 'index.json'), 'utf8');
|
|
451
|
-
const index = JSON.parse(rawIndex);
|
|
452
|
-
const files = {
|
|
453
|
-
config: paths.configPath,
|
|
454
|
-
auth: paths.authPath,
|
|
455
|
-
credentials: paths.credentialsPath,
|
|
456
|
-
helper: paths.helperPath,
|
|
457
|
-
manifest: paths.manifestPath,
|
|
458
|
-
};
|
|
459
|
-
for (const [name, target] of Object.entries(files)) {
|
|
460
|
-
if (name === 'config' && !includeConfig)
|
|
461
|
-
continue;
|
|
462
|
-
if (name === 'auth' && !includeAuth)
|
|
463
|
-
continue;
|
|
464
|
-
const fileState = index.files[name];
|
|
465
|
-
// Version 0.1.0 did not manage Codex auth.json, so its backup index has no auth entry.
|
|
466
|
-
if (!fileState && name === 'auth')
|
|
467
|
-
continue;
|
|
468
|
-
if (!fileState)
|
|
469
|
-
throw new Error(`Backup index is missing ${name}`);
|
|
470
|
-
if (!fileState.existed) {
|
|
471
|
-
await unlink(target).catch((error) => {
|
|
472
|
-
if (error.code !== 'ENOENT')
|
|
473
|
-
throw error;
|
|
474
|
-
});
|
|
475
|
-
continue;
|
|
476
|
-
}
|
|
477
|
-
const mode = name === 'helper' ? 0o700 : 0o600;
|
|
478
|
-
await atomicWrite(target, await readFile(join(backupPath, name)), mode);
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
async function prepareCodexAuthRestoration(paths, backupPath, expectedKeyHash) {
|
|
482
|
-
const current = await readCodexAuth(paths.authPath);
|
|
483
|
-
const currentKey = current?.OPENAI_API_KEY;
|
|
484
|
-
if (typeof currentKey !== 'string' || secretHash(currentKey) !== expectedKeyHash) {
|
|
485
|
-
throw new Error('Codex OPENAI_API_KEY changed after setup; refusing to overwrite it during rollback');
|
|
486
|
-
}
|
|
487
|
-
if (!current)
|
|
488
|
-
throw new Error('Codex auth.json is missing during rollback');
|
|
489
|
-
const rawIndex = await readFile(join(backupPath, 'index.json'), 'utf8');
|
|
490
|
-
const index = JSON.parse(rawIndex);
|
|
491
|
-
const priorState = index.files.auth;
|
|
492
|
-
if (!priorState)
|
|
493
|
-
throw new Error('Backup index is missing auth');
|
|
494
|
-
const priorRaw = priorState.existed ? await readFile(join(backupPath, 'auth'), 'utf8') : undefined;
|
|
495
|
-
const prior = priorRaw === undefined ? {} : JSON.parse(priorRaw);
|
|
496
|
-
const currentUnrelated = cloneRecord(current);
|
|
497
|
-
const priorUnrelated = cloneRecord(prior);
|
|
498
|
-
delete currentUnrelated.OPENAI_API_KEY;
|
|
499
|
-
delete priorUnrelated.OPENAI_API_KEY;
|
|
500
|
-
if (isDeepStrictEqual(currentUnrelated, priorUnrelated))
|
|
501
|
-
return { content: priorRaw };
|
|
502
|
-
const restored = cloneRecord(current);
|
|
503
|
-
if (typeof prior.OPENAI_API_KEY === 'string')
|
|
504
|
-
restored.OPENAI_API_KEY = prior.OPENAI_API_KEY;
|
|
505
|
-
else
|
|
506
|
-
delete restored.OPENAI_API_KEY;
|
|
507
|
-
return Object.keys(restored).length === 0
|
|
508
|
-
? {}
|
|
509
|
-
: { content: `${JSON.stringify(restored, null, 2)}\n` };
|
|
510
|
-
}
|
|
511
|
-
async function applyCodexAuthRestoration(path, restoration) {
|
|
512
|
-
if (restoration.content !== undefined) {
|
|
513
|
-
await atomicWrite(path, restoration.content, 0o600);
|
|
514
|
-
return;
|
|
515
|
-
}
|
|
516
|
-
await unlink(path).catch((error) => {
|
|
517
|
-
if (error.code !== 'ENOENT')
|
|
518
|
-
throw error;
|
|
519
|
-
});
|
|
520
|
-
}
|
|
521
|
-
async function backupFileExisted(backupPath, name) {
|
|
522
|
-
const rawIndex = await readFile(join(backupPath, 'index.json'), 'utf8');
|
|
523
|
-
const index = JSON.parse(rawIndex);
|
|
524
|
-
const fileState = index.files[name];
|
|
525
|
-
if (!fileState)
|
|
526
|
-
throw new Error(`Backup index is missing ${name}`);
|
|
527
|
-
return fileState.existed;
|
|
528
|
-
}
|
|
529
|
-
async function nextCodexAuth(path, apiKey) {
|
|
530
|
-
return {
|
|
531
|
-
...(await readCodexAuth(path) ?? {}),
|
|
532
|
-
OPENAI_API_KEY: apiKey,
|
|
533
|
-
};
|
|
534
|
-
}
|
|
535
|
-
async function readCodexAuth(path) {
|
|
536
|
-
const raw = await readOptionalText(path);
|
|
537
|
-
if (raw === undefined)
|
|
538
|
-
return undefined;
|
|
539
|
-
let parsed;
|
|
540
|
-
try {
|
|
541
|
-
parsed = JSON.parse(raw);
|
|
542
|
-
}
|
|
543
|
-
catch (error) {
|
|
544
|
-
throw new Error(`Unable to parse Codex auth.json: ${errorMessage(error)}`);
|
|
545
|
-
}
|
|
546
|
-
const record = asRecord(parsed);
|
|
547
|
-
if (!record)
|
|
548
|
-
throw new Error('Codex auth.json must contain a JSON object');
|
|
549
|
-
if (record.OPENAI_API_KEY !== undefined && typeof record.OPENAI_API_KEY !== 'string') {
|
|
550
|
-
throw new Error('Codex auth.json OPENAI_API_KEY must be a string');
|
|
551
|
-
}
|
|
552
|
-
return record;
|
|
553
|
-
}
|
|
554
|
-
async function readStoredCredentials(path) {
|
|
555
|
-
const raw = await readOptionalText(path);
|
|
556
|
-
if (raw === undefined)
|
|
557
|
-
return undefined;
|
|
558
|
-
let parsed;
|
|
559
|
-
try {
|
|
560
|
-
parsed = JSON.parse(raw);
|
|
561
|
-
}
|
|
562
|
-
catch (error) {
|
|
563
|
-
throw new Error(`Unable to parse BOFT Codex credentials: ${errorMessage(error)}`);
|
|
564
|
-
}
|
|
565
|
-
const record = asRecord(parsed);
|
|
566
|
-
const profiles = asRecord(record?.profiles);
|
|
567
|
-
if (record?.version !== 1 || !profiles)
|
|
568
|
-
throw new Error('BOFT Codex credentials have an invalid format');
|
|
569
|
-
for (const profile of Object.values(profiles)) {
|
|
570
|
-
const item = asRecord(profile);
|
|
571
|
-
if (!item || typeof item.api_key !== 'string' || typeof item.updated_at !== 'string') {
|
|
572
|
-
throw new Error('BOFT Codex credentials have an invalid profile');
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
return parsed;
|
|
576
|
-
}
|
|
577
|
-
async function readManifest(path) {
|
|
578
|
-
const raw = await readOptionalText(path);
|
|
579
|
-
if (raw === undefined)
|
|
580
|
-
return undefined;
|
|
581
|
-
let parsed;
|
|
582
|
-
try {
|
|
583
|
-
parsed = JSON.parse(raw);
|
|
584
|
-
}
|
|
585
|
-
catch (error) {
|
|
586
|
-
throw new Error(`Unable to parse BOFT Codex manifest: ${errorMessage(error)}`);
|
|
587
|
-
}
|
|
588
|
-
const record = asRecord(parsed);
|
|
589
|
-
if (record?.version !== 1 ||
|
|
590
|
-
(record.provider_id !== CODEX_PROVIDER_ID && record.provider_id !== LEGACY_CODEX_PROVIDER_ID) ||
|
|
591
|
-
typeof record.backup_id !== 'string' || typeof record.config_path !== 'string' ||
|
|
592
|
-
(record.auth_key_hash !== undefined && typeof record.auth_key_hash !== 'string') ||
|
|
593
|
-
!asRecord(record.previous) || !asRecord(record.applied)) {
|
|
594
|
-
throw new Error('BOFT Codex manifest has an invalid format');
|
|
595
|
-
}
|
|
596
|
-
return parsed;
|
|
597
|
-
}
|
|
598
|
-
function secretHash(value) {
|
|
599
|
-
return createHash('sha256').update(value).digest('hex');
|
|
600
|
-
}
|
|
601
|
-
function validateSecret(value, label) {
|
|
602
|
-
const normalized = value.trim();
|
|
603
|
-
if (!normalized || normalized.length > 4096 || containsControlCharacter(normalized)) {
|
|
604
|
-
throw new Error(`${label} must contain 1-4096 printable characters`);
|
|
605
|
-
}
|
|
606
|
-
return normalized;
|
|
607
|
-
}
|
|
608
|
-
function containsControlCharacter(value) {
|
|
609
|
-
return [...value].some((character) => {
|
|
610
|
-
const code = character.codePointAt(0) ?? 0;
|
|
611
|
-
return code <= 31 || code === 127;
|
|
612
|
-
});
|
|
613
|
-
}
|
|
614
|
-
function backupIdentifier() {
|
|
615
|
-
return `${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID()}`;
|
|
616
|
-
}
|
|
617
|
-
function ensureTrailingNewline(value) {
|
|
618
|
-
return value.endsWith('\n') ? value : `${value}\n`;
|
|
619
|
-
}
|
|
620
|
-
async function readOptionalText(path) {
|
|
621
|
-
try {
|
|
622
|
-
return await readFile(path, 'utf8');
|
|
623
|
-
}
|
|
624
|
-
catch (error) {
|
|
625
|
-
if (error.code === 'ENOENT')
|
|
626
|
-
return undefined;
|
|
627
|
-
throw error;
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
async function readOptionalBuffer(path) {
|
|
631
|
-
try {
|
|
632
|
-
return await readFile(path);
|
|
633
|
-
}
|
|
634
|
-
catch (error) {
|
|
635
|
-
if (error.code === 'ENOENT')
|
|
636
|
-
return undefined;
|
|
637
|
-
throw error;
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
async function pathExists(path) {
|
|
641
|
-
try {
|
|
642
|
-
await stat(path);
|
|
643
|
-
return true;
|
|
644
|
-
}
|
|
645
|
-
catch (error) {
|
|
646
|
-
if (error.code === 'ENOENT')
|
|
647
|
-
return false;
|
|
648
|
-
throw error;
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
async function checkOwnerOnlyMode(path, forbiddenBits, label, issues) {
|
|
652
|
-
try {
|
|
653
|
-
if (((await stat(path)).mode & forbiddenBits) !== 0)
|
|
654
|
-
issues.push(`BOFT Codex ${label} permissions are too broad`);
|
|
655
|
-
}
|
|
656
|
-
catch (error) {
|
|
657
|
-
if (error.code !== 'ENOENT')
|
|
658
|
-
throw error;
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
|
-
function errorMessage(error) {
|
|
662
|
-
return error instanceof Error ? error.message : String(error);
|
|
663
|
-
}
|
|
664
|
-
//# sourceMappingURL=codex.js.map
|