t3-auto-build 1.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/lib/probe.mjs ADDED
@@ -0,0 +1,251 @@
1
+ // Live model probes through the official CLIs, and syncing the allowlist to the result. Node >=18, node:* only.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { isDeepStrictEqual } from 'node:util';
6
+ import {
7
+ CONFIG_FILE, COOLDOWN_FILE, cliModelId, effectiveAllowlist, isBanned, isObject, isStringList, normalizeName,
8
+ readJson, run, which as findOnPath,
9
+ } from '../hooks/_shared.mjs';
10
+ import { parseRateLimit, readCooldowns, writeCooldowns } from '../hooks/_quota.mjs';
11
+ import { HEAVY_MODELS } from './detect.mjs';
12
+ import { CliError, PACKAGE_ROOT } from './paths.mjs';
13
+ import { completeConfig, configProblem, syncConfig } from './install.mjs';
14
+ import { LADDERS } from './render.mjs';
15
+
16
+ const TIMEOUT = 20_000;
17
+
18
+ // Flags confirmed by `claude --help` and `codex exec --help`: one-word prompt, no tools or writes, nothing saved.
19
+ // There is no documented Antigravity probe. The prompt has no spaces so it survives a cmd.exe shim.
20
+ const PROBES = {
21
+ claude: (id) => ['-p', 'ok', '--model', id, '--tools', '', '--safe-mode', '--no-session-persistence', '--output-format', 'text'],
22
+ codex: (id) => ['exec', '--model', id, '--sandbox', 'read-only', '--ephemeral', '--skip-git-repo-check',
23
+ '--ignore-user-config', '--ignore-rules', '--color', 'never', 'ok'],
24
+ };
25
+
26
+ /** Runs a CLI from PATH in an empty temp directory (no project context) with stdin closed. */
27
+ export const createRunner = (which = findOnPath) => (cmd, args, { timeout = TIMEOUT } = {}) => {
28
+ const failed = (code) => ({ status: null, stdout: '', stderr: '', error: { code } });
29
+ const executable = which(cmd);
30
+ if (!executable) return failed('ENOENT');
31
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 't3-probe-'));
32
+ try {
33
+ // shortcut: a timeout kills only the direct child; kill the process tree if CLIs are seen to linger.
34
+ const res = run(executable, args, { cwd, timeout, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
35
+ if (!res) return failed('EUNSAFE');
36
+ return { status: res.status, stdout: res.stdout ?? '', stderr: res.stderr ?? '', error: res.error };
37
+ } finally {
38
+ try {
39
+ fs.rmSync(cwd, { recursive: true, force: true });
40
+ } catch {
41
+ // still held by a dying child; the OS temp cleanup takes it
42
+ }
43
+ }
44
+ };
45
+
46
+ const NOT_LOGGED_IN = /not (?:logged|signed) in|not authenticated|please (?:run )?[`'"]?(?:\/login|(?:claude |codex )?(?:auth )?log ?in)|(?:login|authentication) (?:is )?required|authentication[ _](?:failed|error)|invalid (?:api key|x-api-key|authentication)|token (?:has )?expired|\b401\b/i;
47
+ const RATE_LIMITED = /\b429\b|rate[\s_-]*limit|(?:usage|session|weekly)[\s_-]*limit|hit your limit|limit reached|too many requests|quota (?:exceeded|exhausted)/i;
48
+ // Kept model-specific: a match removes the model from the allowlist.
49
+ const PLAN_RESTRICTED = /not (?:available|included|supported|enabled) (?:on|in|with|for) (?:your|this)(?: current)? (?:plan|subscription|account)|(?:not|n't) have access|no access to (?:this |the )?model|unauthorized (?:for (?:this )?)?model|(?:unknown|invalid|unsupported) model|model[ _]not[ _]found|issue with the selected model|model\b[^\n]{0,80}?(?:does not exist|is not supported|not found|not available on)/i;
50
+
51
+ /** { state: available | rate-limited | plan-restricted | unavailable, reason }; reasons never quote CLI output. */
52
+ export function classify(res, { timeout = TIMEOUT } = {}) {
53
+ const result = (state, reason) => ({ state, reason });
54
+ const unavailable = (reason) => result('unavailable', reason);
55
+ if (!res) return unavailable('command could not be run safely');
56
+ const code = res.error?.code;
57
+ if (code === 'ENOENT') return unavailable('cli not found');
58
+ if (code === 'ETIMEDOUT') return unavailable(`timed out after ${timeout / 1000}s`);
59
+ if (code === 'EUNSAFE') return unavailable('command could not be run safely');
60
+ // A successful reply is free text, so its words are never matched.
61
+ if (res.status === 0 && !res.error) return result('available', 'ok');
62
+ const text = `${res.stdout ?? ''}\n${res.stderr ?? ''}`;
63
+ if (NOT_LOGGED_IN.test(text)) return unavailable('not logged in');
64
+ if (RATE_LIMITED.test(text)) return result('rate-limited', 'rate limited');
65
+ if (PLAN_RESTRICTED.test(text)) return result('plan-restricted', 'not available on this plan');
66
+ return unavailable(Number.isInteger(res.status) ? `probe failed (exit ${res.status})` : 'probe failed');
67
+ }
68
+
69
+ const same = (a, b) => a.toLowerCase() === b.toLowerCase();
70
+ const has = (list, name) => list.some((item) => same(item, name));
71
+ const wantedProviders = (providers) => {
72
+ if (!providers?.length) return () => true;
73
+ const names = [providers].flat().flatMap((p) => p.split(',')).map((p) => p.trim().toLowerCase()).filter(Boolean);
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(', ')}`);
76
+ return (key) => names.includes(key.toLowerCase());
77
+ };
78
+
79
+ function cooldownFor(provider, model, id, text, config, now) {
80
+ const tier = config.tiers?.[provider];
81
+ const limit = parseRateLimit(text, { now, sharing: tier?.sharing, resetDay: tier?.resetDay });
82
+ 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];
87
+ const entry = {
88
+ scope, window: limit.window, until: limit.until, reason: `rate limited (${limit.window})`, source: 'probe',
89
+ ...(scope === 'tier' && { tier: 'heavy' }),
90
+ };
91
+ return { key, entry };
92
+ }
93
+
94
+ /** Probes each candidate model in turn. candidates: { providerKey: [display names] }, default config.allowlist. */
95
+ export async function probeModels({
96
+ config, candidates, providers, runner, which = findOnPath, now = Date.now(), log = () => {},
97
+ } = {}) {
98
+ const exec = runner ?? createRunner(which);
99
+ const wanted = wantedProviders(providers);
100
+ const results = [];
101
+ for (const [provider, models] of Object.entries(candidates ?? config.allowlist)) {
102
+ if (!wanted(provider)) continue;
103
+ const name = provider.toLowerCase();
104
+ let providerLimited = false;
105
+ for (const model of models) {
106
+ if (isBanned(model, config.bannedModels ?? [])) continue;
107
+ let outcome;
108
+ if (!Object.hasOwn(PROBES, name)) {
109
+ outcome = { state: 'unavailable', reason: 'probe not supported' };
110
+ } else if (providerLimited) {
111
+ outcome = { state: 'rate-limited', reason: 'skipped: provider is rate limited', skipped: true };
112
+ } else {
113
+ const id = cliModelId(name, model, config);
114
+ if (typeof id !== 'string' || !/^[a-z0-9][\w.:/[\]-]*$/i.test(id)) {
115
+ outcome = { state: 'unavailable', reason: 'invalid model id' };
116
+ } else {
117
+ const res = await exec(name, PROBES[name](id), { timeout: TIMEOUT });
118
+ outcome = classify(res);
119
+ if (outcome.state === 'rate-limited') {
120
+ outcome.cooldown = cooldownFor(name, model, id, `${res.stdout ?? ''}\n${res.stderr ?? ''}`, config, now);
121
+ providerLimited = outcome.cooldown.entry.scope === 'provider';
122
+ }
123
+ }
124
+ }
125
+ results.push({ provider, model, ...outcome });
126
+ log(`${provider} ${model}: ${outcome.state} (${outcome.reason})`);
127
+ }
128
+ }
129
+ return { results };
130
+ }
131
+
132
+ const isModelMap = (v) => isObject(v) && Object.values(v).every(isStringList);
133
+
134
+ function readConfig(file) {
135
+ let config;
136
+ try {
137
+ config = readJson(file);
138
+ } catch (error) {
139
+ if (error.code === 'ENOENT') throw new CliError(`${file} not found; run the installer first`);
140
+ // The parser message can quote file content, so only the error name is shown.
141
+ throw new CliError(`${file}: cannot be read (${error.code ?? error.name})`);
142
+ }
143
+ if (!isObject(config)) throw new CliError(`${file}: not a JSON object`);
144
+ for (const key of ['allowlist', 'planRestricted']) {
145
+ if (config[key] !== undefined && !isModelMap(config[key])) {
146
+ throw new CliError(`${file}: "${key}" must map provider names to lists of model names`);
147
+ }
148
+ }
149
+ if (config.bannedModels !== undefined && !isStringList(config.bannedModels)) {
150
+ throw new CliError(`${file}: "bannedModels" must be a list of model names`);
151
+ }
152
+ if (config.ladders !== undefined && !(isObject(config.ladders) && Object.values(config.ladders).every(isStringList))) {
153
+ throw new CliError(`${file}: "ladders" must map ladder names to lists`);
154
+ }
155
+ return config;
156
+ }
157
+
158
+ /** Union of provider->models maps; provider and model names compare case-insensitively, first spelling wins. */
159
+ function mergeModelMaps(...maps) {
160
+ const merged = {};
161
+ for (const [provider, models] of maps.flatMap((map) => Object.entries(map ?? {}))) {
162
+ const key = Object.keys(merged).find((name) => same(name, provider)) ?? provider;
163
+ merged[key] ??= [];
164
+ for (const model of models) if (!has(merged[key], model)) merged[key].push(model);
165
+ }
166
+ return merged;
167
+ }
168
+
169
+ /** New config for the probe results: unavailable and unprobed models keep their membership. */
170
+ function applyResults(config, preset, results) {
171
+ const allowlist = mergeModelMaps(config.allowlist ?? preset.allowlist);
172
+ const restricted = mergeModelMaps(config.planRestricted);
173
+ const keyIn = (map, provider) => Object.keys(map).find((name) => same(name, provider)) ?? provider;
174
+ for (const { provider, model, state, skipped } of results) {
175
+ if (state === 'unavailable') continue;
176
+ const allowKey = keyIn(allowlist, provider);
177
+ const restrictKey = keyIn(restricted, provider);
178
+ const wasRestricted = has(restricted[restrictKey] ?? [], model);
179
+ if (state === 'plan-restricted') {
180
+ if (allowlist[allowKey]) allowlist[allowKey] = allowlist[allowKey].filter((m) => !same(m, model));
181
+ if (!wasRestricted) (restricted[restrictKey] ??= []).push(model);
182
+ } else if (!(skipped && wasRestricted)) { // a model never actually probed does not lift its restriction
183
+ if (!has(allowlist[allowKey] ??= [], model)) allowlist[allowKey].push(model);
184
+ if (wasRestricted) restricted[restrictKey] = restricted[restrictKey].filter((m) => !same(m, model));
185
+ }
186
+ }
187
+ const planRestricted = Object.fromEntries(Object.entries(restricted).filter(([, models]) => models.length > 0));
188
+ const next = { ...config, allowlist };
189
+ if (config.planRestricted !== undefined || Object.keys(planRestricted).length > 0) next.planRestricted = planRestricted;
190
+ return { next, planRestricted };
191
+ }
192
+
193
+ /** Gives every ladder at least one allowed model, so renderSkill cannot fail after removals. */
194
+ function backfillLadders(next, preset) {
195
+ const allowed = effectiveAllowlist({ allowlist: next.allowlist, bannedModels: next.bannedModels ?? preset.bannedModels })
196
+ .flatMap(([, models]) => models);
197
+ const fallback = allowed.find((m) => same(m, next.defaultModel ?? preset.defaultModel)) ?? allowed[0];
198
+ for (const name of LADDERS) {
199
+ const ladder = next.ladders?.[name] ?? preset.ladders[name] ?? [];
200
+ if (!ladder.some((entry) => has(allowed, entry.split('@')[0].trim()))) {
201
+ next.ladders = { ...next.ladders, [name]: [...ladder, fallback] };
202
+ }
203
+ }
204
+ }
205
+
206
+ /** Probes the candidate models of <target>'s config and persists the allowlist, cooldowns and SKILL.md. */
207
+ export async function syncModels(target, {
208
+ providers, dryRun = false, yes = false, force = false, runner, which, now = Date.now(), log = console.log,
209
+ confirm = async () => false, syncFiles = syncConfig,
210
+ } = {}) {
211
+ const config = readConfig(path.join(target, CONFIG_FILE));
212
+ const presetName = ['claude-codex', 'claude-only'].includes(config.preset) ? config.preset : 'tri-provider';
213
+ const preset = readJson(path.join(PACKAGE_ROOT, 'presets', `${presetName}.json`));
214
+ const bannedModels = config.bannedModels ?? preset.bannedModels;
215
+ // Checked before probing, so quota is not spent on a config that cannot be saved.
216
+ const problem = configProblem(completeConfig(config));
217
+ if (problem) throw new CliError(`${CONFIG_FILE}: ${problem}`);
218
+ const candidates = mergeModelMaps(config.allowlist ?? preset.allowlist, config.planRestricted, preset.allowlist);
219
+ const { results } = await probeModels({
220
+ config: { ...config, bannedModels }, candidates, providers, runner, which, now, log,
221
+ });
222
+
223
+ const { next, planRestricted } = applyResults(config, preset, results);
224
+ if (effectiveAllowlist({ allowlist: next.allowlist, bannedModels }).length === 0) {
225
+ throw new CliError('no allowed model would remain; nothing was written. Log in with the official CLI, '
226
+ + 'or limit the check with --providers');
227
+ }
228
+ backfillLadders(next, preset);
229
+
230
+ const cooldowns = Object.fromEntries(results.filter((r) => r.cooldown).map((r) => [r.cooldown.key, r.cooldown.entry]));
231
+ const changed = !isDeepStrictEqual(next, config);
232
+ const summary = { allowlist: next.allowlist, planRestricted, results, cooldowns, changed };
233
+ if (dryRun) return summary;
234
+ if (!yes && !(await confirm(summary))) return { ...summary, changed: false };
235
+
236
+ const cooldownFile = path.join(target, COOLDOWN_FILE);
237
+ let stored;
238
+ try {
239
+ stored = readCooldowns(cooldownFile); // read before any write, so a broken file stops the whole sync
240
+ } catch (error) {
241
+ throw new CliError(`${cooldownFile}: cannot be read (${error.code ?? error.name}); fix or delete it`);
242
+ }
243
+ await syncFiles(target, next, { force, log });
244
+ if (Object.keys(cooldowns).length > 0) {
245
+ // An existing lock that lasts longer is never shortened.
246
+ const longer = Object.entries(cooldowns)
247
+ .filter(([key, { until }]) => !(Date.parse(stored[key]?.until) >= Date.parse(until)));
248
+ writeCooldowns(cooldownFile, { ...stored, ...Object.fromEntries(longer) });
249
+ }
250
+ return summary;
251
+ }
package/lib/prompt.mjs ADDED
@@ -0,0 +1,114 @@
1
+ import path from 'node:path';
2
+ import readline from 'node:readline/promises';
3
+ import { CONFIG_FILE, isObject, readJson } from '../hooks/_shared.mjs';
4
+ import { detect as detectProviders, parseTiers } from './detect.mjs';
5
+ import { MODULES, readManifest } from './manifest.mjs';
6
+ import { PRESETS, completeConfig } from './install.mjs';
7
+ import { CliError } from './paths.mjs';
8
+
9
+ const MODULE_LABELS = { full: 'Full Suite', 'auto-build': '/auto-build Only', core: 'Core Discipline + Commands' };
10
+ const PLAN_NAMES = { claude: 'pro|max', codex: 'plus|pro', antigravity: 'standard|ultra' };
11
+
12
+ /** parseTiers, with a bad value reported as a usage error. */
13
+ export function parseTierSpec(spec) {
14
+ try {
15
+ return parseTiers(spec);
16
+ } catch (error) {
17
+ if (error instanceof CliError) error.exitCode = 2;
18
+ throw error;
19
+ }
20
+ }
21
+
22
+ /** Yes only on an explicit "y" or "yes"; closed input counts as no. */
23
+ export async function confirmYes(question, input = process.stdin, output = process.stdout) {
24
+ const rl = readline.createInterface({ input, output, terminal: false });
25
+ try {
26
+ const lines = rl[Symbol.asyncIterator]();
27
+ output.write(question);
28
+ const { value, done } = await lines.next();
29
+ return !done && /^y(es)?$/i.test(value.trim());
30
+ } finally {
31
+ rl.close();
32
+ }
33
+ }
34
+
35
+ /** The init questions, defaulting to the installed config, or on a fresh one to the detected CLIs. */
36
+ export async function initPrompts(target, options, { detect = detectProviders, input, output } = {}) {
37
+ let config = null;
38
+ try {
39
+ config = readJson(path.join(target, CONFIG_FILE));
40
+ } catch {
41
+ // no usable config yet; install() reports a broken one
42
+ }
43
+ const found = detect();
44
+ const complete = completeConfig(config ?? {});
45
+ const current = {
46
+ modules: readManifest(target)?.modules ?? 'full',
47
+ preset: config ? complete.preset : found.preset,
48
+ compaction: complete.compactionThreshold,
49
+ providers: Object.keys(found.providers).filter((name) => found.providers[name].binary),
50
+ tiers: isObject(complete.tiers) ? complete.tiers : {},
51
+ };
52
+ const answers = await promptOptions(options, current, input, output);
53
+ if (!config && (answers.modules ?? current.modules) !== 'core') answers.preset ??= found.preset;
54
+ return answers;
55
+ }
56
+
57
+ export function parseChoice(value, choices, name) {
58
+ const text = value.trim().toLowerCase();
59
+ const choice = choices.includes(text) ? text : /^\d+$/.test(text) ? choices[Number(text) - 1] : undefined;
60
+ if (!choice) throw new CliError(`invalid ${name} "${value}" (expected ${choices.join(', ')})`, 2);
61
+ return choice;
62
+ }
63
+
64
+ export function parsePercent(value) {
65
+ const text = value.trim();
66
+ const percent = Number(text);
67
+ if (!/^\d+$/.test(text) || percent < 1 || percent > 100) {
68
+ throw new CliError(`invalid compaction "${value}" (expected an integer from 1 to 100)`, 2);
69
+ }
70
+ return percent;
71
+ }
72
+
73
+ /** Ask for whatever the flags left open. Enter keeps the current value (answer stays undefined). */
74
+ export async function promptOptions(options, current, input = process.stdin, output = process.stdout) {
75
+ const rl = readline.createInterface({ input, output, terminal: false });
76
+ const lines = rl[Symbol.asyncIterator]();
77
+ const ask = async (question) => {
78
+ output.write(question);
79
+ const { value, done } = await lines.next();
80
+ if (done) throw new CliError('input closed; nothing was changed', 2);
81
+ return value.trim();
82
+ };
83
+ const numbered = (items) => items.map((item, i) => ` ${i + 1}) ${item}`).join('\n');
84
+ const answers = { ...options };
85
+ try {
86
+ if (answers.modules === undefined) {
87
+ const reply = await ask(`Modules:\n${numbered(MODULES.map((m) => `${m} - ${MODULE_LABELS[m]}`))}\nChoose [${current.modules}]: `);
88
+ if (reply) answers.modules = parseChoice(reply, MODULES, 'modules');
89
+ }
90
+ if ((answers.modules ?? current.modules) === 'core') return answers;
91
+ if (answers.preset === undefined) {
92
+ const reply = await ask(`Preset:\n${numbered(PRESETS)}\nChoose [${current.preset}]: `);
93
+ if (reply) answers.preset = parseChoice(reply, PRESETS, 'preset');
94
+ }
95
+ const banned = await ask('Extra banned models, comma separated [none]: ');
96
+ answers.banned = banned.split(',').map((name) => name.trim()).filter(Boolean);
97
+ if (answers.compaction === undefined) {
98
+ const reply = await ask(`Auto-compaction threshold, percent 1-100 [${current.compaction}]: `);
99
+ if (reply) answers.compaction = parsePercent(reply);
100
+ }
101
+ if (options.tiers === undefined) {
102
+ for (const provider of current.providers ?? []) {
103
+ const kept = current.tiers?.[provider]?.plan ?? 'skip';
104
+ const plan = await ask(`${provider} subscription tier (${PLAN_NAMES[provider]}) [${kept}]: `);
105
+ if (!plan) continue;
106
+ const day = await ask(`${provider} weekly reset day, such as monday [skip]: `);
107
+ answers.tiers = { ...answers.tiers, ...parseTierSpec([provider, plan, day].filter(Boolean).join(':')) };
108
+ }
109
+ }
110
+ return answers;
111
+ } finally {
112
+ rl.close();
113
+ }
114
+ }
package/lib/quota.mjs ADDED
@@ -0,0 +1,204 @@
1
+ // Manual cooldown locks and the login-status check behind `t3-auto-build quota`. Node >=18, node:* only.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {
5
+ COOLDOWN_FILE, cliModelId, inferProvider, loadConfig, modelKeys, normalizeModel, which as findOnPath,
6
+ } from '../hooks/_shared.mjs';
7
+ import { isLocked, parseRateLimit, prune, readCooldowns, writeCooldowns } from '../hooks/_quota.mjs';
8
+ import { HEAVY_MODELS } from './detect.mjs';
9
+ import { CliError } from './paths.mjs';
10
+ import { createRunner } from './probe.mjs';
11
+
12
+ export const QUOTA_WINDOWS = ['burst', '5h', 'weekly'];
13
+ const isProvider = (name) => Object.hasOwn(HEAVY_MODELS, name);
14
+ const cooldownPath = (target) => path.join(target, COOLDOWN_FILE);
15
+ // File and argument text is printed, so it is kept to one line without control characters.
16
+ const clean = (text) => String(text).replace(/[\s\p{Cc}]+/gu, ' ').slice(0, 120);
17
+
18
+ function load(target, onInvalid) {
19
+ const file = cooldownPath(target);
20
+ try {
21
+ return readCooldowns(file, onInvalid);
22
+ } catch (error) {
23
+ // The parser message can quote file content, so only the error name is shown.
24
+ throw new CliError(`${file}: cannot be read (${error.code ?? error.name}); fix it or run quota clear --all`);
25
+ }
26
+ }
27
+
28
+ /** { provider } for a provider name, else { model, id } for a model this config or a known family names. */
29
+ function resolveSubject(subject, config) {
30
+ const text = String(subject ?? '').trim();
31
+ const lower = text.toLowerCase();
32
+ if (isProvider(lower)) return { provider: lower };
33
+ const model = normalizeModel(text);
34
+ const wanted = modelKeys(model, config);
35
+ const known = [...Object.values(config.allowlist).flat(), ...Object.keys(config.modelIds ?? {})]
36
+ .some((name) => [...modelKeys(name, config)].some((key) => wanted.has(key)));
37
+ if (!text || (!known && !inferProvider(model))) {
38
+ throw new CliError(`unknown provider or model "${clean(text)}"; use ${Object.keys(HEAVY_MODELS).join(', ')} or a model name`, 2);
39
+ }
40
+ return { model, id: cliModelId(inferProvider(model), model, config) };
41
+ }
42
+
43
+ const UNIT_MS = { w: 604_800_000, d: 86_400_000, h: 3_600_000, m: 60_000 };
44
+ const ISO = /^(\d{4})-(\d{2})-(\d{2})(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
45
+
46
+ /** An ISO time, or a duration such as 90m or 1w2d, as a future timestamp. */
47
+ function parseUntil(value, now) {
48
+ const text = String(value).trim();
49
+ let time = NaN;
50
+ if (/^(\d+[wdhm])+$/.test(text)) {
51
+ time = [...text.matchAll(/(\d+)([wdhm])/g)].reduce((total, [, n, unit]) => total + n * UNIT_MS[unit], now);
52
+ } else {
53
+ const [, year, month, day] = text.match(ISO) ?? [];
54
+ // Date.parse rolls 02-30 over into March, so the calendar date is checked separately.
55
+ if (year && new Date(Date.UTC(year, month - 1, day)).getUTCDate() === Number(day)) time = Date.parse(text);
56
+ }
57
+ if (!(time > now && time < 8.64e15)) {
58
+ throw new CliError(`invalid --until "${clean(text)}"; use a future ISO time or a duration such as 90m, 5h or 1w2d`, 2);
59
+ }
60
+ return time;
61
+ }
62
+
63
+ /** Locks a provider or model for a window (default burst) or until a given time. */
64
+ export function quotaSet(target, subject, { window, until, reason, now = Date.now(), log = console.log } = {}) {
65
+ if (window !== undefined && until !== undefined) throw new CliError('give a window or --until, not both', 2);
66
+ const span = until === undefined ? window ?? 'burst' : 'custom';
67
+ if (span !== 'custom' && !QUOTA_WINDOWS.includes(span)) throw new CliError(`unknown window "${clean(span)}"`, 2);
68
+ const config = loadConfig(target);
69
+ const { provider, id } = resolveSubject(subject, config);
70
+ const tier = config.tiers?.[provider ?? inferProvider(id)];
71
+ const limit = span === 'custom'
72
+ ? { until: new Date(parseUntil(until, now)).toISOString() }
73
+ : parseRateLimit({ burst: '', '5h': '5h limit', weekly: 'weekly limit' }[span], {
74
+ now, sharing: tier?.sharing, resetDay: tier?.resetDay,
75
+ });
76
+ let scope = provider ? 'provider' : 'model';
77
+ if (provider && span === '5h' && limit.scope === 'tier') scope = 'tier';
78
+ const key = { model: `model:${id}`, provider: `provider:${provider}`, tier: `tier:${provider}:heavy` }[scope];
79
+ const entry = {
80
+ scope, window: span, until: limit.until, reason: reason ?? `manual lock (${span})`, source: 'manual',
81
+ ...(scope === 'tier' && { tier: 'heavy' }),
82
+ };
83
+ writeCooldowns(cooldownPath(target), { ...prune(load(target), now).kept, [key]: entry });
84
+ log(`locked ${key} until ${entry.until} (${span})`);
85
+ return { key, entry };
86
+ }
87
+
88
+ function countdown(ms) {
89
+ let seconds = Math.ceil(ms / 1000);
90
+ const parts = [];
91
+ for (const [unit, size] of [['d', 86_400], ['h', 3600], ['m', 60], ['s', 1]]) {
92
+ const count = Math.floor(seconds / size);
93
+ seconds -= count * size;
94
+ if (count || parts.length) parts.push(`${count}${unit}`);
95
+ }
96
+ return parts.join(' ');
97
+ }
98
+
99
+ /** Drops expired locks and prints the rest. Returns the active ones. */
100
+ export function quotaStatus(target, { now = Date.now(), log = console.log } = {}) {
101
+ const { kept, removed } = prune(load(target), now);
102
+ if (Object.keys(removed).length) writeCooldowns(cooldownPath(target), kept);
103
+ const locks = Object.entries(kept).map(([key, entry]) => ({ key, ...entry }));
104
+ if (!locks.length) log('no active cooldowns');
105
+ for (const { key, window, until, reason, source } of locks) {
106
+ log(`${clean(key)}: ${countdown(Date.parse(until) - now)} left, resets ${until} `
107
+ + `(${clean(window)}, ${clean(source)}: ${clean(reason)})`);
108
+ }
109
+ return locks;
110
+ }
111
+
112
+ /** subject: a provider or model name, or { all: true }. Returns the removed keys (null for all). */
113
+ export function quotaClear(target, subject, { log = console.log } = {}) {
114
+ if (subject?.all) {
115
+ fs.rmSync(cooldownPath(target), { force: true }); // also the way out of a corrupt file
116
+ log('cleared all cooldowns');
117
+ return null;
118
+ }
119
+ const config = loadConfig(target);
120
+ const { provider, model } = resolveSubject(subject, config);
121
+ const bad = [];
122
+ const data = load(target, (key) => bad.push(key));
123
+ // A malformed entry has no usable fields, so it is matched by its key alone.
124
+ const stubs = bad.map((key) => [key, {
125
+ scope: key.match(/^(model|provider|tier):/i)?.[1].toLowerCase() ?? (provider ? 'provider' : 'model'),
126
+ until: '9999-01-01T00:00:00Z',
127
+ }]);
128
+ const removed = [...Object.entries(data), ...stubs].filter(([key, entry]) => {
129
+ if (provider && entry.scope === 'tier') return key.toLowerCase() === `tier:${provider}:heavy`;
130
+ // Time 0 makes isLocked match expired entries too.
131
+ return entry.scope === (provider ? 'provider' : 'model')
132
+ && isLocked({ [key]: entry }, { provider, model, config }, 0) !== null;
133
+ }).map(([key]) => key);
134
+ for (const key of removed) delete data[key];
135
+ if (removed.length) writeCooldowns(cooldownPath(target), data, { remove: removed });
136
+ log(removed.length ? `cleared: ${removed.map(clean).join(', ')}` : `no cooldown recorded for ${clean(subject)}`);
137
+ return removed;
138
+ }
139
+
140
+ // Confirmed official commands. They report login state; there is no documented Antigravity equivalent.
141
+ const STATUS = { claude: ['auth', 'status'], codex: ['login', 'status'] };
142
+ const EXHAUSTED = /(?<![\d.])(?:0(?:\.0+)?\s*% (?:remaining|left)|100(?:\.0+)?\s*% (?:used|consumed))\b|\blimit (?:has been )?(?:reached|exceeded|exhausted)\b|\b(?:hit|reached) your (?:[\w-]+ ){0,3}limit\b/i;
143
+ // "no limit reached" or "when the limit is reached" is not exhaustion.
144
+ const HEDGED = /(?:\b(?:no|not|never|if|when|once|until|before)\b|n't\b)[^.;]*$/i;
145
+
146
+ /** Runs the status commands and records a lock only for explicitly reported exhaustion. Output is never logged. */
147
+ export async function quotaCheck(target, { providers, runner, which = findOnPath, now = Date.now(), log = console.log } = {}) {
148
+ const names = providers?.length ? providers.map((p) => p.toLowerCase()) : Object.keys(HEAVY_MODELS);
149
+ const unknown = names.find((name) => !isProvider(name));
150
+ if (unknown !== undefined) throw new CliError(`unknown provider "${clean(unknown)}"; use ${Object.keys(HEAVY_MODELS).join(', ')}`, 2);
151
+ const exec = runner ?? createRunner(which);
152
+ const config = loadConfig(target);
153
+ const locks = {};
154
+ for (const provider of names) {
155
+ const fallback = (why) => log(`${provider}: ${why}; using recorded cooldowns`);
156
+ if (!STATUS[provider]) {
157
+ fallback('no official status command');
158
+ continue;
159
+ }
160
+ let res;
161
+ try {
162
+ res = await exec(provider, STATUS[provider], { timeout: 15_000 });
163
+ } catch {
164
+ res = null;
165
+ }
166
+ if (!res || res.error) {
167
+ const code = res?.error?.code;
168
+ fallback(code === 'ENOENT' ? 'cli not found' : code === 'ETIMEDOUT' ? 'status check timed out' : 'status check failed');
169
+ continue;
170
+ }
171
+ const lines = `${res.stdout ?? ''}\n${res.stderr ?? ''}`.split(/\r?\n/);
172
+ const found = {};
173
+ lines.forEach((line, i) => {
174
+ const match = EXHAUSTED.exec(line);
175
+ if (!match || HEDGED.test(line.slice(0, match.index))) return;
176
+ const reset = /^\s*resets?\b/i.test(lines[i + 1] ?? '') ? ` ${lines[i + 1]}` : '';
177
+ const tier = config.tiers?.[provider];
178
+ const limit = parseRateLimit(`${line}${reset}`, { now, sharing: tier?.sharing, resetDay: tier?.resetDay });
179
+ const scope = limit.scope === 'tier' ? 'tier' : 'provider';
180
+ const key = scope === 'tier' ? `tier:${provider}:heavy` : `provider:${provider}`;
181
+ if (Date.parse(found[key]?.until) >= Date.parse(limit.until)) return;
182
+ found[key] = {
183
+ scope, window: limit.window, until: limit.until, reason: `usage exhausted (${limit.window})`, source: 'probe',
184
+ ...(scope === 'tier' && { tier: 'heavy' }),
185
+ };
186
+ });
187
+ if (Object.keys(found).length === 0) {
188
+ fallback(`${res.status === 0 ? 'logged in' : 'not logged in or status failed'}; usage not exposed`);
189
+ }
190
+ Object.assign(locks, found);
191
+ }
192
+ if (Object.keys(locks).length === 0) return locks;
193
+ try {
194
+ const stored = load(target);
195
+ // An existing lock that lasts longer is never shortened.
196
+ const longer = Object.entries(locks).filter(([key, { until }]) => !(Date.parse(stored[key]?.until) >= Date.parse(until)));
197
+ const next = { ...stored, ...Object.fromEntries(longer) };
198
+ writeCooldowns(cooldownPath(target), next);
199
+ for (const key of Object.keys(locks)) log(`${key}: usage exhausted; locked until ${next[key].until}`);
200
+ } catch (error) {
201
+ log(`warning: lockout not recorded: ${error.message}`);
202
+ }
203
+ return locks;
204
+ }
package/lib/render.mjs ADDED
@@ -0,0 +1,59 @@
1
+ import { CONFIG_FILE, COOLDOWN_FILE, displayPath, effectiveAllowlist } from '../hooks/_shared.mjs';
2
+ import { CliError } from './paths.mjs';
3
+
4
+ export const LADDERS = ['tier1', 'commandRunner', 'builderA', 'testerA', 'auditorA', 'builderB', 'testerB', 'auditorB', 'architect', 'dualAudit'];
5
+
6
+ /** Fill {{slot}} placeholders; an unknown slot is an error. */
7
+ export function fillTemplate(template, values) {
8
+ return template.replace(/\{\{([^{}]*)\}\}/g, (match, name) => {
9
+ const key = name.trim();
10
+ if (!Object.prototype.hasOwnProperty.call(values, key)) throw new CliError(`unresolved template slot ${match}`);
11
+ return String(values[key]);
12
+ });
13
+ }
14
+
15
+ const code = (text) => `\`${text}\``;
16
+
17
+ /** Render SKILL.md from the config. Banned or non-allowlisted ladder entries are dropped. */
18
+ export function renderSkill(template, config, configDir) {
19
+ const groups = effectiveAllowlist(config);
20
+ const allowed = new Map(groups.flatMap(([, models]) => models).map((model) => [model.toLowerCase(), model]));
21
+ if (allowed.size === 0) throw new CliError('the allowlist is empty after removing banned models');
22
+
23
+ const ladders = Object.fromEntries(
24
+ LADDERS.map((name) => {
25
+ const entries = (config.ladders[name] ?? []).flatMap((entry) => {
26
+ const [model, effort] = entry.split('@');
27
+ const known = allowed.get(model.trim().toLowerCase());
28
+ return known ? [{ model: known, effort }] : [];
29
+ });
30
+ if (entries.length === 0) {
31
+ throw new CliError(`ladder "${name}" has no model left after removing banned and non-allowlisted entries; edit ${CONFIG_FILE}`);
32
+ }
33
+ return [name, entries];
34
+ }),
35
+ );
36
+ const describe = ({ model, effort }) => `${code(model)}${effort ? ` (${code(effort)})` : ''}`;
37
+ const duals = ladders.dualAudit.map(describe);
38
+ const defaultModel = allowed.get(config.defaultModel.toLowerCase()) ?? ladders.builderA[0].model;
39
+ const flags = groups.map(([provider, models]) => ({ flag: `--${provider.toLowerCase().replace(/\s+/g, '-')}-only`, provider, models }));
40
+
41
+ return fillTemplate(template, {
42
+ ...Object.fromEntries(LADDERS.map((name) => [name, ladders[name].map(describe).join(' -> ')])),
43
+ modelCount: allowed.size,
44
+ allowlist: groups.map(([provider, models]) => `- **${provider}:** ${models.map(code).join(', ')}`).join('\n'),
45
+ providerFlags: flags
46
+ .map(({ flag, provider, models }) => `- \`${flag}\`: Restrict all steps and failovers to allowlisted ${provider} models (${models.map(code).join(', ')}).`)
47
+ .join('\n'),
48
+ banned: config.bannedModels.length ? `${config.bannedModels.join(', ')}, or ` : '',
49
+ defaultModel,
50
+ defaultEffort: config.defaultEffort,
51
+ compactionThreshold: config.compactionThreshold,
52
+ firstBuilderA: ladders.builderA[0].model,
53
+ firstBuilderB: ladders.builderB[0].model,
54
+ dualAuditNames: ladders.dualAudit.map(({ model }) => code(model)).join(' and '),
55
+ dualAuditRun: duals.length > 1 ? `Run ${duals.join(' AND ')} in parallel` : `Run ${duals[0]}`,
56
+ cooldownsPath: displayPath(configDir, COOLDOWN_FILE),
57
+ configPath: displayPath(configDir, CONFIG_FILE),
58
+ });
59
+ }