t3-auto-build 1.0.0 → 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
@@ -1,86 +1,112 @@
1
1
  #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
2
4
  import { HEAVY_MODELS } from '../lib/detect.mjs';
3
5
  import { doctor } from '../lib/doctor.mjs';
4
- 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';
5
8
  import { MODULES, readManifest } from '../lib/manifest.mjs';
6
- import { CliError, resolveTarget } from '../lib/paths.mjs';
9
+ import { CliError, PACKAGE_ROOT, resolveTarget } from '../lib/paths.mjs';
7
10
  import { syncModels } from '../lib/probe.mjs';
8
- 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';
9
13
  import { QUOTA_WINDOWS, quotaCheck, quotaClear, quotaSet, quotaStatus } from '../lib/quota.mjs';
14
+ import { CONFIG_FILE, readJson } from '../hooks/_shared.mjs';
10
15
 
11
16
  const USAGE = `Usage: t3-auto-build <command> [options]
12
17
 
13
18
  Commands:
14
- init install or update (interactive unless --yes)
15
- doctor check an installation
16
- uninstall remove what init installed, keeping your edits
17
- sync-models probe the models and update the allowlist
18
- quota set <subject> lock a provider (claude, codex, antigravity) or a model
19
- quota status show active locks and drop expired ones
20
- quota clear [subject] remove the locks of a provider or model (or --all)
21
- quota check [provider] run the official login status commands
22
-
23
- Options:
24
- --target <dir> config dir (default: $CLAUDE_CONFIG_DIR, else ~/.claude)
25
- -h, --help show this help
26
- init only:
27
- --preset <name> ${PRESETS.join(' | ')}
28
- --modules <name> ${MODULES.join(' | ')}
29
- --compaction <n> auto-compaction threshold, 1-100
30
- --tiers <list> provider:plan[:weekday], comma separated, e.g. claude:max,codex:pro
31
- --probe run sync-models after installing (spends real quota)
32
- --yes do not prompt
33
- sync-models only:
34
- --dry-run show the result without writing. Note: sync-models --dry-run
35
- still executes live probes (spends real quota) but writes nothing.
36
- --providers <list> only these providers, comma separated
37
- --yes write without asking
38
- init and sync-models:
39
- --force back up your edited files to .bak, then overwrite. sync-models applies it
40
- to a hand-edited SKILL.md (default: skip it with a warning)
41
- quota set only (one window, default --burst):
42
- --burst 10 minutes
43
- --5h 5 hours
44
- --weekly until the tier's weekly reset day, else 7 days
45
- --until <when> ISO time, or a duration such as 90m or 1w2d
46
- --reason <text> note shown by quota status
47
- quota clear only:
48
- --all remove every lock`;
49
-
50
- const VALUE_FLAGS = ['target', 'preset', 'modules', 'compaction', 'tiers', 'providers', 'until', 'reason'];
51
- const SWITCHES = ['yes', 'force', 'help', '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];
52
86
  const COMMAND_FLAGS = {
53
- init: ['preset', 'modules', 'compaction', 'tiers', 'probe', 'yes', 'force'],
54
- doctor: [],
55
- uninstall: [],
56
- 'sync-models': ['dry-run', 'providers', 'yes', 'force'],
57
- 'quota set': [...QUOTA_WINDOWS, 'until', 'reason'],
58
- 'quota status': [],
59
- 'quota clear': ['all'],
60
- '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': [],
61
94
  };
62
- // [min, max] positional arguments after the command.
63
- 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] };
64
96
 
65
97
  function parseArgs(argv) {
66
98
  const flags = {};
67
99
  const positional = [];
68
100
  for (let i = 0; i < argv.length; i += 1) {
69
- const argument = argv[i] === '-h' ? '--help' : argv[i];
70
- if (!argument.startsWith('-')) {
71
- positional.push(argument);
72
- continue;
73
- }
101
+ const argument = { '-h': '--help', '-v': '--version' }[argv[i]] ?? argv[i];
102
+ if (!argument.startsWith('-')) { positional.push(argument); continue; }
74
103
  const [, name, inline] = argument.match(/^--([^=]+)(?:=(.*))?$/s) ?? [];
75
- if (SWITCHES.includes(name) && inline === undefined) {
76
- flags[name] = true;
77
- } else if (VALUE_FLAGS.includes(name)) {
104
+ if (SWITCHES.includes(name) && inline === undefined) flags[name] = true;
105
+ else if (VALUE_FLAGS.includes(name)) {
78
106
  const value = inline ?? argv[(i += 1)];
79
107
  if (!value || (inline === undefined && value.startsWith('--'))) throw new CliError(`--${name} needs a value`, 2);
80
108
  flags[name] = value;
81
- } else {
82
- throw new CliError(`unknown option ${argument}`, 2);
83
- }
109
+ } else throw new CliError(`unknown option ${argument}`, 2);
84
110
  }
85
111
  return { flags, positional };
86
112
  }
@@ -91,25 +117,35 @@ function parseProviders(value) {
91
117
  return names.map((name) => parseChoice(name, Object.keys(HEAVY_MODELS), 'provider'));
92
118
  }
93
119
 
