t3-auto-build 1.0.1 → 2.0.0

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/bin/cli.mjs CHANGED
@@ -3,87 +3,110 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { HEAVY_MODELS } from '../lib/detect.mjs';
5
5
  import { doctor } from '../lib/doctor.mjs';
6
- import { PRESETS, install, uninstall, wantsAuto } from '../lib/install.mjs';
6
+ import { applyDrift, checkModels, markAvailability, readAvailabilityFile } from '../lib/discover.mjs';
7
+ import { PRESETS, install, syncConfig, uninstall, upgrade, wantsAuto } from '../lib/install.mjs';
7
8
  import { MODULES, readManifest } from '../lib/manifest.mjs';
8
9
  import { CliError, PACKAGE_ROOT, resolveTarget } from '../lib/paths.mjs';
9
10
  import { syncModels } from '../lib/probe.mjs';
10
- import { confirmYes, initPrompts, parseChoice, parsePercent, parseTierSpec } from '../lib/prompt.mjs';
11
+ import { CATALOG, PROVIDERS } from '../lib/plans.mjs';
12
+ import { confirmYes, initPrompts, parseChoice, parsePercent, parseTierSpec, TIER_FLAGS } from '../lib/prompt.mjs';
11
13
  import { QUOTA_WINDOWS, quotaCheck, quotaClear, quotaSet, quotaStatus } from '../lib/quota.mjs';
14
+ import { CONFIG_FILE, readJson } from '../hooks/_shared.mjs';
12
15
 
