t3-auto-build 1.0.1 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +115 -0
- package/README.md +384 -118
- package/bin/cli.mjs +155 -82
- package/hooks/_quota.mjs +75 -23
- package/hooks/_shared.mjs +165 -10
- package/hooks/pre-compact.mjs +41 -4
- package/hooks/pre-tool-use.mjs +52 -15
- package/hooks/session-start.mjs +55 -9
- package/lib/detect.mjs +5 -1
- package/lib/discover.mjs +492 -0
- package/lib/doctor.mjs +42 -2
- package/lib/install.mjs +234 -29
- package/lib/plans.mjs +318 -0
- package/lib/probe.mjs +49 -15
- package/lib/prompt.mjs +82 -5
- package/lib/quota.mjs +59 -18
- package/lib/render.mjs +25 -4
- package/lib/settings.mjs +41 -1
- package/package.json +12 -5
- package/presets/claude-codex.json +62 -14
- package/presets/claude-only.json +41 -11
- package/presets/tri-provider.json +80 -14
- package/skills/auto-build/SKILL.md.tmpl +12 -8
package/bin/cli.mjs
CHANGED
|
@@ -3,87 +3,111 @@ import fs from 'node:fs';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { HEAVY_MODELS } from '../lib/detect.mjs';
|
|
5
5
|
import { doctor } from '../lib/doctor.mjs';
|
|
6
|
-
import {
|
|
6
|
+
import { applyDrift, checkModels, markAvailability, readAvailabilityFile } from '../lib/discover.mjs';
|
|
7
|
+
import { PRESETS, install, syncConfig, uninstall, upgrade, wantsAuto } from '../lib/install.mjs';
|
|
7
8
|
import { MODULES, readManifest } from '../lib/manifest.mjs';
|
|
8
9
|
import { CliError, PACKAGE_ROOT, resolveTarget } from '../lib/paths.mjs';
|
|
9
10
|
import { syncModels } from '../lib/probe.mjs';
|
|
10
|
-
import {
|
|
11
|
+
import { CATALOG, PROVIDERS } from '../lib/plans.mjs';
|
|
12
|
+
import { confirmYes, initPrompts, parseChoice, parsePercent, parseTierSpec, TIER_FLAGS } from '../lib/prompt.mjs';
|
|
11
13
|
import { QUOTA_WINDOWS, quotaCheck, quotaClear, quotaSet, quotaStatus } from '../lib/quota.mjs';
|
|
14
|
+
import { CONFIG_FILE, readJson } from '../hooks/_shared.mjs';
|
|
12
15
|
|
|
13
16
|
const USAGE = `Usage: t3-auto-build <command> [options]
|
|
14
17
|
|
|
15
18
|
Commands:
|
|
16
|
-
init
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
sync-models
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
quota
|
|
23
|
-
quota
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
--
|
|
31
|
-
--
|
|
32
|
-
--
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
--
|
|
36
|
-
|
|
37
|
-
--
|
|
38
|
-
|
|
39
|
-
--
|
|
40
|
-
--
|
|
41
|
-
|
|
42
|
-
--
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
--
|
|
46
|
-
--
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
--
|
|
50
|
-
quota
|
|
51
|
-
--
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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
|
+
--recheck-locks retest every active provider lock now
|
|
55
|
+
--json print machine-readable results
|
|
56
|
+
|
|
57
|
+
sync-models only:
|
|
58
|
+
--auto run without confirmation
|
|
59
|
+
--refresh ignore the probe cache TTL
|
|
60
|
+
--probe-scarce also probe scarce quota models
|
|
61
|
+
--apply promote newer known models from discovered drift
|
|
62
|
+
--dry-run probe but do not write the synced allowlist
|
|
63
|
+
--providers <list> only these providers, comma separated
|
|
64
|
+
--force replace edited managed SKILL.md after backup
|
|
65
|
+
|
|
66
|
+
availability only:
|
|
67
|
+
--ttl <duration> mark lifetime: 1m..30d (default 24h)
|
|
68
|
+
--reason <text> note shown in availability status
|
|
69
|
+
|
|
70
|
+
quota set only:
|
|
71
|
+
--pool <name> lock a model pool (standard, fable, astra, third-party-claude)
|
|
72
|
+
--burst | --5h | --weekly lock window (default burst)
|
|
73
|
+
--until <when> ISO time or duration such as 90m or 1w2d
|
|
74
|
+
--reason <text> note shown by quota status
|
|
75
|
+
quota clear flag: --all remove every lock
|
|
76
|
+
|
|
77
|
+
Examples:
|
|
78
|
+
t3-auto-build init --claude-tier pro --codex-tier plus --antigravity-tier pro --parent opus
|
|
79
|
+
t3-auto-build check-models --json
|
|
80
|
+
t3-auto-build sync-models --refresh --probe-scarce
|
|
81
|
+
t3-auto-build availability mark antigravity:claude-opus-5-5 plan-restricted --ttl 24h
|
|
82
|
+
t3-auto-build quota set antigravity:claude-opus-5-5 --pool third-party-claude
|
|
83
|
+
Overflow to cross-hosted models requires an explicit provider, e.g. antigravity:claude-opus-5-5.`;
|
|
84
|
+
|
|
85
|
+
const VALUE_FLAGS = ['target', 'preset', 'modules', 'compaction', 'tiers', 'providers', 'until', 'reason', 'parent', 'claude-tier', 'codex-tier', 'antigravity-tier', 'ttl', 'pool'];
|
|
86
|
+
const SWITCHES = ['yes', 'force', 'help', 'version', 'probe', 'dry-run', 'all', 'auto', 'refresh', 'probe-scarce', 'recheck-locks', 'apply', 'json', 'allow-usage-credits', 'allow-fast-modes', 'verified-org', ...QUOTA_WINDOWS];
|
|
55
87
|
const COMMAND_FLAGS = {
|
|
56
|
-
init: ['preset', 'modules', 'compaction', 'tiers', 'probe', 'yes', 'force'],
|
|
57
|
-
doctor: [],
|
|
58
|
-
|
|
59
|
-
'sync-models': ['dry-run', 'providers', 'yes', 'force'],
|
|
60
|
-
'
|
|
61
|
-
'quota
|
|
62
|
-
'quota clear': ['all'],
|
|
63
|
-
'quota check': [],
|
|
88
|
+
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'],
|
|
89
|
+
upgrade: ['yes'], doctor: [], uninstall: [],
|
|
90
|
+
'check-models': ['refresh', 'probe-scarce', 'recheck-locks', 'json'],
|
|
91
|
+
'sync-models': ['dry-run', 'providers', 'yes', 'auto', 'force', 'refresh', 'probe-scarce', 'apply'],
|
|
92
|
+
'availability mark': ['ttl', 'reason'], 'availability status': [],
|
|
93
|
+
'quota set': [...QUOTA_WINDOWS, 'until', 'reason', 'pool'],
|
|
94
|
+
'quota status': [], 'quota clear': ['all'], 'quota check': [],
|
|
64
95
|
};
|
|
65
|
-
|
|
66
|
-
const ARGUMENTS = { 'quota set': [1, 1], 'quota clear': [0, 1], 'quota check': [0, 1] };
|
|
96
|
+
const ARGUMENTS = { upgrade: [0, 0], 'availability mark': [2, 2], 'quota set': [1, 1], 'quota clear': [0, 1], 'quota check': [0, 1] };
|
|
67
97
|
|
|
68
98
|
function parseArgs(argv) {
|
|
69
99
|
const flags = {};
|
|
70
100
|
const positional = [];
|
|
71
101
|
for (let i = 0; i < argv.length; i += 1) {
|
|
72
102
|
const argument = { '-h': '--help', '-v': '--version' }[argv[i]] ?? argv[i];
|
|
73
|
-
if (!argument.startsWith('-')) {
|
|
74
|
-
positional.push(argument);
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
103
|
+
if (!argument.startsWith('-')) { positional.push(argument); continue; }
|
|
77
104
|
const [, name, inline] = argument.match(/^--([^=]+)(?:=(.*))?$/s) ?? [];
|
|
78
|
-
if (SWITCHES.includes(name) && inline === undefined)
|
|
79
|
-
|
|
80
|
-
} else if (VALUE_FLAGS.includes(name)) {
|
|
105
|
+
if (SWITCHES.includes(name) && inline === undefined) flags[name] = true;
|
|
106
|
+
else if (VALUE_FLAGS.includes(name)) {
|
|
81
107
|
const value = inline ?? argv[(i += 1)];
|
|
82
108
|
if (!value || (inline === undefined && value.startsWith('--'))) throw new CliError(`--${name} needs a value`, 2);
|
|
83
109
|
flags[name] = value;
|
|
84
|
-
} else {
|
|
85
|
-
throw new CliError(`unknown option ${argument}`, 2);
|
|
86
|
-
}
|
|
110
|
+
} else throw new CliError(`unknown option ${argument}`, 2);
|
|
87
111
|
}
|
|
88
112
|
return { flags, positional };
|
|
89
113
|
}
|
|
@@ -94,25 +118,35 @@ function parseProviders(value) {
|
|
|
94
118
|
return names.map((name) => parseChoice(name, Object.keys(HEAVY_MODELS), 'provider'));
|
|
95
119
|
}
|
|
96
120
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
121
|
+
function rawConfig(target) {
|
|
122
|
+
const file = path.join(target, CONFIG_FILE);
|
|
123
|
+
try { return readJson(file); } catch (error) { throw new CliError(`${file}: cannot read valid config JSON (${error.code ?? error.name})`); }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function sync(target, { yes = false, dryRun = false, force = false, providers, refresh = false, probeScarce = false, apply = false } = {}) {
|
|
127
|
+
if (apply) {
|
|
128
|
+
const config = rawConfig(target);
|
|
129
|
+
const availability = readAvailabilityFile(target);
|
|
130
|
+
if (!availability) throw new CliError('no availability cache; run t3-auto-build check-models first');
|
|
131
|
+
const result = applyDrift(config, availability);
|
|
132
|
+
for (const promotion of result.promoted) console.log(`promoted ${promotion.provider}:${promotion.from} -> ${promotion.provider}:${promotion.to}`);
|
|
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');
|
|
136
|
+
return;
|
|
100
137
|
}
|
|
101
|
-
|
|
138
|
+
if (!yes && !dryRun && !process.stdin.isTTY) throw new CliError('no interactive terminal; re-run with --auto (or --dry-run); nothing was written', 2);
|
|
102
139
|
const manifest = readManifest(target);
|
|
103
|
-
if (!dryRun && !(manifest && wantsAuto(manifest.modules))) {
|
|
104
|
-
throw new CliError(`no auto-build installation in ${target}; run init first`);
|
|
105
|
-
}
|
|
140
|
+
if (!dryRun && !(manifest && wantsAuto(manifest.modules))) throw new CliError(`no auto-build installation in ${target}; run init first`);
|
|
106
141
|
let declined = false;
|
|
107
142
|
const confirm = async ({ allowlist, planRestricted, cooldowns, changed }) => {
|
|
108
143
|
if (force || changed || Object.keys(cooldowns).length) {
|
|
109
144
|
console.log(JSON.stringify({ allowlist, planRestricted, cooldowns }, null, 2));
|
|
110
145
|
if (await confirmYes(`Write these changes to ${target}? [y/N] `)) return true;
|
|
111
146
|
}
|
|
112
|
-
declined = true;
|
|
113
|
-
return false;
|
|
147
|
+
declined = true; return false;
|
|
114
148
|
};
|
|
115
|
-
const summary = await syncModels(target, { providers, dryRun, yes,
|
|
149
|
+
const summary = await syncModels(target, { providers, dryRun, yes, refresh, probeScarce, confirm });
|
|
116
150
|
if (dryRun) {
|
|
117
151
|
const { allowlist, planRestricted, cooldowns, changed } = summary;
|
|
118
152
|
console.log(JSON.stringify({ allowlist, planRestricted, cooldowns, changed }, null, 2));
|
|
@@ -121,23 +155,62 @@ async function sync(target, { yes = false, dryRun = false, force = false, provid
|
|
|
121
155
|
}
|
|
122
156
|
|
|
123
157
|
async function init(target, flags) {
|
|
124
|
-
|
|
158
|
+
const options = {
|
|
125
159
|
force: flags.force,
|
|
126
160
|
preset: flags.preset === undefined ? undefined : parseChoice(flags.preset, PRESETS, 'preset'),
|
|
127
161
|
modules: flags.modules === undefined ? undefined : parseChoice(flags.modules, MODULES, 'modules'),
|
|
128
162
|
compaction: flags.compaction === undefined ? undefined : parsePercent(flags.compaction),
|
|
129
163
|
tiers: flags.tiers === undefined ? undefined : parseTierSpec(flags.tiers),
|
|
164
|
+
claudeTier: flags['claude-tier'], codexTier: flags['codex-tier'], antigravityTier: flags['antigravity-tier'],
|
|
165
|
+
parent: flags.parent, allowUsageCredits: flags['allow-usage-credits'], allowFastModes: flags['allow-fast-modes'], verifiedOrg: flags['verified-org'],
|
|
130
166
|
};
|
|
167
|
+
for (const provider of PROVIDERS) {
|
|
168
|
+
const field = { claude: 'claudeTier', codex: 'codexTier', antigravity: 'antigravityTier' }[provider];
|
|
169
|
+
if (options[field] !== undefined && !Object.hasOwn(CATALOG[provider], options[field])) {
|
|
170
|
+
throw new CliError(`unknown ${provider} tier "${options[field]}"; valid tiers: ${Object.keys(CATALOG[provider]).join(', ')}`, 2);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (options.parent !== undefined && !['sonnet', 'opus', 'fable'].includes(options.parent)) {
|
|
174
|
+
throw new CliError('--parent must be sonnet, opus or fable', 2);
|
|
175
|
+
}
|
|
176
|
+
let finalOptions = options;
|
|
131
177
|
if (!flags.yes) {
|
|
132
|
-
if (!process.stdin.isTTY) throw new CliError('no interactive terminal; re-run with --yes (and
|
|
133
|
-
|
|
178
|
+
if (!process.stdin.isTTY) throw new CliError('no interactive terminal; re-run with --yes (and tier flags)', 2);
|
|
179
|
+
finalOptions = await initPrompts(target, options);
|
|
134
180
|
}
|
|
135
|
-
install(target,
|
|
181
|
+
install(target, finalOptions);
|
|
136
182
|
if (!flags.probe) return;
|
|
137
|
-
if (wantsAuto(readManifest(target).modules)) await sync(target, { yes:
|
|
183
|
+
if (wantsAuto(readManifest(target).modules)) await sync(target, { yes: true });
|
|
138
184
|
else console.log('warning: --probe does not apply to the core module; ignored');
|
|
139
185
|
}
|
|
140
186
|
|
|
187
|
+
async function check(target, flags) {
|
|
188
|
+
const config = rawConfig(target);
|
|
189
|
+
const result = await checkModels({
|
|
190
|
+
configDir: target, config, refresh: flags.refresh, probeScarce: flags['probe-scarce'], recheckLocks: flags['recheck-locks'],
|
|
191
|
+
});
|
|
192
|
+
if (flags.json) console.log(JSON.stringify(result, null, 2));
|
|
193
|
+
else {
|
|
194
|
+
console.log(`availability ${result.stale ? 'stale' : 'fresh'}; probed ${result.probed.length}; skipped scarce ${result.skippedScarce.length}`);
|
|
195
|
+
for (const { ref, status } of result.statuses) console.log(`${ref} ${status}`);
|
|
196
|
+
for (const { key, provider, model, result: outcome } of result.rechecked) {
|
|
197
|
+
console.log(outcome === 'via-t3' ? `recheck-via-t3: ${provider} (${model})` : `rechecked ${key} with ${model}: ${outcome}`);
|
|
198
|
+
}
|
|
199
|
+
for (const entry of result.availability.discoveredNew ?? []) console.log(`discovered ${entry.provider}:${entry.model}${entry.supersedes ? ` supersedes ${entry.supersedes}` : ' (unknown family)'}`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function availability(action, target, args, flags) {
|
|
204
|
+
if (action === 'status') {
|
|
205
|
+
const data = readAvailabilityFile(target);
|
|
206
|
+
if (!data) { console.log('availability cache missing or malformed'); return; }
|
|
207
|
+
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
|
+
for (const [ref, entry] of Object.entries(data.models ?? {})) console.log(`${ref}: ${entry.status}${entry.reason ? ` (${entry.reason})` : ''}`);
|
|
210
|
+
console.log(`drift: ${(data.discoveredNew ?? []).length} discovered, ${(data.missingConfigured ?? []).length} missing configured`);
|
|
211
|
+
} else markAvailability({ configDir: target, ref: args[0], status: args[1], ttl: flags.ttl, reason: flags.reason });
|
|
212
|
+
}
|
|
213
|
+
|
|
141
214
|
function quota(action, target, subject, flags) {
|
|
142
215
|
if (action === 'status') return quotaStatus(target);
|
|
143
216
|
if (action === 'check') return quotaCheck(target, { providers: subject === undefined ? undefined : [subject] });
|
|
@@ -147,9 +220,7 @@ function quota(action, target, subject, flags) {
|
|
|
147
220
|
}
|
|
148
221
|
const chosen = [...QUOTA_WINDOWS, 'until'].filter((name) => flags[name] !== undefined);
|
|
149
222
|
if (chosen.length > 1) throw new CliError(`use only one of ${chosen.map((name) => `--${name}`).join(', ')}`, 2);
|
|
150
|
-
return quotaSet(target, subject, {
|
|
151
|
-
window: chosen[0] === 'until' ? undefined : chosen[0], until: flags.until, reason: flags.reason,
|
|
152
|
-
});
|
|
223
|
+
return quotaSet(target, subject, { window: chosen[0] === 'until' ? undefined : chosen[0], until: flags.until, reason: flags.reason, pool: flags.pool });
|
|
153
224
|
}
|
|
154
225
|
|
|
155
226
|
async function main(argv) {
|
|
@@ -157,19 +228,21 @@ async function main(argv) {
|
|
|
157
228
|
if (flags.help) return console.log(USAGE);
|
|
158
229
|
if (flags.version) return console.log(JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8')).version);
|
|
159
230
|
const [first, ...rest] = positional;
|
|
160
|
-
const command = first === 'quota' ?
|
|
231
|
+
const command = first === 'quota' || first === 'availability' ? `${first} ${rest.shift()}` : first;
|
|
161
232
|
const [min, max] = ARGUMENTS[command] ?? [0, 0];
|
|
162
233
|
if (!Object.hasOwn(COMMAND_FLAGS, command) || rest.length < min || rest.length > max) throw new CliError(USAGE, 2);
|
|
163
234
|
const stray = Object.keys(flags).find((name) => name !== 'target' && !COMMAND_FLAGS[command].includes(name));
|
|
164
235
|
if (stray) throw new CliError(`--${stray} is not valid with ${command}`, 2);
|
|
165
236
|
const target = resolveTarget(flags.target);
|
|
166
|
-
|
|
167
237
|
if (command === 'init') await init(target, flags);
|
|
238
|
+
else if (command === 'upgrade') await upgrade(target);
|
|
168
239
|
else if (command === 'doctor') process.exitCode = doctor(target);
|
|
169
240
|
else if (command === 'uninstall') uninstall(target);
|
|
241
|
+
else if (command === 'check-models') await check(target, flags);
|
|
242
|
+
else if (command === 'availability mark' || command === 'availability status') availability(command.slice('availability '.length), target, rest, flags);
|
|
170
243
|
else if (command === 'sync-models') {
|
|
171
244
|
const providers = flags.providers === undefined ? undefined : parseProviders(flags.providers);
|
|
172
|
-
await sync(target, { yes: flags.yes, dryRun: flags['dry-run'], force: flags.force, providers });
|
|
245
|
+
await sync(target, { yes: flags.yes || flags.auto, dryRun: flags['dry-run'], force: flags.force, providers, refresh: flags.refresh, probeScarce: flags['probe-scarce'], apply: flags.apply });
|
|
173
246
|
} else await quota(command.slice('quota '.length), target, rest[0], flags);
|
|
174
247
|
}
|
|
175
248
|
|
package/hooks/_quota.mjs
CHANGED
|
@@ -1,17 +1,27 @@
|
|
|
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 {
|
|
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;
|
|
13
|
+
export const RECHECK_AFTER = 360 * MINUTE;
|
|
14
|
+
|
|
15
|
+
/** A lock lasting more than RECHECK_AFTER past setAt gets a recheckAfter time; others are returned unchanged. */
|
|
16
|
+
export function withRecheck(entry, now = Date.now()) {
|
|
17
|
+
if (!Number.isNaN(Date.parse(entry.recheckAfter))) return entry;
|
|
18
|
+
const setAt = Date.parse(entry.setAt) || now;
|
|
19
|
+
if (!(Date.parse(entry.until) - setAt > RECHECK_AFTER)) return entry;
|
|
20
|
+
return { ...entry, setAt: new Date(setAt).toISOString(), recheckAfter: new Date(setAt + RECHECK_AFTER).toISOString() };
|
|
21
|
+
}
|
|
10
22
|
|
|
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
23
|
const HEAVY_MODELS = { claude: ['Claude Opus 5.5'], codex: ['gpt-6-luna'], antigravity: ['Gemini 4 Carbon'] };
|
|
24
|
+
export const SCARCE_POOL = { claude: 'fable', codex: 'astra', antigravity: 'third-party-claude' };
|
|
15
25
|
|
|
16
26
|
const untilOf = (entry) => {
|
|
17
27
|
const text = entry?.until ?? entry?.until_utc;
|
|
@@ -54,6 +64,9 @@ function readRaw(file) {
|
|
|
54
64
|
}
|
|
55
65
|
|
|
56
66
|
const isValid = (key, value) => {
|
|
67
|
+
const validKey = /^(?:model:[^:]+(?::[^:]+)?|provider:[^:]+|tier:[^:]+:[a-z0-9-]+)$/i.test(key)
|
|
68
|
+
|| !/^(?:model|provider|tier):/i.test(key);
|
|
69
|
+
if (!validKey) return false;
|
|
57
70
|
try {
|
|
58
71
|
return Boolean(canonical(key, value));
|
|
59
72
|
} catch {
|
|
@@ -75,10 +88,11 @@ export function readCooldowns(file, onInvalid = (key) =>
|
|
|
75
88
|
* Atomic replace; an empty map removes the file. Invalid entries already in the file are kept as they are,
|
|
76
89
|
* unless data replaces their key or `remove` names it.
|
|
77
90
|
*/
|
|
78
|
-
export function writeCooldowns(file, data, { remove = [] } = {}) {
|
|
91
|
+
export function writeCooldowns(file, data, { remove = [], now = Date.now() } = {}) {
|
|
79
92
|
const invalid = Object.entries(readRaw(file))
|
|
80
93
|
.filter(([key, value]) => !Object.hasOwn(data, key) && !remove.includes(key) && !isValid(key, value));
|
|
81
|
-
const
|
|
94
|
+
const stamped = Object.entries(canonicalAll(data)).map(([key, entry]) => [key, withRecheck(entry, now)]);
|
|
95
|
+
const entries = Object.fromEntries([...stamped, ...invalid]);
|
|
82
96
|
if (Object.keys(entries).length === 0) {
|
|
83
97
|
fs.rmSync(file, { force: true });
|
|
84
98
|
return;
|
|
@@ -95,29 +109,67 @@ export function prune(data, now = Date.now()) {
|
|
|
95
109
|
return { kept: split(true), removed: split(false) };
|
|
96
110
|
}
|
|
97
111
|
|
|
98
|
-
function matches(key, scope, { provider, model, config }) {
|
|
112
|
+
function matches(key, scope, { provider, providers, model, config }) {
|
|
113
|
+
const declarations = [...new Set((providers ?? (provider === undefined ? [] : [provider]))
|
|
114
|
+
.filter((id) => typeof id === 'string' && id.trim() !== ''))];
|
|
115
|
+
const declared = [...new Set(declarations.map(canonicalProvider).filter(Boolean))];
|
|
116
|
+
const inferred = inferProvider(model);
|
|
117
|
+
const targets = [];
|
|
118
|
+
const target = resolveTarget({ providers: declarations, model }, config);
|
|
119
|
+
targets.push(target);
|
|
120
|
+
// A conflict is blocked separately by pre-tool-use, but cooldowns remain conservative for both sides.
|
|
121
|
+
const candidates = target.conflict ? [...new Set([...declared, inferred].filter(Boolean))] : [];
|
|
122
|
+
for (const candidate of candidates) {
|
|
123
|
+
targets.push(resolveTarget({ providers: [candidate], model }, config));
|
|
124
|
+
}
|
|
125
|
+
|
|
99
126
|
if (scope === 'provider') {
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
const
|
|
106
|
-
|
|
127
|
+
const wantedRaw = key.replace(/^provider:/i, '');
|
|
128
|
+
const compactKey = wantedRaw.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
129
|
+
const wantedProvider = ['claude', 'claudeagent', 'codex', 'antigravity'].includes(compactKey)
|
|
130
|
+
? canonicalProvider(wantedRaw) : null;
|
|
131
|
+
const wanted = normalizeName(wantedRaw);
|
|
132
|
+
const ids = new Set([
|
|
133
|
+
...declarations.map((id) => normalizeName(id)),
|
|
134
|
+
...declared,
|
|
135
|
+
...targets.map((item) => item.provider).filter(Boolean),
|
|
136
|
+
// Unknown aliases may still carry a model from a known provider.
|
|
137
|
+
...(!declared.length || target.conflict ? [inferred] : []),
|
|
138
|
+
].filter(Boolean).map(normalizeName));
|
|
139
|
+
return (wantedProvider ? ids.has(wantedProvider) : ids.has(wanted));
|
|
107
140
|
}
|
|
108
|
-
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
141
|
+
|
|
142
|
+
const modelMatch = (name) => {
|
|
143
|
+
if (!model) return false;
|
|
144
|
+
const keys = modelKeys(model, config);
|
|
145
|
+
return [...modelKeys(name, config)].some((candidate) => keys.has(candidate));
|
|
146
|
+
};
|
|
147
|
+
if (scope === 'model') {
|
|
148
|
+
const match = key.match(/^model:([^:]+):(.+)$/i);
|
|
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]));
|
|
153
|
+
}
|
|
154
|
+
return modelMatch(key.replace(/^model:/i, ''));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const tier = key.match(/^tier:([^:]+):([a-z0-9-]+)$/i);
|
|
113
158
|
if (!tier) return false;
|
|
114
|
-
const
|
|
115
|
-
|
|
159
|
+
const [, providerKey, pool] = tier;
|
|
160
|
+
const wantedProvider = canonicalProvider(providerKey) ?? normalizeName(providerKey);
|
|
161
|
+
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()]);
|
|
166
|
+
}
|
|
167
|
+
return targets.some((item) => normalizeName(item.provider ?? '') === wantedProvider && item.pool === pool.toLowerCase());
|
|
116
168
|
}
|
|
117
169
|
|
|
118
170
|
/** 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 };
|
|
171
|
+
export function isLocked(data, { provider, providers, model, config } = {}, now = Date.now()) {
|
|
172
|
+
const request = { provider, providers, model, config };
|
|
121
173
|
let lock = null;
|
|
122
174
|
for (const [key, value] of Object.entries(data)) {
|
|
123
175
|
const until = untilOf(value);
|