@minniexcode/codex-switch 0.0.5 → 0.0.7

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 (71) hide show
  1. package/README.AI.md +5 -2
  2. package/README.md +44 -100
  3. package/dist/app/add-provider.js +28 -4
  4. package/dist/app/edit-provider.js +47 -19
  5. package/dist/app/export-providers.js +2 -2
  6. package/dist/app/get-current-profile.js +1 -1
  7. package/dist/app/get-status.js +10 -3
  8. package/dist/app/import-providers.js +15 -7
  9. package/dist/app/init-codex.js +68 -0
  10. package/dist/app/list-backups.js +1 -1
  11. package/dist/app/list-config-profiles.js +3 -2
  12. package/dist/app/list-providers.js +2 -1
  13. package/dist/app/remove-provider.js +2 -2
  14. package/dist/app/rollback-backup.js +1 -1
  15. package/dist/app/rollback-latest.js +1 -1
  16. package/dist/app/run-doctor.js +83 -6
  17. package/dist/app/run-mutation.js +2 -2
  18. package/dist/app/setup-codex.js +21 -12
  19. package/dist/app/show-config.js +11 -3
  20. package/dist/app/show-provider.js +1 -1
  21. package/dist/app/switch-provider.js +16 -9
  22. package/dist/cli/add-interactive.js +7 -104
  23. package/dist/cli/args.js +6 -135
  24. package/dist/cli/help.js +8 -313
  25. package/dist/cli/interactive.js +17 -225
  26. package/dist/cli/output.js +21 -6
  27. package/dist/cli/prompt.js +4 -106
  28. package/dist/cli.js +10 -404
  29. package/dist/commands/args.js +132 -0
  30. package/dist/commands/dispatch.js +16 -0
  31. package/dist/commands/handlers.js +460 -0
  32. package/dist/commands/help.js +120 -0
  33. package/dist/commands/registry.js +351 -0
  34. package/dist/commands/types.js +2 -0
  35. package/dist/domain/config.js +235 -21
  36. package/dist/domain/providers.js +16 -2
  37. package/dist/domain/setup.js +1 -0
  38. package/dist/infra/backup-repo.js +9 -206
  39. package/dist/infra/codex-cli.js +9 -126
  40. package/dist/infra/codex-paths.js +6 -67
  41. package/dist/infra/config-repo.js +59 -0
  42. package/dist/infra/fs-utils.js +8 -93
  43. package/dist/infra/lock-repo.js +4 -95
  44. package/dist/infra/providers-repo.js +8 -94
  45. package/dist/interaction/add-interactive.js +99 -0
  46. package/dist/interaction/interactive.js +289 -0
  47. package/dist/interaction/prompt.js +110 -0
  48. package/dist/runtime/codex-cli.js +130 -0
  49. package/dist/runtime/codex-probe.js +57 -0
  50. package/dist/runtime/types.js +2 -0
  51. package/dist/storage/auth-repo.js +160 -0
  52. package/dist/storage/backup-repo.js +210 -0
  53. package/dist/storage/codex-paths.js +71 -0
  54. package/dist/storage/config-repo.js +266 -0
  55. package/dist/storage/fs-utils.js +97 -0
  56. package/dist/storage/lock-repo.js +99 -0
  57. package/dist/storage/providers-repo.js +98 -0
  58. package/docs/Design/codex-switch-v0.0.5-design.md +32 -22
  59. package/docs/Design/codex-switch-v0.0.6-design.md +708 -0
  60. package/docs/Design/codex-switch-v0.0.7-design.md +862 -0
  61. package/docs/PRD/codex-switch-prd-v0.0.5-to-v0.1.0.md +227 -89
  62. package/docs/PRD/codex-switch-prd-v0.1.0.md +200 -226
  63. package/docs/PRD/codex-switch-prd.md +1 -1
  64. package/docs/Reference/codex-config-reference.md +604 -0
  65. package/docs/Reference/codex-config-reference.zh-CN.md +633 -0
  66. package/docs/cli-usage.md +78 -29
  67. package/docs/codex-switch-technical-architecture.md +73 -4
  68. package/docs/test-report-0.0.5.md +163 -0
  69. package/docs/test-report-0.0.7.md +118 -0
  70. package/docs/testing.md +151 -0
  71. package/package.json +1 -1
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CODEX_DIR_ENV_NAME = void 0;
37
+ exports.resolveCodexDir = resolveCodexDir;
38
+ exports.createCodexPaths = createCodexPaths;
39
+ const os = __importStar(require("node:os"));
40
+ const path = __importStar(require("node:path"));
41
+ exports.CODEX_DIR_ENV_NAME = "CODEXS_CODEX_DIR";
42
+ const DEVELOPMENT_DEFAULT_CODEX_DIR = path.resolve(process.cwd(), "dev-codex", "local-sandbox");
43
+ /**
44
+ * Resolves the working Codex directory, defaulting to `~/.codex`.
45
+ */
46
+ function resolveCodexDir(codexDir) {
47
+ if (codexDir) {
48
+ return path.resolve(codexDir);
49
+ }
50
+ const envCodexDir = process.env[exports.CODEX_DIR_ENV_NAME];
51
+ if (envCodexDir) {
52
+ return path.resolve(envCodexDir);
53
+ }
54
+ if (process.env.NODE_ENV === "development") {
55
+ return DEVELOPMENT_DEFAULT_CODEX_DIR;
56
+ }
57
+ return path.join(os.homedir(), ".codex");
58
+ }
59
+ /**
60
+ * Expands a Codex home directory into the file paths used by the CLI.
61
+ */
62
+ function createCodexPaths(codexDir) {
63
+ return {
64
+ codexDir,
65
+ configPath: path.join(codexDir, "config.toml"),
66
+ providersPath: path.join(codexDir, "providers.json"),
67
+ authPath: path.join(codexDir, "auth.json"),
68
+ backupsDir: path.join(codexDir, "backups"),
69
+ latestBackupPath: path.join(codexDir, "backups", "latest.json"),
70
+ };
71
+ }
@@ -0,0 +1,266 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.readConfigFile = readConfigFile;
37
+ exports.readStructuredConfig = readStructuredConfig;
38
+ exports.readCurrentProfile = readCurrentProfile;
39
+ exports.listConfigProfiles = listConfigProfiles;
40
+ exports.ensureProfileExists = ensureProfileExists;
41
+ exports.requireManagedProfileRuntime = requireManagedProfileRuntime;
42
+ exports.requireModelProviderRuntimeSection = requireModelProviderRuntimeSection;
43
+ exports.requireRuntimeEnvKey = requireRuntimeEnvKey;
44
+ exports.resolveActiveProviderName = resolveActiveProviderName;
45
+ exports.updateTopLevelProfile = updateTopLevelProfile;
46
+ exports.createConfigMutationPlan = createConfigMutationPlan;
47
+ exports.applyConfigMutation = applyConfigMutation;
48
+ exports.findCodexDirCandidates = findCodexDirCandidates;
49
+ const fs = __importStar(require("node:fs"));
50
+ const os = __importStar(require("node:os"));
51
+ const path = __importStar(require("node:path"));
52
+ const config_1 = require("../domain/config");
53
+ const errors_1 = require("../domain/errors");
54
+ const providers_1 = require("../domain/providers");
55
+ const codex_paths_1 = require("./codex-paths");
56
+ const fs_utils_1 = require("./fs-utils");
57
+ /**
58
+ * Reads config.toml and throws a typed error when the file is missing.
59
+ */
60
+ function readConfigFile(configPath) {
61
+ return (0, fs_utils_1.readRequiredFile)(configPath, "CONFIG_NOT_FOUND", "config.toml");
62
+ }
63
+ /**
64
+ * Reads and parses config.toml into the managed structured document shape.
65
+ */
66
+ function readStructuredConfig(configPath) {
67
+ const content = readConfigFile(configPath);
68
+ try {
69
+ return (0, config_1.parseStructuredConfig)(content);
70
+ }
71
+ catch (error) {
72
+ throw (0, errors_1.cliError)("CONFIG_PARSE_ERROR", "Failed to parse config.toml.", {
73
+ file: configPath,
74
+ cause: (0, errors_1.normalizeError)(error).message,
75
+ });
76
+ }
77
+ }
78
+ /**
79
+ * Reads the active top-level profile from config.toml.
80
+ */
81
+ function readCurrentProfile(configPath) {
82
+ const profile = readStructuredConfig(configPath).activeProfile ?? (0, config_1.parseTopLevelProfile)(readConfigFile(configPath));
83
+ if (!profile) {
84
+ throw (0, errors_1.cliError)("PROFILE_NOT_FOUND", "No top-level profile is set in config.toml.", {
85
+ file: configPath,
86
+ });
87
+ }
88
+ return profile;
89
+ }
90
+ /**
91
+ * Lists all named profile sections declared in config.toml.
92
+ */
93
+ function listConfigProfiles(configPath) {
94
+ return new Set(readStructuredConfig(configPath).profiles.map((profile) => profile.name));
95
+ }
96
+ /**
97
+ * Verifies that a provider's target profile exists before a switch operation proceeds.
98
+ */
99
+ function ensureProfileExists(configPath, profile, provider) {
100
+ const document = readStructuredConfig(configPath);
101
+ if (!document.profiles.some((entry) => entry.name === profile)) {
102
+ throw (0, errors_1.cliError)("PROFILE_NOT_FOUND", `Profile "${profile}" does not exist in config.toml.`, {
103
+ file: configPath,
104
+ provider,
105
+ profile,
106
+ });
107
+ }
108
+ return document;
109
+ }
110
+ /**
111
+ * Resolves one profile view and enforces the managed model_provider contract.
112
+ */
113
+ function requireManagedProfileRuntime(document, providers, profile) {
114
+ const view = (0, config_1.buildManagedProfileViews)(document, providers).find((entry) => entry.name === profile);
115
+ if (!view) {
116
+ throw (0, errors_1.cliError)("PROFILE_NOT_FOUND", `Profile "${profile}" does not exist in config.toml.`, {
117
+ profile,
118
+ });
119
+ }
120
+ if (!view.modelProvider) {
121
+ throw (0, errors_1.cliError)("MANAGED_PROFILE_FIELDS_MISSING", `Managed profile "${profile}" requires model_provider.`, {
122
+ profile,
123
+ missingFields: ["model_provider"],
124
+ });
125
+ }
126
+ if (view.modelProvider !== profile) {
127
+ throw (0, errors_1.cliError)("INVALID_ARGUMENT", `Managed profile "${profile}" must use the same model_provider name.`, {
128
+ profile,
129
+ modelProvider: view.modelProvider,
130
+ });
131
+ }
132
+ const modelProviderSection = document.modelProviders.find((entry) => entry.name === view.modelProvider);
133
+ if (!modelProviderSection) {
134
+ throw (0, errors_1.cliError)("PROFILE_NOT_FOUND", `Model provider "${view.modelProvider}" does not exist in config.toml.`, {
135
+ profile,
136
+ modelProvider: view.modelProvider,
137
+ });
138
+ }
139
+ if (!modelProviderSection.baseUrl) {
140
+ throw (0, errors_1.cliError)("MANAGED_PROFILE_FIELDS_MISSING", `Model provider "${view.modelProvider}" requires base_url.`, {
141
+ profile,
142
+ modelProvider: view.modelProvider,
143
+ missingFields: ["base_url"],
144
+ });
145
+ }
146
+ if (!modelProviderSection.envKey) {
147
+ throw (0, errors_1.cliError)("MODEL_PROVIDER_ENV_KEY_MISSING", `Model provider "${view.modelProvider}" requires env_key.`, {
148
+ profile,
149
+ modelProvider: view.modelProvider,
150
+ missingFields: ["env_key"],
151
+ });
152
+ }
153
+ return view;
154
+ }
155
+ /**
156
+ * Verifies that a same-named model_provider runtime section exists and has base_url.
157
+ */
158
+ function requireModelProviderRuntimeSection(document, profile) {
159
+ const modelProviderSection = document.modelProviders.find((entry) => entry.name === profile);
160
+ if (!modelProviderSection) {
161
+ throw (0, errors_1.cliError)("PROFILE_NOT_FOUND", `Model provider "${profile}" does not exist in config.toml.`, {
162
+ profile,
163
+ modelProvider: profile,
164
+ });
165
+ }
166
+ if (!modelProviderSection.baseUrl) {
167
+ throw (0, errors_1.cliError)("MANAGED_PROFILE_FIELDS_MISSING", `Model provider "${profile}" requires base_url.`, {
168
+ profile,
169
+ modelProvider: profile,
170
+ missingFields: ["base_url"],
171
+ });
172
+ }
173
+ if (!modelProviderSection.envKey) {
174
+ throw (0, errors_1.cliError)("MODEL_PROVIDER_ENV_KEY_MISSING", `Model provider "${profile}" requires env_key.`, {
175
+ profile,
176
+ modelProvider: profile,
177
+ missingFields: ["env_key"],
178
+ });
179
+ }
180
+ }
181
+ /**
182
+ * Returns the runtime env_key for one profile or throws a typed error.
183
+ */
184
+ function requireRuntimeEnvKey(document, profile) {
185
+ const modelProviderSection = document.modelProviders.find((entry) => entry.name === profile);
186
+ if (!modelProviderSection) {
187
+ throw (0, errors_1.cliError)("PROFILE_NOT_FOUND", `Model provider "${profile}" does not exist in config.toml.`, {
188
+ profile,
189
+ modelProvider: profile,
190
+ });
191
+ }
192
+ if (!modelProviderSection.envKey) {
193
+ throw (0, errors_1.cliError)("MODEL_PROVIDER_ENV_KEY_MISSING", `Model provider "${profile}" requires env_key.`, {
194
+ profile,
195
+ modelProvider: profile,
196
+ missingFields: ["env_key"],
197
+ });
198
+ }
199
+ return modelProviderSection.envKey;
200
+ }
201
+ /**
202
+ * Resolves the current active provider and requires the mapping to be unique.
203
+ */
204
+ function resolveActiveProviderName(document, providers) {
205
+ if (!document.activeProfile) {
206
+ throw (0, errors_1.cliError)("PROFILE_NOT_FOUND", "No top-level profile is set in config.toml.");
207
+ }
208
+ const matches = (0, providers_1.findProvidersByProfile)(providers, document.activeProfile);
209
+ if (matches.length === 0) {
210
+ throw (0, errors_1.cliError)("UNMANAGED_ACTIVE_PROFILE", `Active profile "${document.activeProfile}" is not mapped by providers.json.`, {
211
+ profile: document.activeProfile,
212
+ });
213
+ }
214
+ if (matches.length > 1) {
215
+ throw (0, errors_1.cliError)("ACTIVE_PROVIDER_UNRESOLVED", `Active profile "${document.activeProfile}" maps to multiple providers.`, {
216
+ profile: document.activeProfile,
217
+ providers: matches,
218
+ });
219
+ }
220
+ return matches[0];
221
+ }
222
+ /**
223
+ * Rewrites config.toml so the requested profile becomes the active top-level profile.
224
+ */
225
+ function updateTopLevelProfile(configPath, configContent, profile) {
226
+ (0, fs_utils_1.writeTextFileAtomic)(configPath, (0, config_1.applyPatchOperations)(configContent, (0, config_1.planConfigMutation)((0, config_1.parseStructuredConfig)(configContent), {
227
+ setActiveProfile: profile,
228
+ }).operations));
229
+ }
230
+ /**
231
+ * Exposes the config mutation planner to application services.
232
+ */
233
+ function createConfigMutationPlan(document, args) {
234
+ return (0, config_1.planConfigMutation)(document, args);
235
+ }
236
+ /**
237
+ * Applies a previously generated mutation plan to config.toml in one write.
238
+ */
239
+ function applyConfigMutation(configPath, document, plan) {
240
+ (0, fs_utils_1.writeTextFileAtomic)(configPath, (0, config_1.applyPatchOperations)(document.rawText, plan.operations));
241
+ }
242
+ /**
243
+ * Finds candidate Codex directories in a stable, non-recursive order.
244
+ */
245
+ function findCodexDirCandidates(explicitCodexDir) {
246
+ if (explicitCodexDir) {
247
+ return [(0, codex_paths_1.resolveCodexDir)(explicitCodexDir)];
248
+ }
249
+ const candidates = new Set();
250
+ const ordered = [];
251
+ const envCandidate = process.env[codex_paths_1.CODEX_DIR_ENV_NAME];
252
+ if (envCandidate) {
253
+ ordered.push((0, codex_paths_1.resolveCodexDir)(envCandidate));
254
+ }
255
+ if (process.env.NODE_ENV === "development") {
256
+ ordered.push(path.resolve(process.cwd(), "dev-codex", "local-sandbox"));
257
+ }
258
+ ordered.push(path.join(os.homedir(), ".codex"));
259
+ for (const candidate of ordered) {
260
+ if (!candidate || candidates.has(candidate) || !fs.existsSync(candidate)) {
261
+ continue;
262
+ }
263
+ candidates.add(candidate);
264
+ }
265
+ return [...candidates];
266
+ }
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ensureDir = ensureDir;
37
+ exports.writeTextFileAtomic = writeTextFileAtomic;
38
+ exports.readRequiredFile = readRequiredFile;
39
+ exports.formatDetail = formatDetail;
40
+ exports.printErrorDetails = printErrorDetails;
41
+ const fs = __importStar(require("node:fs"));
42
+ const path = __importStar(require("node:path"));
43
+ const errors_1 = require("../domain/errors");
44
+ /**
45
+ * Creates a directory tree when it does not already exist.
46
+ */
47
+ function ensureDir(directoryPath) {
48
+ fs.mkdirSync(directoryPath, { recursive: true });
49
+ }
50
+ /**
51
+ * Writes a text file via a temporary sibling file and atomic rename.
52
+ */
53
+ function writeTextFileAtomic(filePath, contents) {
54
+ ensureDir(path.dirname(filePath));
55
+ // Use the current process id in the temp name to reduce collision risk.
56
+ const tempPath = `${filePath}.tmp-${process.pid}`;
57
+ fs.writeFileSync(tempPath, contents, "utf8");
58
+ fs.renameSync(tempPath, filePath);
59
+ }
60
+ /**
61
+ * Reads a required text file and throws a typed error when it is missing.
62
+ */
63
+ function readRequiredFile(filePath, code, label) {
64
+ if (!fs.existsSync(filePath)) {
65
+ throw (0, errors_1.cliError)(code, `${label} does not exist.`, { file: filePath });
66
+ }
67
+ return fs.readFileSync(filePath, "utf8");
68
+ }
69
+ /**
70
+ * Formats arbitrary error detail values for human-readable output.
71
+ */
72
+ function formatDetail(value) {
73
+ if (Array.isArray(value)) {
74
+ return value.join(", ");
75
+ }
76
+ if (value && typeof value === "object") {
77
+ return JSON.stringify(value);
78
+ }
79
+ return String(value);
80
+ }
81
+ /**
82
+ * Renders structured error details while suppressing secret-looking API key fields.
83
+ */
84
+ function printErrorDetails(error) {
85
+ if (!error.details) {
86
+ return [];
87
+ }
88
+ const lines = [];
89
+ for (const [key, value] of Object.entries(error.details)) {
90
+ if (typeof value === "string" && key.toLowerCase().includes("apikey")) {
91
+ // Do not leak API keys back into the terminal if one appears in error details.
92
+ continue;
93
+ }
94
+ lines.push(` ${key}: ${formatDetail(value)}`);
95
+ }
96
+ return lines;
97
+ }
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.withCodexLock = withCodexLock;
37
+ const fs = __importStar(require("node:fs"));
38
+ const path = __importStar(require("node:path"));
39
+ const errors_1 = require("../domain/errors");
40
+ const fs_utils_1 = require("./fs-utils");
41
+ /**
42
+ * Executes a mutation while holding an exclusive codex-switch lock file.
43
+ */
44
+ function withCodexLock(codexDir, operation, run) {
45
+ (0, fs_utils_1.ensureDir)(codexDir);
46
+ const lockPath = path.join(codexDir, ".codex-switch.lock");
47
+ acquireLock(lockPath, operation);
48
+ try {
49
+ return run();
50
+ }
51
+ finally {
52
+ releaseLock(lockPath);
53
+ }
54
+ }
55
+ /**
56
+ * Acquires the lock file using exclusive create semantics.
57
+ */
58
+ function acquireLock(lockPath, operation) {
59
+ const payload = {
60
+ pid: process.pid,
61
+ operation,
62
+ createdAt: new Date().toISOString(),
63
+ };
64
+ try {
65
+ fs.writeFileSync(lockPath, `${JSON.stringify(payload, null, 2)}\n`, { encoding: "utf8", flag: "wx" });
66
+ }
67
+ catch {
68
+ const existing = readLockRecord(lockPath);
69
+ throw (0, errors_1.cliError)("LOCK_CONFLICT", "Another codex-switch write operation is already running.", {
70
+ file: lockPath,
71
+ activeOperation: existing?.operation ?? "unknown",
72
+ activePid: existing?.pid ?? null,
73
+ activeSince: existing?.createdAt ?? null,
74
+ requestedOperation: operation,
75
+ });
76
+ }
77
+ }
78
+ /**
79
+ * Removes the lock file when the mutation completes.
80
+ */
81
+ function releaseLock(lockPath) {
82
+ if (fs.existsSync(lockPath)) {
83
+ fs.rmSync(lockPath, { force: true });
84
+ }
85
+ }
86
+ /**
87
+ * Reads the current lock metadata when a lock conflict occurs.
88
+ */
89
+ function readLockRecord(lockPath) {
90
+ if (!fs.existsSync(lockPath)) {
91
+ return null;
92
+ }
93
+ try {
94
+ return JSON.parse(fs.readFileSync(lockPath, "utf8"));
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ }
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.readProvidersFile = readProvidersFile;
37
+ exports.readProvidersFileIfExists = readProvidersFileIfExists;
38
+ exports.writeProvidersFile = writeProvidersFile;
39
+ exports.readProviderRecord = readProviderRecord;
40
+ exports.mergeProviders = mergeProviders;
41
+ const fs = __importStar(require("node:fs"));
42
+ const errors_1 = require("../domain/errors");
43
+ const providers_1 = require("../domain/providers");
44
+ const fs_utils_1 = require("./fs-utils");
45
+ /**
46
+ * Reads and validates providers.json from disk.
47
+ */
48
+ function readProvidersFile(providersPath) {
49
+ const raw = (0, fs_utils_1.readRequiredFile)(providersPath, "PROVIDERS_NOT_FOUND", "providers.json");
50
+ try {
51
+ return (0, providers_1.validateProvidersShape)(JSON.parse(raw));
52
+ }
53
+ catch (error) {
54
+ throw (0, errors_1.cliError)("PROVIDERS_PARSE_ERROR", "Failed to parse providers.json.", {
55
+ file: providersPath,
56
+ cause: (0, errors_1.normalizeError)(error).message,
57
+ });
58
+ }
59
+ }
60
+ /**
61
+ * Reads providers.json when it exists, otherwise returns an empty registry.
62
+ */
63
+ function readProvidersFileIfExists(providersPath) {
64
+ return fs.existsSync(providersPath) ? readProvidersFile(providersPath) : { providers: {} };
65
+ }
66
+ /**
67
+ * Persists providers.json using deterministic key ordering.
68
+ */
69
+ function writeProvidersFile(providersPath, providers) {
70
+ (0, fs_utils_1.writeTextFileAtomic)(providersPath, `${JSON.stringify((0, providers_1.sortProviders)(providers), null, 2)}\n`);
71
+ }
72
+ /**
73
+ * Returns a single provider record or throws a typed not-found error.
74
+ */
75
+ function readProviderRecord(providersPath, providerName) {
76
+ const providers = readProvidersFile(providersPath);
77
+ const record = providers.providers[providerName];
78
+ if (!record) {
79
+ throw (0, errors_1.cliError)("PROVIDER_NOT_FOUND", `Provider "${providerName}" was not found.`, {
80
+ provider: providerName,
81
+ file: providersPath,
82
+ });
83
+ }
84
+ return record;
85
+ }
86
+ /**
87
+ * Merges imported providers into the current registry, preferring the imported side on conflicts.
88
+ */
89
+ function mergeProviders(current, imported) {
90
+ const providers = {};
91
+ for (const [name, record] of Object.entries(current.providers)) {
92
+ providers[name] = (0, providers_1.cleanProviderRecord)(record);
93
+ }
94
+ for (const [name, record] of Object.entries(imported.providers)) {
95
+ providers[name] = (0, providers_1.cleanProviderRecord)(record);
96
+ }
97
+ return (0, providers_1.sortProviders)({ providers });
98
+ }