13
16
  const USAGE = `Usage: t3-auto-build <command> [options]
14
17
 
15
18
  Commands:
16
- init install or update (interactive unless --yes)
17
- doctor check an installation
18
- uninstall remove what init installed, keeping your edits
19
- sync-models probe the models and update the allowlist
20
- quota set <subject> lock a provider (claude, codex, antigravity) or a model
21
- quota status show active locks and drop expired ones
22
- quota clear [subject] remove the locks of a provider or model (or --all)
23
- quota check [provider] run the official login status commands
24
-
25
- Options:
26
- --target <dir> config dir (default: $CLAUDE_CONFIG_DIR, else ~/.claude)
27
- -h, --help show this help
28
- -v, --version print the version
29
- init only:
30
- --preset <name> ${PRESETS.join(' | ')}
31
- --modules <name> ${MODULES.join(' | ')}
32
- --compaction <n> auto-compaction threshold, 1-100
33
- --tiers <list> provider:plan[:weekday], comma separated, e.g. claude:max,codex:pro
34
- --probe run sync-models after installing (spends real quota)
35
- --yes do not prompt
36
- sync-models only:
37
- --dry-run show the result without writing. Note: sync-models --dry-run
38
- still executes live probes (spends real quota) but writes nothing.
39
- --providers <list> only these providers, comma separated
40
- --yes write without asking
41
- init and sync-models:
42
- --force back up your edited files to .bak, then overwrite. sync-models applies it
43
- to a hand-edited SKILL.md (default: skip it with a warning)
44
- quota set only (one window, default --burst):
45
- --burst 10 minutes
46
- --5h 5 hours
47
- --weekly until the tier's weekly reset day, else 7 days
48
- --until <when> ISO time, or a duration such as 90m or 1w2d
49
- --reason <text> note shown by quota status
50
- quota clear only:
51
- --all remove every lock`;
52
-
53
- const VALUE_FLAGS = ['target', 'preset', 'modules', 'compaction', 'tiers', 'providers', 'until', 'reason'];
54
- const SWITCHES = ['yes', 'force', 'help', 'version', 'probe', 'dry-run', 'all', ...QUOTA_WINDOWS];
19
+ init install or update (interactive unless --yes)
20
+ upgrade [--yes] convert a legacy v1 config to v2
21
+ check-models inspect availability and model drift (cached probes)
22
+ sync-models probe and sync models, or apply discovered drift
23
+ availability mark <ref> <status> [--ttl 24h] [--reason <text>]
24
+ availability status show cache age, model status, and discovered drift
25
+ quota set <subject> lock a provider/model, or a model pool with --pool
26
+ quota status show active locks and drop expired ones
27
+ quota clear [subject] remove locks of a provider/model (or --all)
28
+ quota check [provider] run official login status commands
29
+ doctor check installation, tiers, cache, and drift
30
+ uninstall remove what init installed, keeping your edits
31
+
32
+ Global flags:
33
+ --target <dir> config dir (default: $CLAUDE_CONFIG_DIR, else ~/.claude)
34
+ -h, --help show this help; -v, --version prints version
35
+ --yes do not prompt
36
+
37
+ init only:
38
+ --preset <name> ${PRESETS.join(' | ')}
39
+ --modules <name> ${MODULES.join(' | ')}
40
+ --compaction <n> auto-compaction threshold, 1-100
41
+ --tiers <list> legacy provider:plan[:weekday] list
42
+ --claude-tier <tier> ${Object.keys(CATALOG.claude).join(' | ')}
43
+ --codex-tier <tier> ${Object.keys(CATALOG.codex).join(' | ')}
44
+ --antigravity-tier <tier> ${Object.keys(CATALOG.antigravity).join(' | ')}
45
+ --parent <model> sonnet | opus | fable
46
+ --allow-usage-credits allow tiers billed per token
47
+ --allow-fast-modes permit fast/priority service modes
48
+ --verified-org mark the account as verified organization
49
+ --probe run sync-models after installing
50
+
51
+ check-models only:
52
+ --refresh ignore the probe cache TTL
53
+ --probe-scarce also probe scarce quota models
54
+ --json print machine-readable results
55
+
56
+ sync-models only:
57
+ --auto run without confirmation
58
+ --refresh ignore the probe cache TTL
59
+ --probe-scarce also probe scarce quota models
60
+ --apply promote newer known models from discovered drift
61
+ --dry-run probe but do not write the synced allowlist
62
+ --providers <list> only these providers, comma separated
63
+ --force replace edited managed SKILL.md after backup
64
+
65
+ availability only:
66
+ --ttl <duration> mark lifetime: 1m..30d (default 24h)
67
+ --reason <text> note shown in availability status
68
+
69
+ quota set only:
70
+ --pool <name> lock a model pool (standard, fable, astra, third-party-claude)
71
+ --burst | --5h | --weekly lock window (default burst)
72
+ --until <when> ISO time or duration such as 90m or 1w2d
73
+ --reason <text> note shown by quota status
74
+ quota clear flag: --all remove every lock
75
+
76
+ Examples:
77
+ t3-auto-build init --claude-tier pro --codex-tier plus --antigravity-tier pro --parent opus
78
+ t3-auto-build check-models --json
79
+ t3-auto-build sync-models --refresh --probe-scarce
80
+ t3-auto-build availability mark antigravity:claude-opus-5-5 plan-restricted --ttl 24h
81
+ t3-auto-build quota set antigravity:claude-opus-5-5 --pool third-party-claude
82
+ Overflow to cross-hosted models requires an explicit provider, e.g. antigravity:claude-opus-5-5.`;
83
+
84
+ const VALUE_FLAGS = ['target', 'preset', 'modules', 'compaction', 'tiers', 'providers', 'until', 'reason', 'parent', 'claude-tier', 'codex-tier', 'antigravity-tier', 'ttl', 'pool'];
85
+ const SWITCHES = ['yes', 'force', 'help', 'version', 'probe', 'dry-run', 'all', 'auto', 'refresh', 'probe-scarce', 'apply', 'json', 'allow-usage-credits', 'allow-fast-modes', 'verified-org', ...QUOTA_WINDOWS];
55
86
  const COMMAND_FLAGS = {
56
- init: ['preset', 'modules', 'compaction', 'tiers', 'probe', 'yes', 'force'],
57
- doctor: [],
58
- uninstall: [],
59
- 'sync-models': ['dry-run', 'providers', 'yes', 'force'],
60
- 'quota set': [...QUOTA_WINDOWS, 'until', 'reason'],
61
- 'quota status': [],
62
- 'quota clear': ['all'],
63
- 'quota check': [],
87
+ init: ['preset', 'modules', 'compaction', 'tiers', 'probe', 'yes', 'force', ...Object.values(TIER_FLAGS).map((f) => f.slice(2)), 'parent', 'allow-usage-credits', 'allow-fast-modes', 'verified-org'],
88
+ upgrade: ['yes'], doctor: [], uninstall: [],
89
+ 'check-models': ['refresh', 'probe-scarce', 'json'],
90
+ 'sync-models': ['dry-run', 'providers', 'yes', 'auto', 'force', 'refresh', 'probe-scarce', 'apply'],
91
+ 'availability mark': ['ttl', 'reason'], 'availability status': [],
92
+ 'quota set': [...QUOTA_WINDOWS, 'until', 'reason', 'pool'],
93
+ 'quota status': [], 'quota clear': ['all'], 'quota check': [],
64
94
  };
65
- // [min, max] positional arguments after the command.
66
- const ARGUMENTS = { 'quota set': [1, 1], 'quota clear': [0, 1], 'quota check': [0, 1] };
95
+ const ARGUMENTS = { upgrade: [0, 0], 'availability mark': [2, 2], 'quota set': [1, 1], 'quota clear': [0, 1], 'quota check': [0, 1] };
67
96
 
68
97
  function parseArgs(argv) {
69
98
  const flags = {};
70
99
  const positional = [];
71
100
  for (let i = 0; i < argv.length; i += 1) {
72
101
  const argument = { '-h': '--help', '-v': '--version' }[argv[i]] ?? argv[i];
73
- if (!argument.startsWith('-')) {
74
- positional.push(argument);
75
- continue;
76
- }
102
+ if (!argument.startsWith('-')) { positional.push(argument); continue; }
77
103
  const [, name, inline] = argument.match(/^--([^=]+)(?:=(.*))?$/s) ?? [];
78
- if (SWITCHES.includes(name) && inline === undefined) {
79
- flags[name] = true;
80
- } else if (VALUE_FLAGS.includes(name)) {
104
+ if (SWITCHES.includes(name) && inline === undefined) flags[name] = true;
105
+ else if (VALUE_FLAGS.includes(name)) {
81
106
  const value = inline ?? argv[(i += 1)];
82
107
  if (!value || (inline === undefined && value.startsWith('--'))) throw new CliError(`--${name} needs a value`, 2);
83
108
  flags[name] = value;
84
- } else {
85
- throw new CliError(`unknown option ${argument}`, 2);
86
- }
109
+ } else throw new CliError(`unknown option ${argument}`, 2);
87
110
  }
88
111
  return { flags, positional };
89
112
  }
@@ -94,25 +117,35 @@ function parseProviders(value) {
94
117
  return names.map((name) => parseChoice(name, Object.keys(HEAVY_MODELS), 'provider'));
95
118
  }
96
119
 
97
- async function sync(target, { yes = false, dryRun = false, force = false, providers }) {
98
- if (!yes && !dryRun && !process.stdin.isTTY) {
99
- throw new CliError('no interactive terminal; re-run with --yes (or --dry-run); nothing was written', 2);
120
+ function rawConfig(target) {
121
+ const file = path.join(target, CONFIG_FILE);
122
+ try { return readJson(file); } catch (error) { throw new CliError(`${file}: cannot read valid config JSON (${error.code ?? error.name})`); }
123
+ }
124
+
125
+ async function sync(target, { yes = false, dryRun = false, force = false, providers, refresh = false, probeScarce = false, apply = false } = {}) {
126
+ if (apply) {
127
+ const config = rawConfig(target);
128
+ const availability = readAvailabilityFile(target);
129
+ if (!availability) throw new CliError('no availability cache; run t3-auto-build check-models first');
130
+ const result = applyDrift(config, availability);
131
+ for (const promotion of result.promoted) console.log(`promoted ${promotion.provider}:${promotion.from} -> ${promotion.provider}:${promotion.to}`);
132
+ for (const unknown of result.unknown) console.log(`unknown family ${unknown.provider}:${unknown.model} (left disabled)`);
133
+ if (result.promoted.length) await syncConfig(target, result.config, { force, log: console.log });
134
+ else console.log('no known model drift to apply');
135
+ return;
100
136
  }
101
- // Checked before probing, so quota is not spent on results that cannot be saved.
137
+ if (!yes && !dryRun && !process.stdin.isTTY) throw new CliError('no interactive terminal; re-run with --auto (or --dry-run); nothing was written', 2);
102
138
  const manifest = readManifest(target);
103
- if (!dryRun && !(manifest && wantsAuto(manifest.modules))) {
104
- throw new CliError(`no auto-build installation in ${target}; run init first`);
105
- }
139
+ if (!dryRun && !(manifest && wantsAuto(manifest.modules))) throw new CliError(`no auto-build installation in ${target}; run init first`);
106
140
  let declined = false;
107
141
  const confirm = async ({ allowlist, planRestricted, cooldowns, changed }) => {
108
142
  if (force || changed || Object.keys(cooldowns).length) {
109
143
  console.log(JSON.stringify({ allowlist, planRestricted, cooldowns }, null, 2));
110
144
  if (await confirmYes(`Write these changes to ${target}? [y/N] `)) return true;
111
145
  }
112
- declined = true;
113
- return false;
146
+ declined = true; return false;
114
147
  };
115
- const summary = await syncModels(target, { providers, dryRun, yes, force, confirm });
148
+ const summary = await syncModels(target, { providers, dryRun, yes, refresh, probeScarce, confirm });
116
149
  if (dryRun) {
117
150
  const { allowlist, planRestricted, cooldowns, changed } = summary;
118
151
  console.log(JSON.stringify({ allowlist, planRestricted, cooldowns, changed }, null, 2));
@@ -121,23 +154,56 @@ async function sync(target, { yes = false, dryRun = false, force = false, provid
121
154
  }
122
155
 
123
156
  async function init(target, flags) {
124
- let options = {
157
+ const options = {
125
158
  force: flags.force,
126
159
  preset: flags.preset === undefined ? undefined : parseChoice(flags.preset, PRESETS, 'preset'),
127
160
  modules: flags.modules === undefined ? undefined : parseChoice(flags.modules, MODULES, 'modules'),
128
161
  compaction: flags.compaction === undefined ? undefined : parsePercent(flags.compaction),
129
162
  tiers: flags.tiers === undefined ? undefined : parseTierSpec(flags.tiers),
163
+ claudeTier: flags['claude-tier'], codexTier: flags['codex-tier'], antigravityTier: flags['antigravity-tier'],
164
+ parent: flags.parent, allowUsageCredits: flags['allow-usage-credits'], allowFastModes: flags['allow-fast-modes'], verifiedOrg: flags['verified-org'],
130
165
  };
166
+ for (const provider of PROVIDERS) {
167
+ const field = { claude: 'claudeTier', codex: 'codexTier', antigravity: 'antigravityTier' }[provider];
168
+ if (options[field] !== undefined && !Object.hasOwn(CATALOG[provider], options[field])) {
169
+ throw new CliError(`unknown ${provider} tier "${options[field]}"; valid tiers: ${Object.keys(CATALOG[provider]).join(', ')}`, 2);
170
+ }
171
+ }
172
+ if (options.parent !== undefined && !['sonnet', 'opus', 'fable'].includes(options.parent)) {
173
+ throw new CliError('--parent must be sonnet, opus or fable', 2);
174
+ }
175
+ let finalOptions = options;
131
176
  if (!flags.yes) {
132
- if (!process.stdin.isTTY) throw new CliError('no interactive terminal; re-run with --yes (and --preset/--modules/--compaction)', 2);
133
- options = await initPrompts(target, options);
177
+ if (!process.stdin.isTTY) throw new CliError('no interactive terminal; re-run with --yes (and tier flags)', 2);
178
+ finalOptions = await initPrompts(target, options);
134
179
  }
135
- install(target, options);
180
+ install(target, finalOptions);
136
181
  if (!flags.probe) return;
137
- if (wantsAuto(readManifest(target).modules)) await sync(target, { yes: flags.yes });
182
+ if (wantsAuto(readManifest(target).modules)) await sync(target, { yes: true });
138
183
  else console.log('warning: --probe does not apply to the core module; ignored');
139
184
  }
140
185
 
186
+ async function check(target, flags) {
187
+ const config = rawConfig(target);
188
+ const result = await checkModels({ configDir: target, config, refresh: flags.refresh, probeScarce: flags['probe-scarce'] });
189
+ if (flags.json) console.log(JSON.stringify(result, null, 2));
190
+ else {
191
+ console.log(`availability ${result.stale ? 'stale' : 'fresh'}; probed ${result.probed.length}; skipped scarce ${result.skippedScarce.length}`);
192
+ for (const entry of result.availability.discoveredNew ?? []) console.log(`discovered ${entry.provider}:${entry.model}${entry.supersedes ? ` supersedes ${entry.supersedes}` : ' (unknown family)'}`);
193
+ }
194
+ }
195
+
196
+ function availability(action, target, args, flags) {
197
+ if (action === 'status') {
198
+ const data = readAvailabilityFile(target);
199
+ if (!data) { console.log('availability cache missing or malformed'); return; }
200
+ const age = Math.max(0, Date.now() - Date.parse(data.checkedAt));
201
+ console.log(`availability cache ${age <= (data.ttlMs ?? 43_200_000) ? 'fresh' : 'stale'} (${(age / 3_600_000).toFixed(1)}h old)`);
202
+ for (const [ref, entry] of Object.entries(data.models ?? {})) console.log(`${ref}: ${entry.status}${entry.reason ? ` (${entry.reason})` : ''}`);
203
+ console.log(`drift: ${(data.discoveredNew ?? []).length} discovered, ${(data.missingConfigured ?? []).length} missing configured`);
204
+ } else markAvailability({ configDir: target, ref: args[0], status: args[1], ttl: flags.ttl, reason: flags.reason });
205
+ }
206
+
141
207
  function quota(action, target, subject, flags) {
142
208
  if (action === 'status') return quotaStatus(target);
143
209
  if (action === 'check') return quotaCheck(target, { providers: subject === undefined ? undefined : [subject] });
@@ -147,9 +213,7 @@ function quota(action, target, subject, flags) {
147
213
  }
148
214
  const chosen = [...QUOTA_WINDOWS, 'until'].filter((name) => flags[name] !== undefined);
149
215
  if (chosen.length > 1) throw new CliError(`use only one of ${chosen.map((name) => `--${name}`).join(', ')}`, 2);
150
- return quotaSet(target, subject, {
151
- window: chosen[0] === 'until' ? undefined : chosen[0], until: flags.until, reason: flags.reason,
152
- });
216
+ return quotaSet(target, subject, { window: chosen[0] === 'until' ? undefined : chosen[0], until: flags.until, reason: flags.reason, pool: flags.pool });
153
217
  }
154
218
 
155
219
  async function main(argv) {
@@ -157,19 +221,21 @@ async function main(argv) {
157
221
  if (flags.help) return console.log(USAGE);
158
222
  if (flags.version) return console.log(JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8')).version);
159
223
  const [first, ...rest] = positional;
160
- const command = first === 'quota' ? `quota ${rest.shift()}` : first;
224
+ const command = first === 'quota' || first === 'availability' ? `${first} ${rest.shift()}` : first;
161
225
  const [min, max] = ARGUMENTS[command] ?? [0, 0];
162
226
  if (!Object.hasOwn(COMMAND_FLAGS, command) || rest.length < min || rest.length > max) throw new CliError(USAGE, 2);
163
227
  const stray = Object.keys(flags).find((name) => name !== 'target' && !COMMAND_FLAGS[command].includes(name));
164
228
  if (stray) throw new CliError(`--${stray} is not valid with ${command}`, 2);
165
229
  const target = resolveTarget(flags.target);
166
-
167
230
  if (command === 'init') await init(target, flags);
231
+ else if (command === 'upgrade') await upgrade(target);
168
232
  else if (command === 'doctor') process.exitCode = doctor(target);
169
233
  else if (command === 'uninstall') uninstall(target);
234
+ else if (command === 'check-models') await check(target, flags);
235
+ else if (command === 'availability mark' || command === 'availability status') availability(command.slice('availability '.length), target, rest, flags);
170
236
  else if (command === 'sync-models') {
171
237
  const providers = flags.providers === undefined ? undefined : parseProviders(flags.providers);
172
- await sync(target, { yes: flags.yes, dryRun: flags['dry-run'], force: flags.force, providers });
238
+ await sync(target, { yes: flags.yes || flags.auto, dryRun: flags['dry-run'], force: flags.force, providers, refresh: flags.refresh, probeScarce: flags['probe-scarce'], apply: flags.apply });
173
239
  } else await quota(command.slice('quota '.length), target, rest[0], flags);
174
240
  }
175
241
 
package/hooks/_quota.mjs CHANGED
@@ -1,17 +1,18 @@
1
1
  // Cooldown (rate limit / quota lockout) state shared by the installed hooks. Node >=18, node:* only.
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
- import { inferProvider, isObject, isStringList, modelKeys, normalizeName, parseJson, warn } from './_shared.mjs';
4
+ import {
5
+ canonicalProvider, inferProvider, isObject, isStringList, modelKeys, normalizeName, parseJson,
6
+ resolveTarget, warn,
7
+ } from './_shared.mjs';
5
8
 
6
9
  const MINUTE = 60_000;
7
10
  const DAY = 24 * 60 * MINUTE;
8
11
  // A parsed reset time comes from message text, so it can never lock for longer than this.
9
12
  const MAX_LOCK = 14 * DAY;
10
13
 
11
- // T3 provider ids to provider keys. Custom instances (codex-2) resolve by driverKind or this prefix.
12
- const PROVIDERS = new Map([['claudeagent', 'claude'], ['claude', 'claude'], ['codex', 'codex'], ['antigravity', 'antigravity']]);
13
- const compact = (id) => id.toLowerCase().replace(/[^a-z0-9]/g, '');
14
14
  const HEAVY_MODELS = { claude: ['Claude Opus 5.5'], codex: ['gpt-6-luna'], antigravity: ['Gemini 4 Carbon'] };
15
+ export const SCARCE_POOL = { claude: 'fable', codex: 'astra', antigravity: 'third-party-claude' };
15
16
 
16
17
  const untilOf = (entry) => {
17
18
  const text = entry?.until ?? entry?.until_utc;
@@ -54,6 +55,9 @@ function readRaw(file) {
54
55
  }
55
56
 
56
57
  const isValid = (key, value) => {
58
+ const validKey = /^(?:model:[^:]+(?::[^:]+)?|provider:[^:]+|tier:[^:]+:[a-z0-9-]+)$/i.test(key)
59
+ || !/^(?:model|provider|tier):/i.test(key);
60
+ if (!validKey) return false;
57
61
  try {
58
62
  return Boolean(canonical(key, value));
59
63
  } catch {
@@ -95,29 +99,67 @@ export function prune(data, now = Date.now()) {
95
99
  return { kept: split(true), removed: split(false) };
96
100
  }
97
101
 
98
- function matches(key, scope, { provider, model, config }) {
102
+ function matches(key, scope, { provider, providers, model, config }) {
103
+ const declarations = [...new Set((providers ?? (provider === undefined ? [] : [provider]))
104
+ .filter((id) => typeof id === 'string' && id.trim() !== ''))];
105
+ const declared = [...new Set(declarations.map(canonicalProvider).filter(Boolean))];
106
+ const inferred = inferProvider(model);
107
+ const targets = [];
108
+ const target = resolveTarget({ providers: declarations, model }, config);
109
+ targets.push(target);
110
+ // A conflict is blocked separately by pre-tool-use, but cooldowns remain conservative for both sides.
111
+ const candidates = target.conflict ? [...new Set([...declared, inferred].filter(Boolean))] : [];
112
+ for (const candidate of candidates) {
113
+ targets.push(resolveTarget({ providers: [candidate], model }, config));
114
+ }
115
+
99
116
  if (scope === 'provider') {
100
- const aliasOf = (id) => [...PROVIDERS.keys()].find((prefix) => compact(id).startsWith(prefix));
101
- // A custom instance id ("work") says nothing about its provider, so the model decides too.
102
- const ids = [provider, !(provider && aliasOf(provider)) && inferProvider(model)].filter(Boolean);
103
- // Only exact aliases apply to the key, so a "codex-2" cooldown does not block every Codex instance.
104
- const name = key.replace(/^provider:/i, '');
105
- const wanted = normalizeName(PROVIDERS.get(compact(name)) ?? name);
106
- return ids.flatMap((id) => [id, PROVIDERS.get(aliasOf(id)) ?? id]).some((id) => normalizeName(id) === wanted);
117
+ const wantedRaw = key.replace(/^provider:/i, '');
118
+ const compactKey = wantedRaw.toLowerCase().replace(/[^a-z0-9]/g, '');
119
+ const wantedProvider = ['claude', 'claudeagent', 'codex', 'antigravity'].includes(compactKey)
120
+ ? canonicalProvider(wantedRaw) : null;
121
+ const wanted = normalizeName(wantedRaw);
122
+ const ids = new Set([
123
+ ...declarations.map((id) => normalizeName(id)),
124
+ ...declared,
125
+ ...targets.map((item) => item.provider).filter(Boolean),
126
+ // Unknown aliases may still carry a model from a known provider.
127
+ ...(!declared.length || target.conflict ? [inferred] : []),
128
+ ].filter(Boolean).map(normalizeName));
129
+ return (wantedProvider ? ids.has(wantedProvider) : ids.has(wanted));
107
130
  }
108
- if (!model) return false;
109
- const keys = modelKeys(model, config);
110
- const hit = (name) => [...modelKeys(name, config)].some((k) => keys.has(k));
111
- if (scope === 'model') return hit(key.replace(/^model:/i, ''));
112
- const tier = scope === 'tier' && key.match(/^tier:([^:]+):heavy$/i)?.[1].toLowerCase();
131
+
132
+ const modelMatch = (name) => {
133
+ if (!model) return false;
134
+ const keys = modelKeys(model, config);
135
+ return [...modelKeys(name, config)].some((candidate) => keys.has(candidate));
136
+ };
137
+ if (scope === 'model') {
138
+ const match = key.match(/^model:([^:]+):(.+)$/i);
139
+ if (match) {
140
+ const wantedProvider = canonicalProvider(match[1]) ?? normalizeName(match[1]);
141
+ return targets.some((item) => item.provider
142
+ && normalizeName(item.provider) === wantedProvider && modelMatch(match[2]));
143
+ }
144
+ return modelMatch(key.replace(/^model:/i, ''));
145
+ }
146
+
147
+ const tier = key.match(/^tier:([^:]+):([a-z0-9-]+)$/i);
113
148
  if (!tier) return false;
114
- const configured = config?.tiers?.[tier]?.heavyModels;
115
- return (isStringList(configured) ? configured : HEAVY_MODELS[tier] ?? []).some(hit);
149
+ const [, providerKey, pool] = tier;
150
+ const wantedProvider = canonicalProvider(providerKey) ?? normalizeName(providerKey);
151
+ if (pool.toLowerCase() === 'heavy') {
152
+ const configured = config?.tiers?.[providerKey.toLowerCase()]?.heavyModels;
153
+ const legacyModels = isStringList(configured) ? configured : HEAVY_MODELS[providerKey.toLowerCase()] ?? [];
154
+ return legacyModels.some(modelMatch) || targets.some((item) => normalizeName(item.provider ?? '') === wantedProvider
155
+ && item.pool === SCARCE_POOL[providerKey.toLowerCase()]);
156
+ }
157
+ return targets.some((item) => normalizeName(item.provider ?? '') === wantedProvider && item.pool === pool.toLowerCase());
116
158
  }
117
159
 
118
160
  /** The matching active lock that ends last, or null. A missing or unknown provider is inferred from the model. */
119
- export function isLocked(data, { provider, model, config } = {}, now = Date.now()) {
120
- const request = { provider, model, config };
161
+ export function isLocked(data, { provider, providers, model, config } = {}, now = Date.now()) {
162
+ const request = { provider, providers, model, config };
121
163
  let lock = null;
122
164
  for (const [key, value] of Object.entries(data)) {
123
165
  const until = untilOf(value);