94
- async function sync(target, { yes = false, dryRun = false, force = false, providers }) {
95
- if (!yes && !dryRun && !process.stdin.isTTY) {
96
- 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;
97
136
  }
98
- // 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);
99
138
  const manifest = readManifest(target);
100
- if (!dryRun && !(manifest && wantsAuto(manifest.modules))) {
101
- throw new CliError(`no auto-build installation in ${target}; run init first`);
102
- }
139
+ if (!dryRun && !(manifest && wantsAuto(manifest.modules))) throw new CliError(`no auto-build installation in ${target}; run init first`);
103
140
  let declined = false;
104
141
  const confirm = async ({ allowlist, planRestricted, cooldowns, changed }) => {
105
142
  if (force || changed || Object.keys(cooldowns).length) {
106
143
  console.log(JSON.stringify({ allowlist, planRestricted, cooldowns }, null, 2));
107
144
  if (await confirmYes(`Write these changes to ${target}? [y/N] `)) return true;
108
145
  }
109
- declined = true;
110
- return false;
146
+ declined = true; return false;
111
147
  };
112
- const summary = await syncModels(target, { providers, dryRun, yes, force, confirm });
148
+ const summary = await syncModels(target, { providers, dryRun, yes, refresh, probeScarce, confirm });
113
149
  if (dryRun) {
114
150
  const { allowlist, planRestricted, cooldowns, changed } = summary;
115
151
  console.log(JSON.stringify({ allowlist, planRestricted, cooldowns, changed }, null, 2));
@@ -118,23 +154,56 @@ async function sync(target, { yes = false, dryRun = false, force = false, provid
118
154
  }
119
155
 
120
156
  async function init(target, flags) {
121
- let options = {
157
+ const options = {
122
158
  force: flags.force,
123
159
  preset: flags.preset === undefined ? undefined : parseChoice(flags.preset, PRESETS, 'preset'),
124
160
  modules: flags.modules === undefined ? undefined : parseChoice(flags.modules, MODULES, 'modules'),
125
161
  compaction: flags.compaction === undefined ? undefined : parsePercent(flags.compaction),
126
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'],
127
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;
128
176
  if (!flags.yes) {
129
- if (!process.stdin.isTTY) throw new CliError('no interactive terminal; re-run with --yes (and --preset/--modules/--compaction)', 2);
130
- 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);
131
179
  }
132
- install(target, options);
180
+ install(target, finalOptions);
133
181
  if (!flags.probe) return;
134
- if (wantsAuto(readManifest(target).modules)) await sync(target, { yes: flags.yes });
182
+ if (wantsAuto(readManifest(target).modules)) await sync(target, { yes: true });
135
183
  else console.log('warning: --probe does not apply to the core module; ignored');
136
184
  }
137
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
+
138
207
  function quota(action, target, subject, flags) {
139
208
  if (action === 'status') return quotaStatus(target);
140
209
  if (action === 'check') return quotaCheck(target, { providers: subject === undefined ? undefined : [subject] });
@@ -144,28 +213,29 @@ function quota(action, target, subject, flags) {
144
213
  }
145
214
  const chosen = [...QUOTA_WINDOWS, 'until'].filter((name) => flags[name] !== undefined);
146
215
  if (chosen.length > 1) throw new CliError(`use only one of ${chosen.map((name) => `--${name}`).join(', ')}`, 2);
147
- return quotaSet(target, subject, {
148
- window: chosen[0] === 'until' ? undefined : chosen[0], until: flags.until, reason: flags.reason,
149
- });
216
+ return quotaSet(target, subject, { window: chosen[0] === 'until' ? undefined : chosen[0], until: flags.until, reason: flags.reason, pool: flags.pool });
150
217
  }
151
218
 
152
219
  async function main(argv) {
153
220
  const { flags, positional } = parseArgs(argv);
154
221
  if (flags.help) return console.log(USAGE);
222
+ if (flags.version) return console.log(JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8')).version);
155
223
  const [first, ...rest] = positional;
156
- const command = first === 'quota' ? `quota ${rest.shift()}` : first;
224
+ const command = first === 'quota' || first === 'availability' ? `${first} ${rest.shift()}` : first;
157
225
  const [min, max] = ARGUMENTS[command] ?? [0, 0];
158
226
  if (!Object.hasOwn(COMMAND_FLAGS, command) || rest.length < min || rest.length > max) throw new CliError(USAGE, 2);
159
227
  const stray = Object.keys(flags).find((name) => name !== 'target' && !COMMAND_FLAGS[command].includes(name));
160
228
  if (stray) throw new CliError(`--${stray} is not valid with ${command}`, 2);
161
229
  const target = resolveTarget(flags.target);
162
-
163
230
  if (command === 'init') await init(target, flags);
231
+ else if (command === 'upgrade') await upgrade(target);
164
232
  else if (command === 'doctor') process.exitCode = doctor(target);
165
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);
166
236
  else if (command === 'sync-models') {
167
237
  const providers = flags.providers === undefined ? undefined : parseProviders(flags.providers);
168
- 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 });
169
239
  } else await quota(command.slice('quota '.length), target, rest[0], flags);
170
240
  }
171
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);