t3-auto-build 1.0.1 → 2.0.1

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/lib/plans.mjs ADDED
@@ -0,0 +1,318 @@
1
+ // Subscription catalog and ladder resolution. Pure: no fs, no child_process.
2
+ import { RETIRED_MODELS, matchRetired } from '../hooks/_shared.mjs';
3
+
4
+ export { RETIRED_MODELS, matchRetired };
5
+
6
+ export const PROVIDERS = ['claude', 'codex', 'antigravity'];
7
+ export const POOLS = ['standard', 'fable', 'astra', 'third-party-claude'];
8
+ export const PARENTS = { sonnet: 'claude-sonnet-5-5', opus: 'claude-opus-5-5', fable: 'claude-fable-5-2' };
9
+
10
+ const ROLES = ['triage', 'planner', 'builder', 'tester', 'auditor'];
11
+ const DISPLAY = { claude: 'Claude', codex: 'Codex', antigravity: 'Antigravity' };
12
+ const PARENT_EFFORT = 'medium';
13
+ const MAX_BUILDERS = 6;
14
+
15
+ function deepFreeze(value) {
16
+ if (value !== null && typeof value === 'object') Object.values(value).forEach(deepFreeze);
17
+ return Object.freeze(value);
18
+ }
19
+
20
+ const model = (provider, family, version, pool = 'standard') =>
21
+ ({ provider, family, version, pool, scarceQuota: pool !== 'standard' });
22
+
23
+ export const MODELS = deepFreeze({
24
+ 'claude-haiku-5-5': model('claude', 'claude-haiku', '5.5'),
25
+ 'claude-sonnet-5-5': model('claude', 'claude-sonnet', '5.5'),
26
+ 'claude-opus-5-5': model('claude', 'claude-opus', '5.5'),
27
+ 'claude-fable-5-2': model('claude', 'claude-fable', '5.2', 'fable'),
28
+ 'gpt-6-luna': model('codex', 'gpt-luna', '6'),
29
+ 'gpt-6.1-terra': model('codex', 'gpt-terra', '6.1'),
30
+ 'gpt-6.1-sol': model('codex', 'gpt-sol', '6.1'),
31
+ 'gpt-6-astra': model('codex', 'gpt-astra', '6', 'astra'),
32
+ 'gpt-5.6-terra': model('codex', 'gpt-terra', '5.6'),
33
+ 'gpt-5.6-luna': model('codex', 'gpt-luna', '5.6'),
34
+ 'gemini-4-hydrogen': model('antigravity', 'gemini-hydrogen', '4'),
35
+ 'gemini-4-neon': model('antigravity', 'gemini-neon', '4'),
36
+ 'gemini-4-carbon': model('antigravity', 'gemini-carbon', '4'),
37
+ });
38
+
39
+ // Role preference per hosting; a tier keeps the ids it has.
40
+ const PREFERENCE = {
41
+ claude: {
42
+ triage: ['claude-haiku-5-5', 'claude-sonnet-5-5'],
43
+ planner: ['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-fable-5-2'],
44
+ builder: ['claude-sonnet-5-5', 'claude-opus-5-5', 'claude-fable-5-2'],
45
+ tester: ['claude-sonnet-5-5', 'claude-opus-5-5', 'claude-fable-5-2'],
46
+ auditor: ['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-fable-5-2'],
47
+ },
48
+ codex: {
49
+ triage: ['gpt-6-luna', 'gpt-6.1-terra', 'gpt-5.6-luna', 'gpt-5.6-terra'],
50
+ planner: ['gpt-6.1-sol', 'gpt-6.1-terra', 'gpt-5.6-terra', 'gpt-6-luna', 'gpt-5.6-luna', 'gpt-6-astra'],
51
+ builder: ['gpt-6.1-terra', 'gpt-6.1-sol', 'gpt-5.6-terra', 'gpt-6-luna', 'gpt-5.6-luna', 'gpt-6-astra'],
52
+ tester: ['gpt-6-luna', 'gpt-6.1-terra', 'gpt-6.1-sol', 'gpt-5.6-luna', 'gpt-5.6-terra', 'gpt-6-astra'],
53
+ auditor: ['gpt-6.1-sol', 'gpt-6.1-terra', 'gpt-5.6-terra', 'gpt-6-luna', 'gpt-5.6-luna', 'gpt-6-astra'],
54
+ },
55
+ antigravity: {
56
+ triage: ['gemini-4-hydrogen', 'gemini-4-neon'],
57
+ planner: ['gemini-4-carbon', 'gemini-4-neon', 'gemini-4-hydrogen', 'claude-opus-5-5', 'claude-sonnet-5-5'],
58
+ builder: ['gemini-4-neon', 'gemini-4-carbon', 'gemini-4-hydrogen', 'claude-sonnet-5-5', 'claude-opus-5-5'],
59
+ tester: ['gemini-4-neon', 'gemini-4-hydrogen', 'gemini-4-carbon', 'claude-sonnet-5-5', 'claude-opus-5-5'],
60
+ auditor: ['gemini-4-carbon', 'gemini-4-neon', 'gemini-4-hydrogen', 'claude-opus-5-5', 'claude-sonnet-5-5'],
61
+ },
62
+ };
63
+
64
+ const NO_WINDOWS = { fiveHour: false, weekly: false, subCaps: {} };
65
+
66
+ /** Cross-hosted, or from a capped pool: overflow/escalation only. Takes "provider:model[@effort]". */
67
+ function isOverflow(ref) {
68
+ const [provider, rest] = ref.split(':');
69
+ const { provider: native, scarceQuota } = MODELS[rest.split('@')[0]];
70
+ return native !== provider || scarceQuota;
71
+ }
72
+
73
+ function tierLadders(provider, models) {
74
+ const ids = new Set(models.map((m) => m.model));
75
+ return Object.fromEntries(ROLES.map((role) => {
76
+ const refs = PREFERENCE[provider][role].filter((id) => ids.has(id)).map((id) => `${provider}:${id}`);
77
+ const ordered = [...refs.filter((ref) => !isOverflow(ref)), ...refs.filter(isOverflow)];
78
+ return [role, ordered.map((ref, index) => {
79
+ if (isOverflow(ref)) return `${ref}@medium`;
80
+ return role === 'planner' || (role === 'auditor' && index === 0) ? `${ref}@high` : ref;
81
+ })];
82
+ }));
83
+ }
84
+
85
+ function tier(provider, id, label, {
86
+ ids = [], cross = [], builders = 0, warning, usageBilled = false, windows, subCaps = {}, parent, parentOptions = [],
87
+ } = {}) {
88
+ const entry = (name, overrides) => {
89
+ const { family, version, pool, scarceQuota } = MODELS[name];
90
+ return { provider, model: name, pool, scarceQuota, family, version, ...overrides };
91
+ };
92
+ const models = [
93
+ ...ids.map((name) => entry(name)),
94
+ ...cross.map((name) => entry(name, { pool: 'third-party-claude', scarceQuota: true })),
95
+ ];
96
+ const cliSupported = models.length > 0;
97
+ return {
98
+ id,
99
+ label,
100
+ cliSupported,
101
+ warning: warning ?? (cliSupported ? null : `no ${DISPLAY[provider]} subscription selected`),
102
+ usageBilled,
103
+ windows: windows ?? (cliSupported ? { fiveHour: true, weekly: true, subCaps } : NO_WINDOWS),
104
+ parentDefault: parent ? { model: parent, effort: PARENT_EFFORT } : null,
105
+ parentOptions,
106
+ models,
107
+ maxParallelBuilders: builders,
108
+ ladders: tierLadders(provider, models),
109
+ };
110
+ }
111
+
112
+ const API = { usageBilled: true, windows: NO_WINDOWS, warning: 'API usage is billed per token' };
113
+
114
+ // shortcut: builder counts and quota windows are estimates, tune when providers publish per-tier limits.
115
+ function claudeTiers() {
116
+ const base = ['claude-haiku-5-5', 'claude-sonnet-5-5', 'claude-opus-5-5'];
117
+ const all = [...base, 'claude-fable-5-2'];
118
+ const two = ['sonnet', 'opus'];
119
+ const three = [...two, 'fable'];
120
+ const make = (id, label, options) => tier('claude', id, label, options);
121
+ return [
122
+ make('none', 'No Claude plan'),
123
+ make('free', 'Claude Free', { warning: 'Claude Code requires Pro or higher (or api)' }),
124
+ make('pro', 'Claude Pro', { ids: base, parent: 'sonnet', parentOptions: two, builders: 1 }),
125
+ make('max', 'Claude Max', { ids: base, parent: 'opus', parentOptions: two, builders: 2 }),
126
+ make('ultra', 'Claude Ultra', { ids: all, parent: 'opus', parentOptions: three, builders: 3, subCaps: { fable: 'weekly' } }),
127
+ make('team-standard', 'Claude Team Standard', { ids: base, parent: 'sonnet', parentOptions: two, builders: 1 }),
128
+ make('team-premium', 'Claude Team Premium', { ids: base, parent: 'opus', parentOptions: two, builders: 2 }),
129
+ make('api', 'Claude API', { ...API, ids: all, parent: 'opus', parentOptions: three, builders: 3 }),
130
+ ];
131
+ }
132
+
133
+ function codexTiers() {
134
+ const base = ['gpt-6-luna', 'gpt-6.1-terra'];
135
+ const all = [...base, 'gpt-6.1-sol', 'gpt-6-astra'];
136
+ const starter = ['gpt-6-luna', 'gpt-5.6-terra', 'gpt-5.6-luna'];
137
+ const make = (id, label, options) => tier('codex', id, label, options);
138
+ const full = (id, label, builders) => make(id, label, { ids: all, builders, subCaps: { astra: 'weekly' } });
139
+ return [
140
+ make('none', 'No Codex plan'),
141
+ make('free', 'ChatGPT Free', { ids: starter, builders: 1 }),
142
+ make('go', 'ChatGPT Go', { ids: starter, builders: 1 }),
143
+ make('plus', 'ChatGPT Plus', { ids: base, builders: 1 }),
144
+ full('pro-100', 'ChatGPT Pro $100', 2),
145
+ full('pro-200', 'ChatGPT Pro $200', 2),
146
+ full('pro-500', 'ChatGPT Pro $500', 3),
147
+ full('business', 'ChatGPT Business', 2),
148
+ make('api', 'OpenAI API', { ...API, ids: all, builders: 3 }),
149
+ ];
150
+ }
151
+
152
+ function antigravityTiers() {
153
+ const base = ['gemini-4-hydrogen', 'gemini-4-neon'];
154
+ const all = [...base, 'gemini-4-carbon'];
155
+ const make = (id, label, options) => tier('antigravity', id, label, options);
156
+ const withClaude = (id, label, builders) => make(id, label, {
157
+ ids: all, cross: ['claude-sonnet-5-5', 'claude-opus-5-5'], builders, subCaps: { 'third-party-claude': 'weekly' },
158
+ });
159
+ return [
160
+ make('none', 'No Antigravity plan'),
161
+ make('free', 'Antigravity Free', { ids: base, builders: 1 }),
162
+ make('plus', 'Google AI Plus', { ids: all, builders: 1 }),
163
+ make('pro-trial', 'Google AI Pro (trial)', { ids: all, builders: 1 }),
164
+ withClaude('pro', 'Google AI Pro', 2),
165
+ withClaude('ultra-5x', 'Google AI Ultra 5x', 2),
166
+ withClaude('ultra-20x', 'Google AI Ultra 20x', 3),
167
+ ];
168
+ }
169
+
170
+ const byId = (tiers) => Object.fromEntries(tiers.map((t) => [t.id, t]));
171
+
172
+ export const CATALOG = deepFreeze({ claude: byId(claudeTiers()), codex: byId(codexTiers()), antigravity: byId(antigravityTiers()) });
173
+
174
+ /** The provider's cheapest (triage order) standard-pool model among ids, else null. */
175
+ export function cheapestModel(provider, ids) {
176
+ // Models outside the triage list rank last, in the given order.
177
+ const rank = (id) => (PREFERENCE[provider].triage.indexOf(id) + 1) || Number.MAX_SAFE_INTEGER;
178
+ return ids.filter((id) => !MODELS[id]?.scarceQuota).sort((a, b) => rank(a) - rank(b))[0] ?? null;
179
+ }
180
+
181
+ export function getTier(provider, tierId) {
182
+ if (!PROVIDERS.includes(provider)) throw new Error(`unknown provider "${provider}"; expected one of ${PROVIDERS.join(', ')}`);
183
+ if (!Object.hasOwn(CATALOG[provider], tierId)) {
184
+ throw new Error(`unknown ${provider} tier "${tierId}"; expected one of ${Object.keys(CATALOG[provider]).join(', ')}`);
185
+ }
186
+ return CATALOG[provider][tierId];
187
+ }
188
+
189
+ /** Native ids are bare in resolved ladders; cross-hosted ones keep their "provider:" prefix. */
190
+ function ladderEntry(ref) {
191
+ const [provider, rest] = ref.split(':');
192
+ return MODELS[rest.split('@')[0]].provider === provider ? rest : ref;
193
+ }
194
+
195
+ /** Round-robin over providers beginning at lists[start]; overflow entries go last. */
196
+ function interleave(lists, start) {
197
+ const rotated = lists.map((_, i) => lists[(i + start) % lists.length]);
198
+ const roundRobin = (groups) => Array.from(
199
+ { length: Math.max(...groups.map((g) => g.length)) },
200
+ (_, i) => groups.flatMap((g) => g.slice(i, i + 1)),
201
+ ).flat();
202
+ return [
203
+ ...roundRobin(rotated.map((list) => list.filter((ref) => !isOverflow(ref)))),
204
+ ...roundRobin(rotated.map((list) => list.filter(isOverflow))),
205
+ ];
206
+ }
207
+
208
+ function resolveLadders(tiers) {
209
+ const slot = (role, start) => interleave(tiers.map((t) => t.ladders[role]), start).map(ladderEntry);
210
+ // Every provider's top auditor carries @high in the catalog; a merged ladder keeps it on its first entry only.
211
+ const auditor = (start) => slot('auditor', start).map((entry, index) => {
212
+ const [ref, effort] = entry.split('@');
213
+ if (index === 0) return `${ref}@high`;
214
+ return effort === 'high' ? ref : entry;
215
+ });
216
+ return {
217
+ tier1: slot('triage', 0),
218
+ commandRunner: slot('triage', 0),
219
+ builderA: slot('builder', 0),
220
+ testerA: slot('tester', 1),
221
+ auditorA: auditor(1),
222
+ builderB: slot('builder', 1),
223
+ testerB: slot('tester', 2),
224
+ auditorB: auditor(0),
225
+ architect: slot('planner', 0),
226
+ dualAudit: tiers.slice(0, 2).map((t) => ladderEntry(t.ladders.auditor[0])),
227
+ };
228
+ }
229
+
230
+ function resolveParent(claude, requested) {
231
+ if (requested == null) return claude ? { ...claude.parentDefault } : null;
232
+ if (!claude?.parentOptions.includes(requested)) {
233
+ const options = claude?.parentOptions.join(', ') ?? 'none (needs an eligible Claude tier)';
234
+ throw new Error(`--parent ${requested} is not available on the selected Claude tier; options: ${options}`);
235
+ }
236
+ return { model: requested, effort: claude.parentDefault.effort };
237
+ }
238
+
239
+ export function resolveTiers({ claude = 'none', codex = 'none', antigravity = 'none' } = {}, { parent, allowUsageCredits = false } = {}) {
240
+ const subscriptions = { claude, codex, antigravity };
241
+ const warnings = [];
242
+ const planRestrictedModels = [];
243
+ const eligible = new Map();
244
+ for (const provider of PROVIDERS) {
245
+ const selected = getTier(provider, subscriptions[provider]);
246
+ if (selected.warning) warnings.push(`${provider} ${selected.id}: ${selected.warning}`);
247
+ if (selected.usageBilled && !allowUsageCredits) {
248
+ warnings.push(`${provider} ${selected.id}: models excluded; pass --allow-usage-credits to use them`);
249
+ planRestrictedModels.push(...selected.models.map((m) => `${provider}:${m.model}`));
250
+ } else if (selected.cliSupported) {
251
+ eligible.set(provider, selected);
252
+ }
253
+ }
254
+ if (eligible.size === 0) throw new Error(`no CLI-capable subscription (${warnings.join('; ')})`);
255
+
256
+ const tiers = [...eligible.values()];
257
+ const models = tiers.flatMap((t) => t.models.map((m) => ({ ...m })));
258
+ const allowlist = Object.fromEntries(PROVIDERS.map(
259
+ (provider) => [DISPLAY[provider], models.filter((m) => m.provider === provider).map((m) => m.model)],
260
+ ));
261
+ return {
262
+ subscriptions,
263
+ parent: resolveParent(eligible.get('claude'), parent),
264
+ models,
265
+ allowlist,
266
+ ladders: resolveLadders(tiers),
267
+ maxParallelBuilders: Math.min(MAX_BUILDERS, tiers.reduce((sum, t) => sum + t.maxParallelBuilders, 0)),
268
+ planRestrictedModels,
269
+ warnings,
270
+ };
271
+ }
272
+
273
+ function presetFor(allowlist) {
274
+ const active = PROVIDERS.filter((p) => allowlist[DISPLAY[p]].length > 0).join(',');
275
+ return { 'claude,codex,antigravity': 'tri-provider', 'claude,codex': 'claude-codex', claude: 'claude-only' }[active] ?? 'custom';
276
+ }
277
+
278
+ export function toConfig(resolved, {
279
+ preset, allowFastModes = false, allowUsageCredits = false, verifiedOrg = false, userBannedModels = [], compactionThreshold = 35,
280
+ } = {}) {
281
+ const { subscriptions, parent, models, allowlist, planRestrictedModels, ladders, maxParallelBuilders } = structuredClone(resolved);
282
+ const banned = [...userBannedModels];
283
+ return {
284
+ schemaVersion: 2,
285
+ preset: preset ?? presetFor(allowlist),
286
+ subscriptions,
287
+ parent,
288
+ allowFastModes,
289
+ allowUsageCredits,
290
+ verifiedOrg,
291
+ models,
292
+ allowlist,
293
+ retiredModels: [...RETIRED_MODELS],
294
+ planRestrictedModels,
295
+ userBannedModels: banned,
296
+ bannedModels: banned,
297
+ ladders,
298
+ maxParallelBuilders,
299
+ defaultModel: allowlist.Claude.includes(PARENTS.sonnet) ? PARENTS.sonnet : ladders.builderA[0].split('@')[0],
300
+ defaultEffort: 'medium',
301
+ compactionThreshold,
302
+ modelIds: {},
303
+ discovery: {},
304
+ };
305
+ }
306
+
307
+ const versionOf = (value) => String(value?.version ?? value).split('.').map(Number);
308
+
309
+ /** Numerically newer dotted version; objects must also share a family. */
310
+ export function supersedes(a, b) {
311
+ if (a?.family !== b?.family) return false;
312
+ const [left, right] = [versionOf(a), versionOf(b)];
313
+ for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
314
+ const difference = (left[i] ?? 0) - (right[i] ?? 0);
315
+ if (difference !== 0) return difference > 0;
316
+ }
317
+ return false;
318
+ }
package/lib/probe.mjs CHANGED
@@ -4,10 +4,10 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { isDeepStrictEqual } from 'node:util';
6
6
  import {
7
- CONFIG_FILE, COOLDOWN_FILE, cliModelId, effectiveAllowlist, isBanned, isObject, isStringList, normalizeName,
8
- readJson, run, which as findOnPath,
7
+ canonicalProvider, CONFIG_FILE, COOLDOWN_FILE, cliModelId, effectiveAllowlist, isBanned, isObject, isStringList,
8
+ readJson, resolveTarget, run, which as findOnPath,
9
9
  } from '../hooks/_shared.mjs';
