t3-auto-build 2.0.2 → 2.1.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/CHANGELOG.md CHANGED
@@ -4,6 +4,25 @@ All notable changes to this project are documented here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [2.1.0] - 2026-11-26
8
+
9
+ ### Fixed
10
+
11
+ - Quota and cooldown lock matching (`hooks/_quota.mjs`): normalized `tier:` provider alias lookups (`config.tiers`, `HEAVY_MODELS`, `SCARCE_POOL`), gated legacy heavy-model matching on provider match to prevent cross-host leaks, and isolated custom instance keys (`tier:codex-2:*`, `model:codex-2:*`) from canonical providers.
12
+ - Rate-limit clock parsing (`hooks/_quota.mjs`): `parseRateLimit()` now honors explicit `UTC`/`GMT`/`Z` clock times via UTC date methods and only enters the `5h` branch when `clockIn()` parses a valid time.
13
+ - Quota CLI (`lib/quota.mjs`): `quotaSet()` now uses `host` for `config.tiers` lookup (supporting custom `modelIds`) and falls back to `'heavy'` when `SCARCE_POOL[host]` is absent; `countdown()` returns `'unknown'` for non-finite values and `'0s'` for non-positive durations; `quotaClear()` fixes malformed stub scope for qualified models, matches `tier:` provider aliases via `exactProvider`, and handles display-name/cased qualified model keys.
14
+ - Probe cooldowns (`lib/probe.mjs`): `syncModels()` now forwards `{ now }` to `writeCooldowns()`, preserves the longest `until` per cooldown key across probe results in the same run, and exits with code `2` on unknown providers.
15
+ - Availability & restrictions (`hooks/_shared.mjs`, `lib/discover.mjs`, `bin/cli.mjs`): aligned staleness boundary to strict `<` with `ttlMs > 0` fallback, preserved live manual marks without a parseable `until` in `put()`, shared normalized `isPlanRestricted()`, and added optional `config` forwarding to `restrictedBy()` for `modelIds` aliases.
16
+ - Doctor & install hardening (`lib/doctor.mjs`, `lib/install.mjs`): `doctor` skips `tierId === 'none'` warnings, guards `NaN` availability age, validates `isFile()` / `fileHash()` safely inside `attempt()`, checks `isObject()` for cooldown JSON, and guards `CONFIG_FILE`, `AVAILABILITY_FILE`, and `COOLDOWN_FILE` with `safePath()`; `completeConfig()` no longer masks `ladders: null` before validation.
17
+ - CLI & hook guards (`bin/cli.mjs`, `hooks/pre-compact.mjs`, `hooks/pre-tool-use.mjs`): `sync-models --apply --dry-run` no longer writes config or `SKILL.md`; `pre-compact.mjs` renders availability marks whose model names contain spaces or instance hyphens while rejecting control characters; `pre-tool-use.mjs` enforces per-provider allowlist membership (blocking bare `claude-*` calls when native Claude has no allowlisted models).
18
+ - Test suite: fixed false-positive cooldown test in `test/v2-edge.test.mjs` and expanded regression coverage to 224 passing tests.
19
+
20
+ ## [2.0.2] - 2026-11-26
21
+
22
+ ### Changed
23
+
24
+ - Document starting-model orchestrator behavior, task-based starting-model recommendations,
25
+ hook guard scope, and same-thread follow-up rules in README and the skill template.
7
26
  ## [2.0.1] - 2026-11-26
8
27
 
9
28
  ### Added
