t3-auto-build 1.0.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +96 -0
- package/README.md +367 -118
- package/bin/cli.mjs +148 -82
- package/hooks/_quota.mjs +63 -21
- package/hooks/_shared.mjs +162 -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 +410 -0
- package/lib/doctor.mjs +42 -2
- package/lib/install.mjs +234 -29
- package/lib/plans.mjs +309 -0
- package/lib/probe.mjs +48 -14
- package/lib/prompt.mjs +82 -5
- package/lib/quota.mjs +54 -15
- 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 +10 -7
package/lib/discover.mjs
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// Tier-1 availability: zero-inference discovery, the cached availability file and model drift. Node >=18, node:* only.
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {
|
|
7
|
+
AVAILABILITY_FILE, COOLDOWN_FILE, RETIRED_MODELS, canonicalProvider, inferProvider, isBanned, isObject, isStringList,
|
|
8
|
+
matchRetired, modelKeys, normalizeModel, readAvailability, warn, which as findOnPath,
|
|
9
|
+
} from '../hooks/_shared.mjs';
|
|
10
|
+
import { prune, readCooldowns, writeCooldowns } from '../hooks/_quota.mjs';
|
|
11
|
+
import { CliError } from './paths.mjs';
|
|
12
|
+
import { MODELS, PROVIDERS, supersedes } from './plans.mjs';
|
|
13
|
+
import { probeModels } from './probe.mjs';
|
|
14
|
+
|
|
15
|
+
const UNIT_MS = { m: 60_000, h: 3_600_000, d: 86_400_000 };
|
|
16
|
+
const MAX_TTL = 30 * UNIT_MS.d;
|
|
17
|
+
const CACHE_TTL = 12 * UNIT_MS.h;
|
|
18
|
+
const MAX_OUTPUT = 1_000_000;
|
|
19
|
+
const STATUSES = ['available', 'plan-restricted', 'unavailable'];
|
|
20
|
+
// Adapter output and the availability file are untrusted, and these ids can end up in the config and SKILL.md.
|
|
21
|
+
const DISCOVERED_ID = /^(?=.*\d)[a-z0-9][a-z0-9._-]{0,79}$/;
|
|
22
|
+
const MARKED_MODEL = /^[\p{L}\p{N}][\p{L}\p{N} ._:/()[\]-]{0,99}$/u;
|
|
23
|
+
|
|
24
|
+
/** "30m" | "24h" | "30d" in milliseconds; more than 0 and at most 30 days. */
|
|
25
|
+
export function parseTtl(text = '24h') {
|
|
26
|
+
const match = typeof text === 'string' ? text.match(/^(\d+)(m|h|d)$/) : null;
|
|
27
|
+
const ms = match ? Number(match[1]) * UNIT_MS[match[2]] : 0;
|
|
28
|
+
if (!(ms > 0 && ms <= MAX_TTL)) {
|
|
29
|
+
throw new CliError(`invalid ttl "${String(text).slice(0, 20)}"; use <n>m, <n>h or <n>d, up to 30d`, 2);
|
|
30
|
+
}
|
|
31
|
+
return ms;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** { family, version } of a model id or display name, else null. */
|
|
35
|
+
export function parseFamily(id) {
|
|
36
|
+
if (typeof id !== 'string') return null;
|
|
37
|
+
const name = normalizeModel(id.trim().toLowerCase().replace(/\s+/g, '-'));
|
|
38
|
+
if (Object.hasOwn(MODELS, name)) return { family: MODELS[name].family, version: MODELS[name].version };
|
|
39
|
+
const other = name.match(/^(gpt|gemini)-(\d+(?:\.\d+)*)-([a-z]+(?:-[a-z]+)*)$/);
|
|
40
|
+
if (other) return { family: `${other[1]}-${other[3]}`, version: other[2] };
|
|
41
|
+
const claude = name.match(/^claude-([a-z]+)-(\d+(?:[.-]\d+)*)$/);
|
|
42
|
+
return claude ? { family: `claude-${claude[1]}`, version: claude[2].replace(/-/g, '.') } : null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const sameModel = (a, b, config) => {
|
|
46
|
+
const keys = modelKeys(a, config);
|
|
47
|
+
return [...modelKeys(b, config)].some((key) => keys.has(key));
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** Usable config.models entries, with canonical provider keys. */
|
|
51
|
+
const configuredModels = (config) => (Array.isArray(config?.models) ? config.models : [])
|
|
52
|
+
.filter((entry) => isObject(entry) && typeof entry.model === 'string' && canonicalProvider(entry.provider))
|
|
53
|
+
.map((entry) => ({ ...entry, provider: canonicalProvider(entry.provider) }));
|
|
54
|
+
|
|
55
|
+
const list = (value) => (isStringList(value) ? value : []);
|
|
56
|
+
const retiredPatterns = (config) => [...RETIRED_MODELS, ...list(config?.retiredModels)];
|
|
57
|
+
const bannedTerms = (config) => [...list(config?.bannedModels), ...list(config?.userBannedModels)];
|
|
58
|
+
|
|
59
|
+
const failed = (code) => ({ status: null, stdout: '', stderr: '', error: { code } });
|
|
60
|
+
|
|
61
|
+
// A .cmd shim goes through run() in a node child, which keeps its quoting rules and leaves this process free to kill it.
|
|
62
|
+
const SHIM_RUNNER = `const { run } = await import(${JSON.stringify(new URL('../hooks/_shared.mjs', import.meta.url).href)});
|
|
63
|
+
const [file, args] = JSON.parse(process.argv[1]);
|
|
64
|
+
process.exitCode = run(file, args, { stdio: ['ignore', 'inherit', 'ignore'] })?.status ?? 1;`;
|
|
65
|
+
|
|
66
|
+
function killTree(child) {
|
|
67
|
+
if (!child.pid) return;
|
|
68
|
+
if (process.platform === 'win32') {
|
|
69
|
+
const taskkill = path.join(process.env.SystemRoot || 'C:/Windows', 'System32', 'taskkill.exe');
|
|
70
|
+
spawn(taskkill, ['/pid', String(child.pid), '/t', '/f'], { stdio: 'ignore', windowsHide: true })
|
|
71
|
+
.on('error', () => child.kill()).unref();
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
process.kill(-child.pid, 'SIGKILL'); // the child leads its own process group
|
|
76
|
+
} catch {
|
|
77
|
+
// already gone
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Async counterpart of probe.mjs createRunner: runs in an empty temp directory and kills the tree on timeout. */
|
|
82
|
+
const asyncRunner = (which) => (cmd, args, { timeout }) => new Promise((resolve) => {
|
|
83
|
+
const executable = path.isAbsolute(cmd) ? cmd : which(cmd);
|
|
84
|
+
if (!executable) {
|
|
85
|
+
resolve(failed('ENOENT'));
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const [file, argv] = /\.(cmd|bat)$/i.test(executable)
|
|
89
|
+
? [process.execPath, ['--input-type=module', '-e', SHIM_RUNNER, JSON.stringify([executable, args])]]
|
|
90
|
+
: [executable, args];
|
|
91
|
+
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 't3-discover-'));
|
|
92
|
+
let timer;
|
|
93
|
+
let stdout = '';
|
|
94
|
+
const finish = (result) => {
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
try {
|
|
97
|
+
fs.rmSync(cwd, { recursive: true, force: true });
|
|
98
|
+
} catch {
|
|
99
|
+
// still held by a dying child; the OS temp cleanup takes it
|
|
100
|
+
}
|
|
101
|
+
resolve(result);
|
|
102
|
+
};
|
|
103
|
+
let child;
|
|
104
|
+
try {
|
|
105
|
+
child = spawn(file, argv, {
|
|
106
|
+
cwd, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, detached: process.platform !== 'win32',
|
|
107
|
+
});
|
|
108
|
+
} catch (error) {
|
|
109
|
+
finish(failed(error.code));
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const abort = (code) => {
|
|
113
|
+
killTree(child);
|
|
114
|
+
child.stdout.destroy();
|
|
115
|
+
child.unref();
|
|
116
|
+
finish(failed(code));
|
|
117
|
+
};
|
|
118
|
+
timer = setTimeout(() => abort('ETIMEDOUT'), timeout);
|
|
119
|
+
child.stdout.setEncoding('utf8').on('data', (chunk) => {
|
|
120
|
+
stdout += chunk;
|
|
121
|
+
if (stdout.length > MAX_OUTPUT) abort('ENOBUFS');
|
|
122
|
+
});
|
|
123
|
+
child.on('error', (error) => finish(failed(error.code)));
|
|
124
|
+
child.on('close', (status) => finish({ status, stdout, stderr: '' }));
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
/** Never rejects and never takes longer than timeoutMs, whatever the runner does. */
|
|
128
|
+
function bounded(work, timeoutMs) {
|
|
129
|
+
let timer;
|
|
130
|
+
const deadline = new Promise((resolve) => { timer = setTimeout(() => resolve(failed('ETIMEDOUT')), timeoutMs); });
|
|
131
|
+
const attempt = Promise.resolve().then(work).catch((error) => failed(error?.code));
|
|
132
|
+
return Promise.race([attempt, deadline]).finally(() => clearTimeout(timer));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const succeeded = (result) => result?.status === 0 && !result.error;
|
|
136
|
+
|
|
137
|
+
const versionIn = (result) => (succeeded(result)
|
|
138
|
+
? String(result.stdout).slice(0, 500).match(/\d+(?:\.\d+)+(?:-[0-9A-Za-z.]{1,20})?/)?.[0] ?? null
|
|
139
|
+
: null);
|
|
140
|
+
|
|
141
|
+
/** Model ids from a JSON array or one-per-line output; null when the adapter failed or listed nothing usable. */
|
|
142
|
+
function modelIdsIn(result) {
|
|
143
|
+
if (!succeeded(result)) return null;
|
|
144
|
+
const text = String(result.stdout).replace(/^\uFEFF/, '').trim();
|
|
145
|
+
let items = text.split(/\r?\n/);
|
|
146
|
+
if (text.startsWith('[')) {
|
|
147
|
+
try {
|
|
148
|
+
items = JSON.parse(text);
|
|
149
|
+
} catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const ids = [...new Set(items.filter((item) => typeof item === 'string')
|
|
154
|
+
.map((item) => item.trim().toLowerCase())
|
|
155
|
+
.filter((item) => DISCOVERED_ID.test(item)))];
|
|
156
|
+
return ids.length ? ids : null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Binary checks and optional listing adapters, in parallel. Never runs inference. */
|
|
160
|
+
export async function discover({ config, runner, which = findOnPath, now = Date.now(), timeoutMs = 1500 } = {}) {
|
|
161
|
+
const exec = runner ?? asyncRunner(which);
|
|
162
|
+
const call = (cmd, args) => bounded(() => exec(cmd, args, { timeout: timeoutMs }), timeoutMs);
|
|
163
|
+
// shortcut: no built-in listing adapters, as no CLI documents one; only config.discovery argv. Add one when a CLI does.
|
|
164
|
+
const hosts = await Promise.all(PROVIDERS.map(async (provider) => {
|
|
165
|
+
const found = Boolean(which(provider));
|
|
166
|
+
const argv = config?.discovery?.[provider];
|
|
167
|
+
const [version, listing] = await Promise.all([
|
|
168
|
+
found ? call(provider, ['--version']) : null,
|
|
169
|
+
isStringList(argv) && argv.length > 0 ? call(argv[0], argv.slice(1)) : null,
|
|
170
|
+
]);
|
|
171
|
+
return { provider, found, version: versionIn(version), listed: modelIdsIn(listing) };
|
|
172
|
+
}));
|
|
173
|
+
|
|
174
|
+
const configured = configuredModels(config);
|
|
175
|
+
const checkedAt = new Date(now).toISOString();
|
|
176
|
+
const models = {};
|
|
177
|
+
const discoveredNew = [];
|
|
178
|
+
const missingConfigured = [];
|
|
179
|
+
for (const { provider, listed } of hosts) {
|
|
180
|
+
if (!listed) continue;
|
|
181
|
+
const mine = configured.filter((entry) => entry.provider === provider);
|
|
182
|
+
for (const id of listed) {
|
|
183
|
+
const match = mine.find((entry) => sameModel(entry.model, id, config));
|
|
184
|
+
if (match) {
|
|
185
|
+
models[`${provider}:${match.model}`] = { status: 'available', source: 'discover', checkedAt };
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const parsed = parseFamily(id);
|
|
189
|
+
const item = { provider, model: id, family: parsed?.family ?? null, version: parsed?.version ?? null };
|
|
190
|
+
let newest = null;
|
|
191
|
+
for (const entry of parsed ? mine : []) {
|
|
192
|
+
const other = parseFamily(entry.model);
|
|
193
|
+
if (other?.family === parsed.family && (!newest || supersedes(other, newest.parsed))) {
|
|
194
|
+
newest = { model: entry.model, parsed: other };
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (newest && supersedes(parsed, newest.parsed) && !matchRetired(id, retiredPatterns(config))) {
|
|
198
|
+
item.supersedes = newest.model;
|
|
199
|
+
}
|
|
200
|
+
discoveredNew.push(item);
|
|
201
|
+
}
|
|
202
|
+
// Cross-hosted models are not expected in a provider's own listing.
|
|
203
|
+
missingConfigured.push(...mine
|
|
204
|
+
.filter((entry) => inferProvider(entry.model) === provider
|
|
205
|
+
&& !listed.some((id) => sameModel(entry.model, id, config)))
|
|
206
|
+
.map((entry) => `${provider}:${entry.model}`));
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
binaries: Object.fromEntries(hosts.map(({ provider, found, version }) => [provider, { found, version }])),
|
|
210
|
+
models,
|
|
211
|
+
discoveredNew,
|
|
212
|
+
missingConfigured,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** The stored availability data, or null when the file is missing or unusable. */
|
|
217
|
+
export function readAvailabilityFile(configDir) {
|
|
218
|
+
return readAvailability(path.join(configDir, AVAILABILITY_FILE)).data;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function writeAvailability(configDir, data) {
|
|
222
|
+
const file = path.join(configDir, AVAILABILITY_FILE);
|
|
223
|
+
const stored = { ...data, schemaVersion: 1 };
|
|
224
|
+
fs.mkdirSync(configDir, { recursive: true });
|
|
225
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
226
|
+
fs.writeFileSync(temp, `${JSON.stringify(stored, null, 2)}\n`);
|
|
227
|
+
fs.renameSync(temp, file);
|
|
228
|
+
return stored;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Entries without an expired "until"; an unreadable one is kept, as restrictedBy does. */
|
|
232
|
+
const unexpired = (models, now) => Object.fromEntries(Object.entries(models ?? {})
|
|
233
|
+
.filter(([, entry]) => isObject(entry) && !(Date.parse(entry.until) <= now)));
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Stores an entry, replacing every spelling of the same provider:model. A live manual mark beats any other source,
|
|
237
|
+
* and a listing alone never lifts a restriction.
|
|
238
|
+
*/
|
|
239
|
+
function put(models, provider, model, entry, now) {
|
|
240
|
+
const matches = Object.keys(models).filter((ref) => {
|
|
241
|
+
const [, host, name] = ref.match(/^([^:]+):(.+)$/) ?? [];
|
|
242
|
+
return name !== undefined && canonicalProvider(host) === provider && sameModel(name, model);
|
|
243
|
+
});
|
|
244
|
+
if (entry.source !== 'mark'
|
|
245
|
+
&& matches.some((ref) => models[ref].source === 'mark' && Date.parse(models[ref].until) > now)) return;
|
|
246
|
+
if (entry.source === 'discover' && matches.some((ref) => models[ref].status !== 'available')) return;
|
|
247
|
+
for (const ref of matches) delete models[ref];
|
|
248
|
+
models[`${provider}:${model}`] = entry;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Drops expired locks and adds new ones without ever shortening an existing lock. */
|
|
252
|
+
function updateCooldowns(configDir, now, locks = []) {
|
|
253
|
+
const file = path.join(configDir, COOLDOWN_FILE);
|
|
254
|
+
let stored;
|
|
255
|
+
try {
|
|
256
|
+
stored = readCooldowns(file);
|
|
257
|
+
} catch (error) {
|
|
258
|
+
warn(`${COOLDOWN_FILE} left unchanged: it cannot be read (${error.code ?? error.name})`);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const { kept, removed } = prune(stored, now);
|
|
262
|
+
let added = 0;
|
|
263
|
+
for (const { key, entry } of locks) {
|
|
264
|
+
if (Date.parse(kept[key]?.until) >= Date.parse(entry.until)) continue;
|
|
265
|
+
kept[key] = entry;
|
|
266
|
+
added += 1;
|
|
267
|
+
}
|
|
268
|
+
if (added || Object.keys(removed).length > 0) writeCooldowns(file, kept, { remove: Object.keys(removed) });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Configured models worth spending a probe on, grouped by provider, and the scarce ones left out. */
|
|
272
|
+
function probeCandidates(config, probeScarce) {
|
|
273
|
+
const candidates = {};
|
|
274
|
+
const skippedScarce = [];
|
|
275
|
+
for (const { provider, model, scarceQuota } of configuredModels(config)) {
|
|
276
|
+
if (matchRetired(model, retiredPatterns(config)) || isBanned(model, bannedTerms(config))) continue;
|
|
277
|
+
if (scarceQuota && !probeScarce) skippedScarce.push(`${provider}:${model}`);
|
|
278
|
+
else (candidates[provider] ??= []).push(model);
|
|
279
|
+
}
|
|
280
|
+
return { candidates, skippedScarce };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Prunes expired state, runs discovery, probes only when the cache is stale or refresh is set, and saves the result.
|
|
285
|
+
* checkedAt dates the last probe run, so discovery alone never keeps the cache fresh.
|
|
286
|
+
*/
|
|
287
|
+
export async function checkModels({
|
|
288
|
+
configDir, config, refresh = false, probeScarce = false, ttlMs = CACHE_TTL, now = Date.now(), runner, which,
|
|
289
|
+
probe = probeModels,
|
|
290
|
+
} = {}) {
|
|
291
|
+
updateCooldowns(configDir, now);
|
|
292
|
+
const found = await discover({ config, runner, which, now });
|
|
293
|
+
const checkedAt = readAvailabilityFile(configDir)?.checkedAt;
|
|
294
|
+
const stale = !(now - Date.parse(checkedAt) <= ttlMs);
|
|
295
|
+
const probing = stale || refresh;
|
|
296
|
+
let results = [];
|
|
297
|
+
let skippedScarce = [];
|
|
298
|
+
if (probing) {
|
|
299
|
+
const selected = probeCandidates(config, probeScarce);
|
|
300
|
+
skippedScarce = selected.skippedScarce;
|
|
301
|
+
({ results } = await probe({
|
|
302
|
+
config, candidates: selected.candidates, probeScarce, runner, which, now,
|
|
303
|
+
}));
|
|
304
|
+
updateCooldowns(configDir, now, results.filter((r) => r.cooldown).map((r) => r.cooldown));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Read again: a mark may have been written while the probes ran.
|
|
308
|
+
const models = unexpired(readAvailabilityFile(configDir)?.models, now);
|
|
309
|
+
const stamp = new Date(now).toISOString();
|
|
310
|
+
for (const [ref, entry] of Object.entries(found.models)) {
|
|
311
|
+
const [, provider, model] = ref.match(/^([^:]+):(.+)$/);
|
|
312
|
+
put(models, provider, model, entry, now);
|
|
313
|
+
}
|
|
314
|
+
for (const { provider, model, state, skipped } of results) {
|
|
315
|
+
// "unavailable" also means timeout, logged out or unprobeable, so it must not block the model.
|
|
316
|
+
if (skipped || !['available', 'plan-restricted'].includes(state)) continue;
|
|
317
|
+
put(models, canonicalProvider(provider), model, { status: state, source: 'probe', checkedAt: stamp }, now);
|
|
318
|
+
}
|
|
319
|
+
const availability = writeAvailability(configDir, {
|
|
320
|
+
checkedAt: probing ? stamp : checkedAt,
|
|
321
|
+
ttlMs,
|
|
322
|
+
binaries: found.binaries,
|
|
323
|
+
models,
|
|
324
|
+
discoveredNew: found.discoveredNew,
|
|
325
|
+
missingConfigured: found.missingConfigured,
|
|
326
|
+
});
|
|
327
|
+
const probed = results.filter((r) => !r.skipped).map((r) => `${canonicalProvider(r.provider)}:${r.model}`);
|
|
328
|
+
return { availability, probed, skippedScarce, stale };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Records a manual status for one hosting of a model, effective immediately and until the ttl ends. */
|
|
332
|
+
export function markAvailability({ configDir, ref, status, ttl = '24h', reason, now = Date.now() } = {}) {
|
|
333
|
+
const [, host, rest = ''] = String(ref ?? '').match(/^([^:]+):(.*)$/s) ?? [];
|
|
334
|
+
const provider = canonicalProvider(host);
|
|
335
|
+
const model = rest.trim();
|
|
336
|
+
if (!provider || !MARKED_MODEL.test(model)) {
|
|
337
|
+
throw new CliError(`invalid model reference; use <${PROVIDERS.join('|')}>:<model>`, 2);
|
|
338
|
+
}
|
|
339
|
+
if (!STATUSES.includes(status)) throw new CliError(`invalid status; use ${STATUSES.join(', ')}`, 2);
|
|
340
|
+
const note = String(reason ?? '').replace(/[\s\p{Cc}\p{Cf}]+/gu, ' ').trim().slice(0, 200);
|
|
341
|
+
const entry = {
|
|
342
|
+
status,
|
|
343
|
+
source: 'mark',
|
|
344
|
+
checkedAt: new Date(now).toISOString(),
|
|
345
|
+
until: new Date(now + parseTtl(ttl)).toISOString(),
|
|
346
|
+
...(note && { reason: note }),
|
|
347
|
+
};
|
|
348
|
+
// A file created by a mark has never been probed, so it starts out stale.
|
|
349
|
+
const data = readAvailabilityFile(configDir) ?? {
|
|
350
|
+
checkedAt: new Date(0).toISOString(), ttlMs: CACHE_TTL, binaries: {}, models: {}, discoveredNew: [],
|
|
351
|
+
missingConfigured: [],
|
|
352
|
+
};
|
|
353
|
+
const models = unexpired(data.models, now);
|
|
354
|
+
put(models, provider, model, entry, now);
|
|
355
|
+
writeAvailability(configDir, { ...data, models });
|
|
356
|
+
return entry;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* A copy of config with every superseded model replaced by its newest discovered successor, for that hosting only.
|
|
361
|
+
* The availability data is re-checked here: only a newer version of a configured family is ever promoted.
|
|
362
|
+
*/
|
|
363
|
+
export function applyDrift(config, availability) {
|
|
364
|
+
const next = structuredClone(config);
|
|
365
|
+
const drift = (Array.isArray(availability?.discoveredNew) ? availability.discoveredNew : []).filter(isObject);
|
|
366
|
+
const configured = configuredModels(config);
|
|
367
|
+
const restricted = list(config?.planRestrictedModels);
|
|
368
|
+
const best = new Map();
|
|
369
|
+
for (const { provider: host, model, supersedes: old } of drift) {
|
|
370
|
+
const provider = canonicalProvider(host);
|
|
371
|
+
if (typeof old !== 'string' || typeof model !== 'string' || !DISCOVERED_ID.test(model)) continue;
|
|
372
|
+
const mine = configured.filter((entry) => entry.provider === provider);
|
|
373
|
+
const from = mine.find((entry) => sameModel(entry.model, old, config));
|
|
374
|
+
const parsed = parseFamily(model);
|
|
375
|
+
if (!from || !parsed || !supersedes(parsed, parseFamily(from.model) ?? {})) continue;
|
|
376
|
+
if (matchRetired(model, retiredPatterns(config)) || isBanned(model, bannedTerms(config))) continue;
|
|
377
|
+
if (restricted.includes(model) || restricted.includes(`${provider}:${model}`)) continue;
|
|
378
|
+
if (mine.some((entry) => sameModel(entry.model, model, config))) continue;
|
|
379
|
+
const key = `${provider}:${from.model}`;
|
|
380
|
+
const current = best.get(key);
|
|
381
|
+
if (!current || supersedes(parsed, current.parsed)) best.set(key, { provider, from: from.model, to: model, parsed });
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
for (const { provider, from, to, parsed } of best.values()) {
|
|
385
|
+
const isOld = (name) => typeof name === 'string' && sameModel(name, from, config);
|
|
386
|
+
next.models = next.models.map((entry) => (canonicalProvider(entry?.provider) === provider && isOld(entry.model)
|
|
387
|
+
? { ...entry, model: to, ...parsed } : entry));
|
|
388
|
+
for (const [group, names] of Object.entries(next.allowlist ?? {})) {
|
|
389
|
+
if (canonicalProvider(group) !== provider || !Array.isArray(names)) continue;
|
|
390
|
+
next.allowlist[group] = [...new Set(names.map((name) => (isOld(name) ? to : name)))];
|
|
391
|
+
}
|
|
392
|
+
for (const [slot, entries] of Object.entries(next.ladders ?? {})) {
|
|
393
|
+
if (!Array.isArray(entries)) continue;
|
|
394
|
+
next.ladders[slot] = entries.map((ref) => {
|
|
395
|
+
// [provider:]model[@effort]; a bare model means its native provider.
|
|
396
|
+
const parts = typeof ref === 'string' ? ref.match(/^(\s*(?:([^:@]+):)?\s*)([^@]*?)(\s*(?:@.*)?)$/) : null;
|
|
397
|
+
if (!parts) return ref;
|
|
398
|
+
const [, head, prefix, name, tail] = parts;
|
|
399
|
+
const hosting = prefix === undefined ? inferProvider(name) : canonicalProvider(prefix);
|
|
400
|
+
return hosting === provider && isOld(name) ? `${head}${to}${tail}` : ref;
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
if (inferProvider(from) === provider && isOld(next.defaultModel)) next.defaultModel = to;
|
|
404
|
+
}
|
|
405
|
+
return {
|
|
406
|
+
config: next,
|
|
407
|
+
promoted: [...best.values()].map(({ provider, from, to }) => ({ provider, from, to })),
|
|
408
|
+
unknown: drift.filter((entry) => !entry.supersedes),
|
|
409
|
+
};
|
|
410
|
+
}
|
package/lib/doctor.mjs
CHANGED
|
@@ -2,9 +2,10 @@ import { spawnSync } from 'node:child_process';
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
-
import { CONFIG_FILE, COOLDOWN_FILE, isObject, readJson, run, which } from '../hooks/_shared.mjs';
|
|
5
|
+
import { AVAILABILITY_FILE, CONFIG_FILE, COOLDOWN_FILE, RETIRED_MODELS, isObject, readAvailability, readJson, run, which } from '../hooks/_shared.mjs';
|
|
6
6
|
import { completeConfig, configProblem, moduleFiles, wantsAuto } from './install.mjs';
|
|
7
7
|
import { fileHash, readManifest } from './manifest.mjs';
|
|
8
|
+
import { CATALOG, PROVIDERS } from './plans.mjs';
|
|
8
9
|
import { safePath } from './paths.mjs';
|
|
9
10
|
import { HOOKS, HOOKS_DIR, readSettings, taggedHooks } from './settings.mjs';
|
|
10
11
|
|
|
@@ -21,6 +22,23 @@ const TOOLS = [
|
|
|
21
22
|
},
|
|
22
23
|
];
|
|
23
24
|
|
|
25
|
+
function v2Problem(config) {
|
|
26
|
+
if (config.schemaVersion !== 2) return 'schemaVersion must be 2';
|
|
27
|
+
if (!isObject(config.subscriptions) || PROVIDERS.some((provider) => !Object.hasOwn(CATALOG[provider], config.subscriptions[provider]))) {
|
|
28
|
+
return 'subscriptions must name a known tier for claude, codex and antigravity';
|
|
29
|
+
}
|
|
30
|
+
if (!Array.isArray(config.models) || config.models.some((entry) => !isObject(entry)
|
|
31
|
+
|| !PROVIDERS.includes(entry.provider) || typeof entry.model !== 'string' || !entry.model.trim()
|
|
32
|
+
|| typeof entry.pool !== 'string' || typeof entry.scarceQuota !== 'boolean'
|
|
33
|
+
|| typeof entry.family !== 'string' || typeof entry.version !== 'string')) return 'models entries must include provider, model, pool, scarceQuota, family and version';
|
|
34
|
+
if (!isObject(config.ladders) || Object.values(config.ladders).some((entries) => !Array.isArray(entries)
|
|
35
|
+
|| entries.some((entry) => typeof entry !== 'string' || !entry.trim()))) return 'ladders must map names to non-empty model reference lists';
|
|
36
|
+
if (!Array.isArray(config.retiredModels) || RETIRED_MODELS.some((model) => !config.retiredModels.includes(model))) {
|
|
37
|
+
return 'retiredModels must include every built-in retired model';
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
24
42
|
// Each hook runs with mock stdin from a temporary copy, so the real cooldown file is never touched.
|
|
25
43
|
function smokeTest(target, report) {
|
|
26
44
|
const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 't3ab-doctor-'));
|
|
@@ -96,8 +114,30 @@ export function doctor(target, log = console.log) {
|
|
|
96
114
|
}
|
|
97
115
|
const problem = isObject(config) ? configProblem(completeConfig(config)) : 'not a JSON object';
|
|
98
116
|
if (problem) throw new Error(`${CONFIG_FILE}: ${problem}`);
|
|
99
|
-
|
|
117
|
+
if (config.schemaVersion === undefined) {
|
|
118
|
+
report('warn', `${CONFIG_FILE}: legacy v1 config — run \`t3-auto-build upgrade\``);
|
|
119
|
+
} else {
|
|
120
|
+
const v2 = v2Problem(config);
|
|
121
|
+
if (v2) throw new Error(`${CONFIG_FILE}: ${v2}`);
|
|
122
|
+
report('ok', `${CONFIG_FILE} v2 is valid`);
|
|
123
|
+
for (const provider of PROVIDERS) {
|
|
124
|
+
const tierId = config.subscriptions[provider];
|
|
125
|
+
const tier = CATALOG[provider][tierId];
|
|
126
|
+
if (!tier.cliSupported) report('warn', `${provider} tier ${tierId} is not supported by its CLI`);
|
|
127
|
+
else if (!which(provider)) report('warn', `${provider} tier ${tierId} is configured but its CLI binary is missing`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
100
130
|
});
|
|
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`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
101
141
|
}
|
|
102
142
|
if (settings) {
|
|
103
143
|
const tagged = taggedHooks(settings.data);
|