10
- import { parseRateLimit, readCooldowns, writeCooldowns } from '../hooks/_quota.mjs';
10
+ import { isLocked, parseRateLimit, readCooldowns, writeCooldowns } from '../hooks/_quota.mjs';
11
11
  import { HEAVY_MODELS } from './detect.mjs';
12
12
  import { CliError, PACKAGE_ROOT } from './paths.mjs';
13
13
  import { completeConfig, configProblem, syncConfig } from './install.mjs';
@@ -17,7 +17,7 @@ const TIMEOUT = 20_000;
17
17
 
18
18
  // Flags confirmed by `claude --help` and `codex exec --help`: one-word prompt, no tools or writes, nothing saved.
19
19
  // There is no documented Antigravity probe. The prompt has no spaces so it survives a cmd.exe shim.
20
- const PROBES = {
20
+ export const PROBES = {
21
21
  claude: (id) => ['-p', 'ok', '--model', id, '--tools', '', '--safe-mode', '--no-session-persistence', '--output-format', 'text'],
22
22
  codex: (id) => ['exec', '--model', id, '--sandbox', 'read-only', '--ephemeral', '--skip-git-repo-check',
23
23
  '--ignore-user-config', '--ignore-rules', '--color', 'never', 'ok'],
@@ -79,21 +79,42 @@ const wantedProviders = (providers) => {
79
79
  function cooldownFor(provider, model, id, text, config, now) {
80
80
  const tier = config.tiers?.[provider];
81
81
  const limit = parseRateLimit(text, { now, sharing: tier?.sharing, resetDay: tier?.resetDay });
82
+ const target = resolveTarget({ providers: [provider], model }, config);
82
83
  let { scope } = limit;
83
- // A heavy-tier lock would not cover a light model that was just refused, so lock that model itself.
84
- const heavy = isStringList(tier?.heavyModels) ? tier.heavyModels : HEAVY_MODELS[provider];
85
- if (scope === 'tier' && !heavy.some((name) => normalizeName(name) === normalizeName(model))) scope = 'model';
86
- const key = { model: `model:${id}`, provider: `provider:${provider}`, tier: `tier:${provider}:heavy` }[scope];
84
+ let pool = 'heavy';
85
+ if (target.pool !== 'standard') {
86
+ // A capped pool has its own quota: its limit must not lock the rest of the provider.
87
+ pool = target.pool;
88
+ if (scope !== 'model') scope = 'tier';
89
+ } else if (scope === 'tier') {
90
+ // A heavy-tier lock would not cover a light model that was just refused, so lock that model itself.
91
+ const heavy = { [`tier:${provider}:heavy`]: { until: limit.until } };
92
+ if (!isLocked(heavy, { provider, model, config }, now)) scope = 'model';
93
+ }
94
+ // A v2 entry names the hosting that refused, so the same model hosted elsewhere stays usable.
95
+ const modelKey = target.entry ? `model:${provider}:${id}` : `model:${id}`;
96
+ const key = { model: modelKey, provider: `provider:${provider}`, tier: `tier:${provider}:${pool}` }[scope];
87
97
  const entry = {
88
98
  scope, window: limit.window, until: limit.until, reason: `rate limited (${limit.window})`, source: 'probe',
89
- ...(scope === 'tier' && { tier: 'heavy' }),
99
+ ...(scope === 'tier' && { tier: pool }),
90
100
  };
91
101
  return { key, entry };
92
102
  }
93
103
 
94
- /** Probes each candidate model in turn. candidates: { providerKey: [display names] }, default config.allowlist. */
104
+ /** Why a model is left unprobed (its quota is not to be spent), else null. */
105
+ function skipReason(provider, model, config, pools, probeScarce) {
106
+ const { pool, scarceQuota } = resolveTarget({ providers: [provider], model }, config);
107
+ if (scarceQuota && !probeScarce) return 'skipped: scarce quota (use --probe-scarce)';
108
+ return pools && !pools.includes(pool) ? 'skipped: pool not selected' : null;
109
+ }
110
+
111
+ /**
112
+ * Probes each candidate model in turn. candidates: { providerKey: [display names] }, default config.allowlist.
113
+ * pools limits probing to those pools; scarceQuota models are reported as skipped unless probeScarce.
114
+ */
95
115
  export async function probeModels({
96
- config, candidates, providers, runner, which = findOnPath, now = Date.now(), log = () => {},
116
+ config, candidates, providers, runner, which = findOnPath, now = Date.now(), log = () => {}, pools,
117
+ probeScarce = false,
97
118
  } = {}) {
98
119
  const exec = runner ?? createRunner(which);
99
120
  const wanted = wantedProviders(providers);
@@ -105,7 +126,10 @@ export async function probeModels({
105
126
  for (const model of models) {
106
127
  if (isBanned(model, config.bannedModels ?? [])) continue;
107
128
  let outcome;
108
- if (!Object.hasOwn(PROBES, name)) {
129
+ const skip = skipReason(name, model, config, pools, probeScarce);
130
+ if (skip) {
131
+ outcome = { state: 'unavailable', reason: skip, skipped: true };
132
+ } else if (!Object.hasOwn(PROBES, name)) {
109
133
  outcome = { state: 'unavailable', reason: 'probe not supported' };
110
134
  } else if (providerLimited) {
111
135
  outcome = { state: 'rate-limited', reason: 'skipped: provider is rate limited', skipped: true };
@@ -186,6 +210,13 @@ function applyResults(config, preset, results) {
186
210
  }
187
211
  const planRestricted = Object.fromEntries(Object.entries(restricted).filter(([, models]) => models.length > 0));
188
212
  const next = { ...config, allowlist };
213
+ if (config.schemaVersion === 2) {
214
+ // v2 restrictions are only added here, never lifted by a probe (tier-derived ones must stay).
215
+ const refs = Object.entries(planRestricted)
216
+ .flatMap(([provider, models]) => models.map((m) => `${canonicalProvider(provider) ?? provider.toLowerCase()}:${m}`));
217
+ next.planRestrictedModels = [...new Set([...(config.planRestrictedModels ?? []), ...refs])];
218
+ return { next, planRestricted };
219
+ }
189
220
  if (config.planRestricted !== undefined || Object.keys(planRestricted).length > 0) next.planRestricted = planRestricted;
190
221
  return { next, planRestricted };
191
222
  }
@@ -206,7 +237,7 @@ function backfillLadders(next, preset) {
206
237
  /** Probes the candidate models of <target>'s config and persists the allowlist, cooldowns and SKILL.md. */
207
238
  export async function syncModels(target, {
208
239
  providers, dryRun = false, yes = false, force = false, runner, which, now = Date.now(), log = console.log,
209
- confirm = async () => false, syncFiles = syncConfig,
240
+ confirm = async () => false, syncFiles = syncConfig, probeScarce = false,
210
241
  } = {}) {
211
242
  const config = readConfig(path.join(target, CONFIG_FILE));
212
243
  const presetName = ['claude-codex', 'claude-only'].includes(config.preset) ? config.preset : 'tri-provider';
@@ -215,9 +246,12 @@ export async function syncModels(target, {
215
246
  // Checked before probing, so quota is not spent on a config that cannot be saved.
216
247
  const problem = configProblem(completeConfig(config));
217
248
  if (problem) throw new CliError(`${CONFIG_FILE}: ${problem}`);
218
- const candidates = mergeModelMaps(config.allowlist ?? preset.allowlist, config.planRestricted, preset.allowlist);
249
+ // v2 allowlists are bound to the subscription tier, so the preset roster is never merged in.
250
+ const candidates = config.schemaVersion === 2
251
+ ? mergeModelMaps(config.allowlist)
252
+ : mergeModelMaps(config.allowlist ?? preset.allowlist, config.planRestricted, preset.allowlist);
219
253
  const { results } = await probeModels({
220
- config: { ...config, bannedModels }, candidates, providers, runner, which, now, log,
254
+ config: { ...config, bannedModels }, candidates, providers, runner, which, now, log, probeScarce,
221
255
  });
222
256
 
223
257
  const { next, planRestricted } = applyResults(config, preset, results);
package/lib/prompt.mjs CHANGED
@@ -1,13 +1,45 @@
1
1
  import path from 'node:path';
2
2
  import readline from 'node:readline/promises';
3
- import { CONFIG_FILE, isObject, readJson } from '../hooks/_shared.mjs';
3
+ import { CONFIG_FILE, isObject, isV2, readJson } from '../hooks/_shared.mjs';
4
4
  import { detect as detectProviders, parseTiers } from './detect.mjs';
5
5
  import { MODULES, readManifest } from './manifest.mjs';
6
- import { PRESETS, completeConfig } from './install.mjs';
6
+ import { ASSUMED_TIERS, PRESETS, completeConfig } from './install.mjs';
7
7
  import { CliError } from './paths.mjs';
8
+ import { CATALOG, PROVIDERS } from './plans.mjs';
8
9
 
9
10
  const MODULE_LABELS = { full: 'Full Suite', 'auto-build': '/auto-build Only', core: 'Core Discipline + Commands' };
10
11
  const PLAN_NAMES = { claude: 'pro|max', codex: 'plus|pro', antigravity: 'standard|ultra' };
12
+ export const TIER_FLAGS = { claude: '--claude-tier', codex: '--codex-tier', antigravity: '--antigravity-tier' };
13
+
14
+ /** A saved config carries no warnings, so they come from the catalog. */
15
+ const catalogWarnings = (config) => PROVIDERS.flatMap((provider) => {
16
+ const id = config.subscriptions?.[provider] ?? 'none';
17
+ const tier = CATALOG[provider][id];
18
+ if (!tier?.warning || id === 'none') return [];
19
+ const excluded = tier.usageBilled && !config.allowUsageCredits
20
+ ? [`${provider} ${id}: models excluded; pass --allow-usage-credits to use them`] : [];
21
+ return [`${provider} ${id}: ${tier.warning}`, ...excluded];
22
+ });
23
+
24
+ /** Plain text overview of a resolveTiers() result or a v2 config, shown before it is written. */
25
+ export function summaryTable(resolved) {
26
+ const names = (models) => models.map((m) => m.model).join(', ') || '-';
27
+ const rows = [['provider', 'tier', 'CLI', 'models (standard)', 'scarce overflow', 'max parallel']];
28
+ for (const provider of PROVIDERS) {
29
+ const id = resolved.subscriptions?.[provider] ?? 'none';
30
+ const tier = CATALOG[provider][id];
31
+ const models = (resolved.models ?? []).filter((m) => m.provider === provider);
32
+ rows.push([provider, id, tier?.cliSupported ? 'yes' : 'no', names(models.filter((m) => !m.scarceQuota)),
33
+ names(models.filter((m) => m.scarceQuota)), String(models.length ? tier?.maxParallelBuilders ?? 0 : 0)]);
34
+ }
35
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((row) => row[i].length)));
36
+ const lines = rows.map((row) => row.map((cell, i) => cell.padEnd(widths[i])).join(' | ').trimEnd());
37
+ lines.push(`parent: ${resolved.parent ? `${resolved.parent.model} (${resolved.parent.effort})` : 'none'}`);
38
+ lines.push(`max parallel builders: ${resolved.maxParallelBuilders ?? 0}`);
39
+ const warnings = (resolved.warnings ?? catalogWarnings(resolved)).filter((text) => !/^\w+ none:/.test(text));
40
+ lines.push(...warnings.map((text) => `warning: ${text}`));
41
+ return lines.join('\n');
42
+ }
11
43
 
12
44
  /** parseTiers, with a bad value reported as a usage error. */
13
45
  export function parseTierSpec(spec) {
@@ -49,8 +81,18 @@ export async function initPrompts(target, options, { detect = detectProviders, i
49
81
  providers: Object.keys(found.providers).filter((name) => found.providers[name].binary),
50
82
  tiers: isObject(complete.tiers) ? complete.tiers : {},
51
83
  };
84
+ const v2 = isV2(config);
85
+ // Default tier per provider. null (v1 config) keeps that config unless a tier is typed.
86
+ current.subscriptions = Object.fromEntries(PROVIDERS.map((provider) => {
87
+ if (v2) return [provider, config.subscriptions?.[provider] ?? 'none'];
88
+ if (config) return [provider, null];
89
+ return [provider, found.providers[provider]?.binary ? ASSUMED_TIERS[provider] : 'none'];
90
+ }));
91
+ current.v2 = v2;
92
+ current.parent = config?.parent?.model;
93
+ current.allowUsageCredits = config?.allowUsageCredits;
52
94
  const answers = await promptOptions(options, current, input, output);
53
- if (!config && (answers.modules ?? current.modules) !== 'core') answers.preset ??= found.preset;
95
+ if (!config && (answers.modules ?? current.modules) !== 'core' && !tiered(answers, v2)) answers.preset ??= found.preset;
54
96
  return answers;
55
97
  }
56
98
 
@@ -70,6 +112,38 @@ export function parsePercent(value) {
70
112
  return percent;
71
113
  }
72
114
 
115
+ /** True when subscription tiers, not a preset, decide the providers. */
116
+ const tiered = (answers, v2) => v2 || PROVIDERS.some((provider) => {
117
+ const tier = answers[`${provider}Tier`] ?? answers.subscriptions?.[provider];
118
+ return tier !== undefined && tier !== 'none';
119
+ });
120
+
121
+ /** One tier question per provider without a flag, then the parent when the Claude tier offers a choice. */
122
+ async function askTiers(options, current, answers, ask, output) {
123
+ const subscriptions = {};
124
+ for (const provider of PROVIDERS) {
125
+ let tier = options[`${provider}Tier`];
126
+ if (tier === undefined) {
127
+ const ids = Object.keys(CATALOG[provider]);
128
+ const kept = current.subscriptions[provider];
129
+ const reply = await ask(`${provider} subscription tier (${ids.join(', ')}) [${kept ?? 'keep'}]: `);
130
+ tier = reply ? parseChoice(reply, ids, `${provider} tier`) : kept;
131
+ }
132
+ if (tier !== null) subscriptions[provider] = tier;
133
+ const chosen = CATALOG[provider][tier];
134
+ if (tier !== 'none' && chosen?.warning) output.write(`warning: ${provider} ${tier}: ${chosen.warning}\n`);
135
+ }
136
+ answers.subscriptions = subscriptions;
137
+
138
+ const claude = CATALOG.claude[options.claudeTier ?? subscriptions.claude];
139
+ const usable = claude && (!claude.usageBilled || (options.allowUsageCredits ?? current.allowUsageCredits));
140
+ if (options.parent === undefined && usable && claude.parentOptions.length > 1) {
141
+ const kept = claude.parentOptions.includes(current.parent) ? current.parent : claude.parentDefault.model;
142
+ const reply = await ask(`Parent model (${claude.parentOptions.join(', ')}) [${kept}]: `);
143
+ if (reply) answers.parent = parseChoice(reply, claude.parentOptions, 'parent');
144
+ }
145
+ }
146
+
73
147
  /** Ask for whatever the flags left open. Enter keeps the current value (answer stays undefined). */
74
148
  export async function promptOptions(options, current, input = process.stdin, output = process.stdout) {
75
149
  const rl = readline.createInterface({ input, output, terminal: false });
@@ -88,7 +162,10 @@ export async function promptOptions(options, current, input = process.stdin, out
88
162
  if (reply) answers.modules = parseChoice(reply, MODULES, 'modules');
89
163
  }
90
164
  if ((answers.modules ?? current.modules) === 'core') return answers;
91
- if (answers.preset === undefined) {
165
+ const subscriptionMode = current.subscriptions !== undefined && options.tiers === undefined;
166
+ if (subscriptionMode) await askTiers(options, current, answers, ask, output);
167
+ // Subscription tiers decide the providers, so a preset is only asked without them.
168
+ if (answers.preset === undefined && !(subscriptionMode && tiered(answers, current.v2))) {
92
169
  const reply = await ask(`Preset:\n${numbered(PRESETS)}\nChoose [${current.preset}]: `);
93
170
  if (reply) answers.preset = parseChoice(reply, PRESETS, 'preset');
94
171
  }
@@ -98,7 +175,7 @@ export async function promptOptions(options, current, input = process.stdin, out
98
175
  const reply = await ask(`Auto-compaction threshold, percent 1-100 [${current.compaction}]: `);
99
176
  if (reply) answers.compaction = parsePercent(reply);
100
177
  }
101
- if (options.tiers === undefined) {
178
+ if (options.tiers === undefined && !subscriptionMode) {
102
179
  for (const provider of current.providers ?? []) {
103
180
  const kept = current.tiers?.[provider]?.plan ?? 'skip';
104
181
  const plan = await ask(`${provider} subscription tier (${PLAN_NAMES[provider]}) [${kept}]: `);