@@ -109,6 +128,8 @@ See [Migrating from v1](README.md#migrating-from-v1).
109
128
  - Hardened the recursive `rm` guard, cooldown handling, the pre-compact state boundary and
110
129
  `sync-models --force`.
111
130
 
131
+ [2.1.0]: https://github.com/mirceas94/t3-auto-build/compare/v2.0.2...v2.1.0
132
+ [2.0.2]: https://github.com/mirceas94/t3-auto-build/compare/v2.0.1...v2.0.2
112
133
  [2.0.1]: https://github.com/mirceas94/t3-auto-build/compare/v2.0.0...v2.0.1
113
134
  [2.0.0]: https://github.com/mirceas94/t3-auto-build/compare/v1.0.1...v2.0.0
114
135
  [1.0.1]: https://github.com/mirceas94/t3-auto-build/compare/v1.0.0...v1.0.1
package/README.md CHANGED
@@ -359,7 +359,7 @@ t3-auto-build uninstall
359
359
  | `--json` | check-models | Machine-readable result. |
360
360
  | `--auto` | sync-models | Write without confirmation, like `--yes`. |
361
361
  | `--apply` | sync-models | Promote newer versions from recorded drift. |
362
- | `--dry-run` | sync-models | Probe and print the result; write nothing. **Still spends real quota.** |
362
+ | `--dry-run` | sync-models | Probe (or preview `--apply` drift) and print the result; write nothing. **Live probes still spend real quota.** |
363
363
  | `--providers <list>` | sync-models | Only these of `claude`, `codex`, `antigravity`; comma separated. |
364
364
  | `--ttl <duration>` | availability mark | `1m` to `30d`, default `24h`. |
365
365
  | `--pool <name>` | quota set | Lock a pool: `standard`, `fable`, `astra`, `third-party-claude`, or another lowercase name. |
@@ -568,7 +568,7 @@ A v1 config has no `schemaVersion` and may also use `tiers` and `planRestricted`
568
568
  - Model names ignore case and punctuation runs, so `claude-sonnet-5-5` matches `Claude Sonnet 5.5`.
569
569
  Provider cooldowns match the provider name or the T3 provider id (`claudeAgent`, `codex`,
570
570
  `antigravity`). `provider:codex` also covers a custom instance such as `codex-2`;
571
- `provider:codex-2` covers only that instance.
571
+ `provider:codex-2`, `tier:codex-2:<pool>` and `model:codex-2:<id>` cover only that instance.
572
572
  - Keys missing from the file come from its `preset` (`tri-provider` when unset or `custom`). The
573
573
  hooks fall back to full defaults on an unknown `schemaVersion`.
574
574
  - Rendering drops banned and non-allowlisted ladder entries. If a ladder ends up empty, `init` fails
@@ -612,8 +612,8 @@ PreToolUse guards:
612
612
  contains a command substitution; is the current directory or `*`; has a `..` or `.git` segment; or
613
613
  is a dot-file glob such as `.*`.
614
614
  - **Delegate calls** (`delegate_task`), in order: [speed mode](#speed-mode-guard), provider/model
615
- conflict, retired, user-banned, plan-restricted, availability, allowlist (a trailing `-YYYYMMDD`
616
- suffix is ignored), then cooldown locks.
615
+ conflict, retired, user-banned, plan-restricted, availability, per-provider allowlist (a trailing
616
+ `-YYYYMMDD` suffix is ignored), then cooldown locks.
617
617
 
618
618
  Empty or unparsable hook input, and unreadable cooldown data, produce exit 0 (fail open). An invalid
619
619
  config value produces a warning and a default, so the allowlist is still enforced. The secret and
package/bin/cli.mjs CHANGED
@@ -11,7 +11,7 @@ import { syncModels } from '../lib/probe.mjs';
11
11
  import { CATALOG, PROVIDERS } from '../lib/plans.mjs';
12
12
  import { confirmYes, initPrompts, parseChoice, parsePercent, parseTierSpec, TIER_FLAGS } from '../lib/prompt.mjs';
13
13
  import { QUOTA_WINDOWS, quotaCheck, quotaClear, quotaSet, quotaStatus } from '../lib/quota.mjs';
14
- import { CONFIG_FILE, readJson } from '../hooks/_shared.mjs';
14
+ import { AVAILABILITY_FILE, CONFIG_FILE, readAvailability, readJson } from '../hooks/_shared.mjs';
15
15
 
16
16
  const USAGE = `Usage: t3-auto-build <command> [options]
17
17
 
@@ -131,8 +131,9 @@ async function sync(target, { yes = false, dryRun = false, force = false, provid
131
131
  const result = applyDrift(config, availability);
132
132
  for (const promotion of result.promoted) console.log(`promoted ${promotion.provider}:${promotion.from} -> ${promotion.provider}:${promotion.to}`);
133
133
  for (const unknown of result.unknown) console.log(`unknown family ${unknown.provider}:${unknown.model} (left disabled)`);
134
- if (result.promoted.length) await syncConfig(target, result.config, { force, log: console.log });
135
- else console.log('no known model drift to apply');
134
+ if (!result.promoted.length) console.log('no known model drift to apply');
135
+ else if (dryRun) console.log('nothing was written');
136
+ else await syncConfig(target, result.config, { force, log: console.log });
136
137
  return;
137
138
  }
138
139
  if (!yes && !dryRun && !process.stdin.isTTY) throw new CliError('no interactive terminal; re-run with --auto (or --dry-run); nothing was written', 2);
@@ -202,10 +203,11 @@ async function check(target, flags) {
202
203
 
203
204
  function availability(action, target, args, flags) {
204
205
  if (action === 'status') {
205
- const data = readAvailabilityFile(target);
206
+ const { data, stale } = readAvailability(path.join(target, AVAILABILITY_FILE));
206
207
  if (!data) { console.log('availability cache missing or malformed'); return; }
207
208
  const age = Math.max(0, Date.now() - Date.parse(data.checkedAt));
208
- console.log(`availability cache ${age <= (data.ttlMs ?? 43_200_000) ? 'fresh' : 'stale'} (${(age / 3_600_000).toFixed(1)}h old)`);
209
+ const ageText = Number.isFinite(age) ? ` (${(age / 3_600_000).toFixed(1)}h old)` : '';
210
+ console.log(`availability cache ${stale ? 'stale' : 'fresh'}${ageText}`);
209
211
  for (const [ref, entry] of Object.entries(data.models ?? {})) console.log(`${ref}: ${entry.status}${entry.reason ? ` (${entry.reason})` : ''}`);
210
212
  console.log(`drift: ${(data.discoveredNew ?? []).length} discovered, ${(data.missingConfigured ?? []).length} missing configured`);
211
213
  } else markAvailability({ configDir: target, ref: args[0], status: args[1], ttl: flags.ttl, reason: flags.reason });
package/hooks/_quota.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {
5
- canonicalProvider, inferProvider, isObject, isStringList, modelKeys, normalizeName, parseJson,
5
+ canonicalProvider, exactProvider, inferProvider, isObject, isStringList, modelKeys, normalizeName, parseJson,
6
6
  resolveTarget, warn,
7
7
  } from './_shared.mjs';
8
8
 
@@ -147,9 +147,12 @@ function matches(key, scope, { provider, providers, model, config }) {
147
147
  if (scope === 'model') {
148
148
  const match = key.match(/^model:([^:]+):(.+)$/i);
149
149
  if (match) {
150
- const wantedProvider = canonicalProvider(match[1]) ?? normalizeName(match[1]);
151
- return targets.some((item) => item.provider
152
- && normalizeName(item.provider) === wantedProvider && modelMatch(match[2]));
150
+ const exact = exactProvider(match[1]);
151
+ const wanted = exact ?? normalizeName(match[1]);
152
+ const hostMatch = exact
153
+ ? (item) => normalizeName(item.provider ?? '') === exact
154
+ : () => declarations.some((id) => normalizeName(id) === wanted);
155
+ return targets.some((item) => hostMatch(item) && modelMatch(match[2]));
153
156
  }
154
157
  return modelMatch(key.replace(/^model:/i, ''));
155
158
  }
@@ -157,14 +160,19 @@ function matches(key, scope, { provider, providers, model, config }) {
157
160
  const tier = key.match(/^tier:([^:]+):([a-z0-9-]+)$/i);
158
161
  if (!tier) return false;
159
162
  const [, providerKey, pool] = tier;
160
- const wantedProvider = canonicalProvider(providerKey) ?? normalizeName(providerKey);
163
+ const exact = exactProvider(providerKey);
164
+ const wanted = exact ?? normalizeName(providerKey);
165
+ const hostMatch = exact
166
+ ? (item) => normalizeName(item.provider ?? '') === exact
167
+ : () => declarations.some((id) => normalizeName(id) === wanted);
161
168
  if (pool.toLowerCase() === 'heavy') {
162
- const configured = config?.tiers?.[providerKey.toLowerCase()]?.heavyModels;
163
- const legacyModels = isStringList(configured) ? configured : HEAVY_MODELS[providerKey.toLowerCase()] ?? [];
164
- return legacyModels.some(modelMatch) || targets.some((item) => normalizeName(item.provider ?? '') === wantedProvider
165
- && item.pool === SCARCE_POOL[providerKey.toLowerCase()]);
169
+ const family = exact ?? canonicalProvider(providerKey) ?? wanted;
170
+ const configured = config?.tiers?.[family]?.heavyModels;
171
+ const legacyModels = isStringList(configured) ? configured : HEAVY_MODELS[family] ?? [];
172
+ return targets.some((item) => hostMatch(item)
173
+ && (legacyModels.some(modelMatch) || item.pool === SCARCE_POOL[family]));
166
174
  }
167
- return targets.some((item) => normalizeName(item.provider ?? '') === wantedProvider && item.pool === pool.toLowerCase());
175
+ return targets.some((item) => hostMatch(item) && item.pool === pool.toLowerCase());
168
176
  }
169
177
 
170
178
  /** The matching active lock that ends last, or null. A missing or unknown provider is inferred from the model. */
@@ -205,7 +213,7 @@ const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
205
213
  const DAY_NAME = '(?:mon(?:day)?|tue(?:s(?:day)?)?|wed(?:nesday)?|thu(?:r(?:s(?:day)?)?)?|fri(?:day)?|sat(?:urday)?|sun(?:day)?)\\b';
206
214
  const RESET_DAY = new RegExp(`\\bresets?\\s+(?:on\\s+)?(${DAY_NAME})`, 'i');
207
215
  const WEEKLY = /\bweek(?:ly)?\b/i;
208
- const CLOCK = /\b(?:resets?(?:\s+at)?|try again at)\s+(\d{1,2})(?::(\d{2})(?:\s*([ap])\.?m\b)?|\s*([ap])\.?m\b)/i;
216
+ const CLOCK = /\b(?:resets?(?:\s+at)?|try again at)\s+(\d{1,2})(?::(\d{2})(?:\s*([ap])\.?m\b\.?)?|\s*([ap])\.?m\b\.?)(?:\s*(utc|gmt|z)\b)?/i;
209
217
  const FIVE_HOUR = /\b(?:5|five)[\s-]*(?:h|hrs?|hours?)\b|\b(?:session|usage) limit\b|\bin\s+\d+\s*(?:h(?![a-z])|hrs?\b|hours?\b)/i;
210
218
  const UNIT = '(?:days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)(?![a-z])';
211
219
  const DURATION = new RegExp(`\\b(?:in|after)\\s+((?:\\d+\\s*${UNIT}[\\s,]*(?:and\\s+)?)+)`, 'i');
@@ -219,18 +227,24 @@ function durationIn(text) {
219
227
  return parts.length ? parts.reduce((total, [, n, unit]) => total + n * UNIT_MS[unit.toLowerCase()], 0) : NaN;
220
228
  }
221
229
 
222
- /** Next local occurrence of a "resets 3pm" / "resets at 15:30" time. */
230
+ /** Next occurrence of a "resets 3pm" / "resets at 15:30" (or "... UTC") time. */
223
231
  function clockIn(text, now) {
224
232
  const match = text.match(CLOCK);
225
233
  if (!match) return NaN;
226
234
  const half = (match[3] ?? match[4])?.toLowerCase();
235
+ const utc = Boolean(match[5]);
227
236
  let hour = Number(match[1]);
228
237
  const minute = Number(match[2] ?? 0);
229
238
  if (minute > 59 || (half ? hour < 1 || hour > 12 : hour > 23)) return NaN;
230
239
  if (half) hour = (hour % 12) + (half === 'p' ? 12 : 0);
231
240
  const date = new Date(now);
232
- date.setHours(hour, minute, 0, 0);
233
- if (date.getTime() <= now) date.setDate(date.getDate() + 1);
241
+ if (utc) {
242
+ date.setUTCHours(hour, minute, 0, 0);
243
+ if (date.getTime() <= now) date.setUTCDate(date.getUTCDate() + 1);
244
+ } else {
245
+ date.setHours(hour, minute, 0, 0);
246
+ if (date.getTime() <= now) date.setDate(date.getDate() + 1);
247
+ }
234
248
  return date.getTime();
235
249
  }
236
250
 
@@ -256,9 +270,10 @@ export function parseRateLimit(text, { now = Date.now(), sharing, resetDay, retr
256
270
  if (WEEKLY.test(message) || day) {
257
271
  return result('weekly', 'provider', isoIn(message), weekdayAt(day, at), weekdayAt(resetDay, at), at + 7 * DAY);
258
272
  }
259
- if (FIVE_HOUR.test(message) || CLOCK.test(message)) {
273
+ const clock = clockIn(message, at);
274
+ if (FIVE_HOUR.test(message) || !Number.isNaN(clock)) {
260
275
  return result('5h', sharing === 'heavy-tier-only' ? 'tier' : 'provider',
261
- isoIn(message), at + durationIn(message), clockIn(message, at), at + 300 * MINUTE);
276
+ isoIn(message), at + durationIn(message), clock, at + 300 * MINUTE);
262
277
  }
263
278
  return result('burst', 'model', at + Number(retryAfter ?? NaN) * 1000,
264
279
  at + Number(message.match(RETRY_AFTER)?.[1] ?? NaN) * 1000, at + durationIn(message), at + 10 * MINUTE);
package/hooks/_shared.mjs CHANGED
@@ -285,20 +285,34 @@ export function readAvailability(file, now = Date.now()) {
285
285
  }
286
286
 
287
287
  /** The entry restricting provider:model, or null. Takes readAvailability's data (or its whole result). */
288
- export function restrictedBy(availability, provider, model, now = Date.now()) {
288
+ export function restrictedBy(availability, provider, model, now = Date.now(), config) {
289
289
  const wanted = canonicalProvider(provider);
290
290
  if (!wanted || typeof model !== 'string') return null;
291
- const keys = modelKeys(model);
291
+ const keys = modelKeys(model, config);
292
292
  const models = (availability?.data ?? availability)?.models;
293
293
  return Object.entries(isObject(models) ? models : {}).find(([ref, entry]) => {
294
294
  const [, host, name] = ref.match(/^([^:]+):(.+)$/) ?? [];
295
- return name !== undefined && canonicalProvider(host) === wanted && [...modelKeys(name)].some((key) => keys.has(key))
295
+ return name !== undefined && canonicalProvider(host) === wanted && [...modelKeys(name, config)].some((key) => keys.has(key))
296
296
  && ['plan-restricted', 'unavailable'].includes(entry?.status)
297
297
  // An unreadable "until" keeps the restriction.
298
298
  && (entry.until === undefined || !(Date.parse(entry.until) <= now));
299
299
  })?.[1] ?? null;
300
300
  }
301
301
 
302
+ /** "provider:model" restricts that hosting only; a bare model restricts every hosting. */
303
+ export function isPlanRestricted(refs, provider, model, config) {
304
+ if (!Array.isArray(refs) || typeof model !== 'string') return false;
305
+ const target = canonicalProvider(provider);
306
+ const keys = modelKeys(model, config);
307
+ return refs.some((ref) => {
308
+ if (typeof ref !== 'string') return false;
309
+ const [, host, name] = ref.match(/^([^:]+):(.+)$/) ?? [];
310
+ const hosting = canonicalProvider(host);
311
+ if (hosting && hosting !== target) return false;
312
+ return [...modelKeys(hosting ? name : ref, config)].some((key) => keys.has(key));
313
+ });
314
+ }
315
+
302
316
  /** PowerShell-like "$($value)" stringification. */
303
317
  export function str(value) {
304
318
  if (value === undefined || value === null) return '';
@@ -23,7 +23,7 @@ function unavailable(configDir) {
23
23
  const { data } = readAvailability(path.join(configDir, AVAILABILITY_FILE));
24
24
  return Object.keys(data?.models ?? {}).flatMap((ref) => {
25
25
  // The file's text goes into the session context, so only plain refs are echoed.
26
- const [, host, model] = ref.match(/^([a-z]{1,20}):([\w.-]{1,60})$/i) ?? [];
26
+ const [, host, model] = ref.match(/^([a-z0-9-]{1,20}):([\w .:/()[\]-]{1,80})$/i) ?? [];
27
27
  const entry = model && restrictedBy(data, host, model);
28
28
  return entry ? [`${ref} (${entry.status})`] : [];
29
29
  });
@@ -3,8 +3,8 @@ import path from 'node:path';
3
3
  import { isLocked, readCooldowns } from './_quota.mjs';
4
4
  import {
5
5
  AVAILABILITY_FILE, COOLDOWN_FILE, canonicalProvider, configDirOf, effectiveAllowlist, fastModeRequested, isBanned,
6
- loadConfig, matchRetired, modelKeys, normalizeModel, payloadProblem, prop, readAvailability, readPayload, resolveTarget,
7
- restrictedBy, str, warn,
6
+ isPlanRestricted, loadConfig, matchRetired, modelKeys, normalizeModel, payloadProblem, prop, readAvailability,
7
+ readPayload, resolveTarget, restrictedBy, str, warn,
8
8
  } from './_shared.mjs';
9
9
 
10
10
  // (?=\n?$) mirrors .NET's "$", which also matches before a trailing newline.
@@ -76,18 +76,8 @@ function cooldownBlock(configDir, models, providers, config) {
76
76
  return null;
77
77
  }
78
78
 
79
- /** "provider:model" restricts that hosting only; a bare model restricts every hosting. */
80
- function planRestricted(refs, provider, keys, config) {
81
- return refs.some((ref) => {
82
- const [, host, name] = ref.match(/^([^:]+):(.+)$/) ?? [];
83
- const hosting = canonicalProvider(host);
84
- if (hosting && hosting !== provider) return false;
85
- return [...modelKeys(hosting ? name : ref, config)].some((key) => keys.includes(key));
86
- });
87
- }
88
-
89
79
  /** Why one requested model is refused, or null. The order of the checks decides which reason is reported. */
90
- function modelBlock(model, { providers, config, availability, allowed, known }) {
80
+ function modelBlock(model, { providers, config, availability, allowed, known, knownByProvider, allCanonical }) {
91
81
  const target = resolveTarget({ providers, model }, config);
92
82
  if (target.conflict) return `Blocked by allowlist hook: ${target.conflict}.`;
93
83
  const keys = [...modelKeys(model, config)];
@@ -97,16 +87,19 @@ function modelBlock(model, { providers, config, availability, allowed, known })
97
87
  if ([model, normalizeModel(model)].some((name) => isBanned(name, config.bannedModels))) {
98
88
  return `Blocked by allowlist hook: model '${model}' is banned.`;
99
89
  }
100
- if (planRestricted(config.planRestrictedModels, target.provider, keys, config)) {
90
+ if (isPlanRestricted(config.planRestrictedModels, target.provider, model, config)) {
101
91
  return `Blocked by plan hook: model '${model}' is plan-restricted on the configured subscription.`;
102
92
  }
103
- const restriction = keys.map((key) => restrictedBy(availability, target.provider, key)).find(Boolean);
93
+ const restriction = restrictedBy(availability, target.provider, model, Date.now(), config);
104
94
  if (restriction) {
105
95
  const until = Date.parse(restriction.until);
106
96
  return `Blocked by availability hook: model '${model}' is ${restriction.status} on ${target.provider}`
107
97
  + `${Number.isNaN(until) ? '' : ` until ${new Date(until).toISOString()}`}.`;
108
98
  }
109
- if (!keys.some((key) => known.has(key))) {
99
+ const perProvider = config.schemaVersion === 2 || target.crossHosted
100
+ || providers.some((p) => canonicalProvider(p) !== null) || allCanonical;
101
+ const pool = perProvider && target.provider ? (knownByProvider.get(target.provider) ?? new Set()) : known;
102
+ if (!keys.some((key) => pool.has(key))) {
110
103
  return `Blocked by allowlist hook: model '${model}' is outside the ${allowed.length}-model allowlist.`;
111
104
  }
112
105
  return null;
@@ -146,11 +139,21 @@ function blockReason(payload) {
146
139
  }
147
140
  if (!models.length && !providers.length) return null;
148
141
  if (models.length) {
149
- const allowed = effectiveAllowlist(config).flatMap(([, names]) => names);
142
+ const groups = effectiveAllowlist(config);
143
+ const allowed = groups.flatMap(([, names]) => names);
150
144
  const known = new Set(allowed.flatMap((name) => [...modelKeys(name)]));
145
+ const knownByProvider = new Map();
146
+ for (const [group, names] of groups) {
147
+ const provider = canonicalProvider(group);
148
+ if (!provider) continue;
149
+ const set = knownByProvider.get(provider) ?? new Set();
150
+ for (const name of names) for (const key of modelKeys(name)) set.add(key);
151
+ knownByProvider.set(provider, set);
152
+ }
153
+ const allCanonical = groups.length > 0 && groups.every(([group]) => canonicalProvider(group) !== null);
151
154
  const { data: availability } = readAvailability(path.join(configDir, AVAILABILITY_FILE));
152
155
  for (const model of models) {
153
- const reason = modelBlock(model, { providers, config, availability, allowed, known });
156
+ const reason = modelBlock(model, { providers, config, availability, allowed, known, knownByProvider, allCanonical });
154
157
  if (reason) return reason;
155
158
  }
156
159
  }
package/lib/discover.mjs CHANGED
@@ -4,8 +4,9 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {
7
- AVAILABILITY_FILE, COOLDOWN_FILE, RETIRED_MODELS, canonicalProvider, exactProvider, inferProvider, isBanned, isObject, isStringList,
8
- matchRetired, modelKeys, normalizeModel, readAvailability, restrictedBy, warn, which as findOnPath,
7
+ AVAILABILITY_FILE, COOLDOWN_FILE, RETIRED_MODELS, canonicalProvider, exactProvider, inferProvider, isBanned, isObject,
8
+ isPlanRestricted, isStringList, matchRetired, modelKeys, normalizeModel, readAvailability, restrictedBy, warn,
9
+ which as findOnPath,
9
10
  } from '../hooks/_shared.mjs';
10
11
  import { isLocked, prune, readCooldowns, RECHECK_AFTER, withRecheck, writeCooldowns } from '../hooks/_quota.mjs';
11
12
  import { CliError } from './paths.mjs';
@@ -242,7 +243,7 @@ function put(models, provider, model, entry, now) {
242
243
  return name !== undefined && canonicalProvider(host) === provider && sameModel(name, model);
243
244
  });
244
245
  if (entry.source !== 'mark'
245
- && matches.some((ref) => models[ref].source === 'mark' && Date.parse(models[ref].until) > now)) return;
246
+ && matches.some((ref) => models[ref].source === 'mark' && !(Date.parse(models[ref].until) <= now))) return;
246
247
  if (entry.source === 'discover' && matches.some((ref) => models[ref].status !== 'available')) return;
247
248
  for (const ref of matches) delete models[ref];
248
249
  models[`${provider}:${model}`] = entry;
@@ -275,9 +276,8 @@ const isExcluded = (model, config) => matchRetired(model, retiredPatterns(config
275
276
 
276
277
  /** "plan-restricted" or "unavailable" when the config or a live availability entry blocks the model, else null. */
277
278
  function restriction(config, availability, provider, model, now) {
278
- const refs = list(config?.planRestrictedModels);
279
- if (refs.includes(model) || refs.includes(`${provider}:${model}`)) return 'plan-restricted';
280
- return restrictedBy(availability, provider, model, now)?.status ?? null;
279
+ if (isPlanRestricted(list(config?.planRestrictedModels), provider, model, config)) return 'plan-restricted';
280
+ return restrictedBy(availability, provider, model, now, config)?.status ?? null;
281
281
  }
282
282
 
283
283
  /** The stored locks, or {} when the file cannot be read (updateCooldowns has already warned). */
@@ -372,7 +372,7 @@ export async function checkModels({
372
372
  configDir, config, binaries: found.binaries, force, now, runner, which, probe,
373
373
  });
374
374
  const checkedAt = readAvailabilityFile(configDir)?.checkedAt;
375
- const stale = !(now - Date.parse(checkedAt) <= ttlMs);
375
+ const stale = !(now - Date.parse(checkedAt) < ttlMs);
376
376
  const probing = stale || refresh;
377
377
  let results = [];
378
378
  let skippedScarce = [];
@@ -456,7 +456,7 @@ export function applyDrift(config, availability) {
456
456
  const parsed = parseFamily(model);
457
457
  if (!from || !parsed || !supersedes(parsed, parseFamily(from.model) ?? {})) continue;
458
458
  if (matchRetired(model, retiredPatterns(config)) || isBanned(model, bannedTerms(config))) continue;
459
- if (restricted.includes(model) || restricted.includes(`${provider}:${model}`)) continue;
459
+ if (isPlanRestricted(restricted, provider, model, config)) continue;
460
460
  if (mine.some((entry) => sameModel(entry.model, model, config))) continue;
461
461
  const key = `${provider}:${from.model}`;
462
462
  const current = best.get(key);
package/lib/doctor.mjs CHANGED
@@ -49,8 +49,8 @@ function smokeTest(target, report) {
49
49
  for (const name of fs.readdirSync(installed)) {
50
50
  if (name.endsWith('.mjs')) fs.copyFileSync(path.join(installed, name), path.join(hooks, name));
51
51
  }
52
- const config = path.join(target, CONFIG_FILE);
53
- if (fs.existsSync(config)) fs.copyFileSync(config, path.join(sandbox, CONFIG_FILE));
52
+ const config = safePath(target, CONFIG_FILE);
53
+ if (config && fs.existsSync(config) && fs.statSync(config).isFile()) fs.copyFileSync(config, path.join(sandbox, CONFIG_FILE));
54
54
 
55
55
  const check = (script, label, payload, expected) => {
56
56
  const result = spawnSync(process.execPath, [path.join(hooks, script)], {
@@ -94,8 +94,11 @@ export function doctor(target, log = console.log) {
94
94
  const file = safePath(target, relative);
95
95
  if (!file) report('fail', `unsafe path or symlink: ${relative}`);
96
96
  else if (!fs.existsSync(file)) report('fail', `missing: ${relative}`);
97
- else if (manifest.files[relative] !== fileHash(file)) report('warn', `differs from the installed version: ${relative}`);
98
- else report('ok', relative);
97
+ else attempt(() => {
98
+ if (!fs.statSync(file).isFile()) throw new Error(`not a regular file: ${relative}`);
99
+ if (manifest.files[relative] !== fileHash(file)) report('warn', `differs from the installed version: ${relative}`);
100
+ else report('ok', relative);
101
+ });
99
102
  }
100
103
  } else if (failures === 0) {
101
104
  report('fail', `not installed: no manifest in ${target}`);
@@ -103,8 +106,8 @@ export function doctor(target, log = console.log) {
103
106
 
104
107
  const settings = attempt(() => readSettings(target));
105
108
  if (manifest && wantsAuto(manifest.modules)) {
106
- const configPath = path.join(target, CONFIG_FILE);
107
- if (fs.existsSync(configPath)) {
109
+ const configPath = safePath(target, CONFIG_FILE);
110
+ if (configPath && fs.existsSync(configPath)) {
108
111
  attempt(() => {
109
112
  let config;
110
113
  try {
@@ -122,20 +125,26 @@ export function doctor(target, log = console.log) {
122
125
  report('ok', `${CONFIG_FILE} v2 is valid`);
123
126
  for (const provider of PROVIDERS) {
124
127
  const tierId = config.subscriptions[provider];
128
+ if (tierId === 'none') continue;
125
129
  const tier = CATALOG[provider][tierId];
126
130
  if (!tier.cliSupported) report('warn', `${provider} tier ${tierId} is not supported by its CLI`);
127
131
  else if (!which(provider)) report('warn', `${provider} tier ${tierId} is configured but its CLI binary is missing`);
128
132
  }
129
133
  }
130
134
  });
131
- const availabilityPath = path.join(target, AVAILABILITY_FILE);
132
- const { data: availability, stale } = readAvailability(availabilityPath);
133
- if (!availability) report('warn', `${AVAILABILITY_FILE} ${fs.existsSync(availabilityPath) ? 'is malformed' : 'is missing'}; run t3-auto-build check-models`);
134
- else {
135
- const age = Math.max(0, Date.now() - Date.parse(availability.checkedAt));
136
- report(stale ? 'warn' : 'ok', `${AVAILABILITY_FILE} ${stale ? 'is stale' : 'is fresh'} (${(age / 3_600_000).toFixed(1)}h old)`);
137
- if ((availability.discoveredNew ?? []).length || (availability.missingConfigured ?? []).length) {
138
- report('warn', `model drift: ${(availability.discoveredNew ?? []).length} discovered, ${(availability.missingConfigured ?? []).length} missing configured`);
135
+ const availabilityPath = safePath(target, AVAILABILITY_FILE);
136
+ if (!availabilityPath) {
137
+ report('fail', `unsafe path or symlink: ${AVAILABILITY_FILE}`);
138
+ } else {
139
+ const { data: availability, stale } = readAvailability(availabilityPath);
140
+ if (!availability) report('warn', `${AVAILABILITY_FILE} ${fs.existsSync(availabilityPath) ? 'is malformed' : 'is missing'}; run t3-auto-build check-models`);
141
+ else {
142
+ const age = Math.max(0, Date.now() - Date.parse(availability.checkedAt));
143
+ const ageText = Number.isFinite(age) ? ` (${(age / 3_600_000).toFixed(1)}h old)` : '';
144
+ report(stale ? 'warn' : 'ok', `${AVAILABILITY_FILE} ${stale ? 'is stale' : 'is fresh'}${ageText}`);
145
+ if ((availability.discoveredNew ?? []).length || (availability.missingConfigured ?? []).length) {
146
+ report('warn', `model drift: ${(availability.discoveredNew ?? []).length} discovered, ${(availability.missingConfigured ?? []).length} missing configured`);
147
+ }
139
148
  }
140
149
  }
141
150
  }
@@ -152,10 +161,12 @@ export function doctor(target, log = console.log) {
152
161
  if (fs.existsSync(path.join(target, ...HOOKS_DIR.split('/')))) attempt(() => smokeTest(target, report));
153
162
  }
154
163
 
155
- const cooldowns = path.join(target, COOLDOWN_FILE);
156
- if (fs.existsSync(cooldowns)) {
164
+ const cooldowns = safePath(target, COOLDOWN_FILE);
165
+ if (!cooldowns) {
166
+ report('fail', `unsafe path or symlink: ${COOLDOWN_FILE}`);
167
+ } else if (fs.existsSync(cooldowns)) {
157
168
  try {
158
- readJson(cooldowns);
169
+ if (!isObject(readJson(cooldowns))) report('warn', `${COOLDOWN_FILE} is not a JSON object`);
159
170
  } catch {
160
171
  report('warn', `${COOLDOWN_FILE} is not valid JSON`);
161
172
  }
package/lib/install.mjs CHANGED
@@ -58,7 +58,10 @@ export function configProblem(config) {
58
58
  /** The config with missing fields filled from its preset. */
59
59
  export function completeConfig(config) {
60
60
  const preset = loadPreset(PRESETS.includes(config.preset) ? config.preset : PRESETS[0]);
61
- return { ...preset, ...config, ladders: isObject(config.ladders ?? {}) ? { ...preset.ladders, ...config.ladders } : config.ladders };
61
+ const ladders = config.ladders === undefined
62
+ ? { ...preset.ladders }
63
+ : isObject(config.ladders) ? { ...preset.ladders, ...config.ladders } : config.ladders;
64
+ return { ...preset, ...config, ladders };
62
65
  }
63
66
 
64
67
  /** What a v1 install is assumed to pay for: a low paid tier with a CLI. */
package/lib/probe.mjs CHANGED
@@ -72,7 +72,7 @@ const wantedProviders = (providers) => {
72
72
  if (!providers?.length) return () => true;
73
73
  const names = [providers].flat().flatMap((p) => p.split(',')).map((p) => p.trim().toLowerCase()).filter(Boolean);
74
74
  const unknown = names.find((name) => !Object.hasOwn(HEAVY_MODELS, name));
75
- if (unknown) throw new CliError(`unknown provider "${unknown}"; use ${Object.keys(HEAVY_MODELS).join(', ')}`);
75
+ if (unknown) throw new CliError(`unknown provider "${unknown}"; use ${Object.keys(HEAVY_MODELS).join(', ')}`, 2);
76
76
  return (key) => names.includes(key.toLowerCase());
77
77
  };
78
78
 
@@ -261,7 +261,12 @@ export async function syncModels(target, {
261
261
  }
262
262
  backfillLadders(next, preset);
263
263
 
264
- const cooldowns = Object.fromEntries(results.filter((r) => r.cooldown).map((r) => [r.cooldown.key, r.cooldown.entry]));
264
+ const cooldowns = {};
265
+ for (const r of results) {
266
+ if (!r.cooldown) continue;
267
+ const { key, entry } = r.cooldown;
268
+ if (!(Date.parse(cooldowns[key]?.until) >= Date.parse(entry.until))) cooldowns[key] = entry;
269
+ }
265
270
  const changed = !isDeepStrictEqual(next, config);
266
271
  const summary = { allowlist: next.allowlist, planRestricted, results, cooldowns, changed };
267
272
  if (dryRun) return summary;
@@ -279,7 +284,7 @@ export async function syncModels(target, {
279
284
  // An existing lock that lasts longer is never shortened.
280
285
  const longer = Object.entries(cooldowns)
281
286
  .filter(([key, { until }]) => !(Date.parse(stored[key]?.until) >= Date.parse(until)));
282
- writeCooldowns(cooldownFile, { ...stored, ...Object.fromEntries(longer) });
287
+ writeCooldowns(cooldownFile, { ...stored, ...Object.fromEntries(longer) }, { now });
283
288
  }
284
289
  return summary;
285
290
  }
package/lib/quota.mjs CHANGED
@@ -89,7 +89,7 @@ export function quotaSet(target, subject, { window, until, reason, pool, heavy =
89
89
  const { provider, id, model } = targetRef;
90
90
  const host = provider ?? inferProvider(model);
91
91
  if ((pool !== undefined || heavy) && !host) throw new CliError(`cannot determine provider for "${clean(subject)}"`, 2);
92
- const tier = config.tiers?.[provider ?? inferProvider(id)];
92
+ const tier = config.tiers?.[host];
93
93
  const limit = span === 'custom'
94
94
  ? { until: new Date(parseUntil(until, now)).toISOString() }
95
95
  : parseRateLimit({ burst: '', '5h': '5h limit', weekly: 'weekly limit' }[span], {
@@ -102,7 +102,7 @@ export function quotaSet(target, subject, { window, until, reason, pool, heavy =
102
102
  poolKey = poolName(pool);
103
103
  } else if (heavy || (provider && !model && span === '5h' && limit.scope === 'tier')) {
104
104
  scope = 'tier';
105
- poolKey = SCARCE_POOL[host];
105
+ poolKey = SCARCE_POOL[host] ?? 'heavy';
106
106
  }
107
107
  const key = scope === 'tier' ? `tier:${host}:${poolKey}`
108
108
  : scope === 'provider' ? `provider:${provider}`
@@ -116,7 +116,9 @@ export function quotaSet(target, subject, { window, until, reason, pool, heavy =
116
116
  return { key, entry };
117
117
  }
118
118
 
119
- function countdown(ms) {
119
+ export function countdown(ms) {
120
+ if (!Number.isFinite(ms)) return 'unknown';
121
+ if (ms <= 0) return '0s';
120
122
  let seconds = Math.ceil(ms / 1000);
121
123
  const parts = [];
122
124
  for (const [unit, size] of [['d', 86_400], ['h', 3600], ['m', 60], ['s', 1]]) {
@@ -156,15 +158,24 @@ export function quotaClear(target, subject, { log = console.log } = {}) {
156
158
  const data = load(target, (key) => bad.push(key));
157
159
  // A malformed entry has no usable fields, so it is matched by its key alone.
158
160
  const stubs = bad.map((key) => [key, {
159
- scope: key.match(/^(model|provider|tier):/i)?.[1].toLowerCase() ?? (provider ? 'provider' : 'model'),
161
+ scope: key.match(/^(model|provider|tier):/i)?.[1].toLowerCase() ?? (provider && !model ? 'provider' : 'model'),
160
162
  until: '9999-01-01T00:00:00Z',
161
163
  }]);
162
164
  const removed = [...Object.entries(data), ...stubs].filter(([key, entry]) => {
163
- if (provider && !model && entry.scope === 'tier') return key.toLowerCase().startsWith(`tier:${provider}:`);
165
+ if (provider && !model && entry.scope === 'tier') {
166
+ const host = key.match(/^tier:([^:]+):/i)?.[1];
167
+ return exactProvider(host ?? '') === provider;
168
+ }
164
169
  if (provider && !model && entry.scope === 'provider') return exactProvider(key.replace(/^provider:/i, '')) === provider;
165
170
  if (model && entry.scope === 'tier') return false;
166
171
  if (model && entry.scope === 'model' && qualified) {
167
- return key.toLowerCase() === `model:${provider}:${targetRef.id}` || key.toLowerCase() === `model:${targetRef.id}`;
172
+ const wanted = modelKeys(model, config);
173
+ const prefixed = key.match(/^model:([^:]+):(.+)$/i);
174
+ if (prefixed) {
175
+ return exactProvider(prefixed[1]) === provider
176
+ && [...modelKeys(prefixed[2], config)].some((k) => wanted.has(k));
177
+ }
178
+ return [...modelKeys(key.replace(/^model:/i, ''), config)].some((k) => wanted.has(k));
168
179
  }
169
180
  // Time 0 makes isLocked match expired entries too.
170
181
  return entry.scope === (provider && !model ? 'provider' : 'model')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "t3-auto-build",
3
- "version": "2.0.2",
3
+ "version": "2.1.0",
4
4
  "description": "Cross-platform installer and $auto-build orchestration suite for T3 Code: subscription-aware cross-provider routing with quota and availability tracking.",
5
5
  "keywords": [
6
6
  "claude-code",