omnitrix 0.0.0-stage → 0.4.3
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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +341 -2
- package/dist/cli.js +972 -0
- package/dist/dashboard-launch.js +185 -0
- package/dist/dashboard.js +466 -0
- package/dist/drivers/anthropic.js +46 -0
- package/dist/drivers/cli.js +432 -0
- package/dist/drivers/http.js +197 -0
- package/dist/drivers/index.js +21 -0
- package/dist/drivers/ollama.js +33 -0
- package/dist/drivers/openai.js +64 -0
- package/dist/engine.js +1174 -0
- package/dist/index.js +6 -0
- package/dist/init.js +57 -0
- package/dist/mcp.js +351 -0
- package/dist/models.js +84 -0
- package/dist/owner.js +59 -0
- package/dist/providers.js +48 -0
- package/dist/quota.js +215 -0
- package/dist/router.js +239 -0
- package/dist/seats.js +119 -0
- package/dist/stats.js +47 -0
- package/dist/statusline.js +76 -0
- package/dist/store.js +303 -0
- package/dist/team.js +406 -0
- package/dist/types.js +24 -0
- package/dist/usage.js +361 -0
- package/dist/verify.js +144 -0
- package/dist/version.js +1 -0
- package/dist/worktree.js +146 -0
- package/package.json +67 -4
package/dist/usage.js
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
// Works out what each account has used per time window, from an append-only log of every request.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { ensureHome, files, processAlive } from './store.js';
|
|
5
|
+
const MIN = 60_000;
|
|
6
|
+
const HOUR = 60 * MIN;
|
|
7
|
+
const DAY = 24 * HOUR;
|
|
8
|
+
export function recordUsage(rec) {
|
|
9
|
+
ensureHome();
|
|
10
|
+
fs.appendFileSync(files.ledger(), JSON.stringify(rec) + '\n');
|
|
11
|
+
}
|
|
12
|
+
export function readLedger(sinceMs = 0) {
|
|
13
|
+
// While another process compacts, its old lines sit in a .compacting file. Counting them too means a
|
|
14
|
+
// reader never sees usage drop to zero; the overlap just before that file is deleted counts twice,
|
|
15
|
+
// which only errs towards caution.
|
|
16
|
+
let raw = '';
|
|
17
|
+
const live = files.ledger();
|
|
18
|
+
try {
|
|
19
|
+
const base = path.basename(live);
|
|
20
|
+
const parts = fs.readdirSync(path.dirname(live)).filter((n) => n === base || n.startsWith(`${base}.compacting.`));
|
|
21
|
+
for (const n of parts) {
|
|
22
|
+
try {
|
|
23
|
+
raw += fs.readFileSync(path.join(path.dirname(live), n), 'utf8') + '\n';
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
// renamed or deleted between the listing and the read
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return [];
|
|
32
|
+
}
|
|
33
|
+
const out = [];
|
|
34
|
+
for (const line of raw.split('\n')) {
|
|
35
|
+
if (!line)
|
|
36
|
+
continue;
|
|
37
|
+
try {
|
|
38
|
+
const rec = JSON.parse(line);
|
|
39
|
+
if (rec.ts >= sinceMs)
|
|
40
|
+
out.push(rec);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// a half-written line from a crash; skip it
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Keeps the ledger in memory and reads only the lines appended since the last call. The ledger only
|
|
50
|
+
* grows, except while it is compacted (it is renamed aside and rebuilt), so a shorter file or a
|
|
51
|
+
* .compacting file means everything is read again.
|
|
52
|
+
*/
|
|
53
|
+
export class LedgerTail {
|
|
54
|
+
offset = 0;
|
|
55
|
+
records = [];
|
|
56
|
+
prunedAt = 0;
|
|
57
|
+
// which file the offset belongs to: a ledger rebuilt by another process can have the same size
|
|
58
|
+
fileId = '';
|
|
59
|
+
read(sinceMs) {
|
|
60
|
+
const live = files.ledger();
|
|
61
|
+
try {
|
|
62
|
+
const base = path.basename(live);
|
|
63
|
+
if (fs.readdirSync(path.dirname(live)).some((n) => n.startsWith(`${base}.compacting.`))) {
|
|
64
|
+
this.offset = 0;
|
|
65
|
+
this.records = [];
|
|
66
|
+
return readLedger(sinceMs);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return [];
|
|
71
|
+
}
|
|
72
|
+
let size = 0;
|
|
73
|
+
let fileId = '';
|
|
74
|
+
try {
|
|
75
|
+
const st = fs.statSync(live, { bigint: true });
|
|
76
|
+
size = Number(st.size);
|
|
77
|
+
// Linux hands a new file the inode number of the one just deleted, so the first bytes count too:
|
|
78
|
+
// a rebuild always starts differently, because it drops the oldest records
|
|
79
|
+
fileId = `${st.dev}:${st.ino}:${firstBytes(live)}`;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
// no ledger yet
|
|
83
|
+
}
|
|
84
|
+
if (size < this.offset || fileId !== this.fileId) {
|
|
85
|
+
this.fileId = fileId;
|
|
86
|
+
this.offset = 0;
|
|
87
|
+
this.records = [];
|
|
88
|
+
}
|
|
89
|
+
if (size > this.offset) {
|
|
90
|
+
const buf = Buffer.alloc(size - this.offset);
|
|
91
|
+
const fd = fs.openSync(live, 'r');
|
|
92
|
+
try {
|
|
93
|
+
fs.readSync(fd, buf, 0, buf.length, this.offset);
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
fs.closeSync(fd);
|
|
97
|
+
}
|
|
98
|
+
// stop at the last complete line; a line still being written is picked up next time
|
|
99
|
+
const end = buf.lastIndexOf(10);
|
|
100
|
+
if (end >= 0) {
|
|
101
|
+
for (const line of buf.subarray(0, end).toString('utf8').split('\n')) {
|
|
102
|
+
if (!line)
|
|
103
|
+
continue;
|
|
104
|
+
try {
|
|
105
|
+
this.records.push(JSON.parse(line));
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
// a line left half-written by a crash
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
this.offset += end + 1;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// records only age out of the window, so trimming once a minute keeps memory bounded
|
|
115
|
+
if (Date.now() - this.prunedAt > 60_000) {
|
|
116
|
+
this.records = this.records.filter((r) => r.ts >= sinceMs);
|
|
117
|
+
this.prunedAt = Date.now();
|
|
118
|
+
}
|
|
119
|
+
return this.records.filter((r) => r.ts >= sinceMs);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Drop records older than 35 days once the file gets big.
|
|
124
|
+
* Other processes keep appending while this runs. So the ledger is first renamed to a file only this
|
|
125
|
+
* process owns: their new lines start a fresh ledger, and the kept lines are appended to it rather than
|
|
126
|
+
* written over it. Line order changes, which nothing depends on.
|
|
127
|
+
*/
|
|
128
|
+
function firstBytes(file) {
|
|
129
|
+
const buf = Buffer.alloc(256);
|
|
130
|
+
const fd = fs.openSync(file, 'r');
|
|
131
|
+
try {
|
|
132
|
+
return buf.subarray(0, fs.readSync(fd, buf, 0, buf.length, 0)).toString('base64');
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
fs.closeSync(fd);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// Records are appended in time order, so the first one shows whether anything is old enough to drop.
|
|
139
|
+
function oldestIsOld(live) {
|
|
140
|
+
const buf = Buffer.alloc(4096);
|
|
141
|
+
const fd = fs.openSync(live, 'r');
|
|
142
|
+
try {
|
|
143
|
+
const n = fs.readSync(fd, buf, 0, buf.length, 0);
|
|
144
|
+
const first = buf.subarray(0, n).toString('utf8').split('\n')[0];
|
|
145
|
+
return JSON.parse(first ?? '').ts < Date.now() - 35 * DAY;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
fs.closeSync(fd);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
export function compactLedger(maxBytes = 5_000_000) {
|
|
155
|
+
const live = files.ledger();
|
|
156
|
+
const mine = `${live}.compacting.${process.pid}`;
|
|
157
|
+
try {
|
|
158
|
+
const dir = path.dirname(live);
|
|
159
|
+
const base = path.basename(live);
|
|
160
|
+
// A process that crashed mid-compaction left its file behind; take it over by renaming it. A file
|
|
161
|
+
// already named for our own pid can only come from an earlier process that had the same pid.
|
|
162
|
+
const stranded = fs.readdirSync(dir).find((n) => {
|
|
163
|
+
const m = n.startsWith(`${base}.compacting.`) && /\.(\d+)$/.exec(n);
|
|
164
|
+
return m && (Number(m[1]) === process.pid || !processAlive(Number(m[1])));
|
|
165
|
+
});
|
|
166
|
+
if (stranded && path.join(dir, stranded) !== mine)
|
|
167
|
+
fs.renameSync(path.join(dir, stranded), mine);
|
|
168
|
+
else if (stranded) {
|
|
169
|
+
// already ours to finish
|
|
170
|
+
}
|
|
171
|
+
else if (fs.statSync(live).size >= maxBytes && oldestIsOld(live))
|
|
172
|
+
fs.renameSync(live, mine);
|
|
173
|
+
else
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const cutoff = Date.now() - 35 * DAY;
|
|
180
|
+
const keep = fs.readFileSync(mine, 'utf8').split('\n').filter((line) => {
|
|
181
|
+
try {
|
|
182
|
+
return line && JSON.parse(line).ts >= cutoff;
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
// The leading newline ends any half-written line a crashed writer left, so it cannot swallow ours.
|
|
189
|
+
if (keep.length)
|
|
190
|
+
fs.appendFileSync(live, '\n' + keep.join('\n') + '\n');
|
|
191
|
+
fs.rmSync(mine, { force: true });
|
|
192
|
+
}
|
|
193
|
+
/** Start of the current calendar month in local time. */
|
|
194
|
+
function monthStart(now) {
|
|
195
|
+
const d = new Date(now);
|
|
196
|
+
return new Date(d.getFullYear(), d.getMonth(), 1).getTime();
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* When `remaining` is used up at `perMs`, if that happens within `horizonMs`. Past the horizon the
|
|
200
|
+
* window resets, or for a rolling window its oldest use drops off, so a forecast would be wrong.
|
|
201
|
+
*/
|
|
202
|
+
function runOut(remaining, perMs, now, horizonMs) {
|
|
203
|
+
if (remaining <= 0 || perMs <= 0)
|
|
204
|
+
return undefined;
|
|
205
|
+
const ms = remaining / perMs;
|
|
206
|
+
return ms < horizonMs ? Math.round(now + ms) : undefined;
|
|
207
|
+
}
|
|
208
|
+
// A pace needs some evidence: three requests in the last hour, or a provider window at least 15 minutes old.
|
|
209
|
+
const MIN_PACE_REQUESTS = 3;
|
|
210
|
+
const MIN_PACE_MS = 15 * MIN;
|
|
211
|
+
export function summarize(account, records, health, now = Date.now(), quota) {
|
|
212
|
+
// One pass fills every window; this runs for every account on each routing pass and status call.
|
|
213
|
+
let minute = 0;
|
|
214
|
+
let fiveHours = 0;
|
|
215
|
+
let week = 0;
|
|
216
|
+
let day = 0;
|
|
217
|
+
let dayTokens = 0;
|
|
218
|
+
let dayCost = 0;
|
|
219
|
+
let monthTokens = 0;
|
|
220
|
+
let hour = 0;
|
|
221
|
+
let hourTokens = 0;
|
|
222
|
+
const monthFrom = monthStart(now);
|
|
223
|
+
for (const r of records) {
|
|
224
|
+
if (r.accountId !== account.id)
|
|
225
|
+
continue;
|
|
226
|
+
// failed calls that never reached the model do not count against a quota
|
|
227
|
+
if (!(r.ok || r.errorKind === 'rate_limit' || r.errorKind === 'quota'))
|
|
228
|
+
continue;
|
|
229
|
+
const t = r.inputTokens + r.outputTokens;
|
|
230
|
+
if (r.ts >= now - MIN)
|
|
231
|
+
minute++;
|
|
232
|
+
if (r.ts >= now - HOUR) {
|
|
233
|
+
hour++;
|
|
234
|
+
hourTokens += t;
|
|
235
|
+
}
|
|
236
|
+
if (r.ts >= now - 5 * HOUR)
|
|
237
|
+
fiveHours++;
|
|
238
|
+
if (r.ts >= now - 7 * DAY)
|
|
239
|
+
week++;
|
|
240
|
+
if (r.ts >= now - DAY) {
|
|
241
|
+
day++;
|
|
242
|
+
dayTokens += t;
|
|
243
|
+
dayCost += r.costUsd ?? 0;
|
|
244
|
+
}
|
|
245
|
+
if (r.ts >= monthFrom)
|
|
246
|
+
monthTokens += t;
|
|
247
|
+
}
|
|
248
|
+
const windows = [];
|
|
249
|
+
// Counted windows take their pace from the last hour, the best guide to the next few hours. One busy
|
|
250
|
+
// hour says little about a week or a month, so those windows (horizon 0) get no forecast.
|
|
251
|
+
const paced = hour >= MIN_PACE_REQUESTS;
|
|
252
|
+
const add = (name, used, limit, unit, horizonMs) => {
|
|
253
|
+
if (!limit || limit <= 0)
|
|
254
|
+
return;
|
|
255
|
+
const remaining = Math.max(0, limit - used);
|
|
256
|
+
const perMs = paced ? (unit === 'tokens' ? hourTokens : hour) / HOUR : 0;
|
|
257
|
+
windows.push({ name, used, limit, remaining, unit, runsOutAt: runOut(remaining, perMs, now, horizonMs) });
|
|
258
|
+
};
|
|
259
|
+
const l = account.limits;
|
|
260
|
+
add('1 minute', minute, l.requestsPerMinute, 'requests', 0);
|
|
261
|
+
add('5 hours', fiveHours, l.requestsPer5h, 'requests', 5 * HOUR);
|
|
262
|
+
add('24 hours', day, l.requestsPerDay, 'requests', DAY);
|
|
263
|
+
add('7 days', week, l.requestsPerWeek, 'requests', 0);
|
|
264
|
+
add('24 hours', dayTokens, l.tokensPerDay, 'tokens', DAY);
|
|
265
|
+
add('this month', monthTokens, l.tokensPerMonth, 'tokens', 0);
|
|
266
|
+
// Use only climbs inside a window, so an old reading stays a safe lower bound until the window resets.
|
|
267
|
+
// Without a reset time there is no telling when it stopped being true.
|
|
268
|
+
const live = quota?.windows.filter((w) => (w.resetsAt ? w.resetsAt > now : now - quota.at < 10 * MIN)) ?? [];
|
|
269
|
+
for (const w of live) {
|
|
270
|
+
// A provider window's pace is its use divided by how long it had been open when it was read. Counting
|
|
271
|
+
// from the reading, not from now, keeps an older reading from making the forecast late.
|
|
272
|
+
const at = quota.at;
|
|
273
|
+
const elapsed = w.minutes && w.resetsAt ? w.minutes * MIN - (w.resetsAt - at) : 0;
|
|
274
|
+
// A window longer than a day needs a day of use first: one large job early in a week is not a pace.
|
|
275
|
+
const enough = w.minutes * MIN > DAY ? DAY : MIN_PACE_MS;
|
|
276
|
+
const end = elapsed >= enough ? runOut(100 - w.usedPercent, w.usedPercent / elapsed, at, w.resetsAt - at) : undefined;
|
|
277
|
+
const runsOutAt = end && end > now ? end : undefined;
|
|
278
|
+
windows.push({ name: w.name, used: w.usedPercent, limit: 100, remaining: 100 - w.usedPercent, unit: 'percent', resetsAt: w.resetsAt, runsOutAt });
|
|
279
|
+
}
|
|
280
|
+
let percentUsed;
|
|
281
|
+
for (const w of windows) {
|
|
282
|
+
// Rounding up would mark an account with 0.5% left as exhausted and stop routing to it.
|
|
283
|
+
const p = Math.min(100, w.unit === 'percent' ? Math.floor(w.used) : Math.round((w.used / w.limit) * 100));
|
|
284
|
+
percentUsed = Math.max(percentUsed ?? 0, p);
|
|
285
|
+
}
|
|
286
|
+
// A fresh number straight from the provider beats our own count.
|
|
287
|
+
const m = health?.measured;
|
|
288
|
+
const fresh = m && now - m.at < 10 * MIN && (!m.resetAt || m.resetAt > now);
|
|
289
|
+
const source = fresh || live.length ? 'measured' : windows.length ? 'estimated' : 'untracked';
|
|
290
|
+
return {
|
|
291
|
+
accountId: account.id,
|
|
292
|
+
requestsToday: day,
|
|
293
|
+
tokensToday: dayTokens,
|
|
294
|
+
tokensMonth: monthTokens,
|
|
295
|
+
costToday: dayCost,
|
|
296
|
+
windows,
|
|
297
|
+
percentUsed,
|
|
298
|
+
source,
|
|
299
|
+
measured: fresh ? m : undefined,
|
|
300
|
+
plan: quota?.plan,
|
|
301
|
+
updatedAt: quota?.at || undefined,
|
|
302
|
+
stale: quota ? (quota.failedAt ?? 0) > quota.at || (quota.at > 0 && now - quota.at > 10 * MIN) : undefined,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
/** 0 = nothing left, 1 = all left. Used by the router to spread load. */
|
|
306
|
+
export function headroom(summary) {
|
|
307
|
+
const m = summary.measured;
|
|
308
|
+
if (m?.remainingRequests !== undefined && m.remainingRequests <= 0)
|
|
309
|
+
return 0;
|
|
310
|
+
if (summary.percentUsed === undefined)
|
|
311
|
+
return 0.8; // unknown: assume fine, but below a tracked fresh account
|
|
312
|
+
return Math.max(0, 1 - summary.percentUsed / 100);
|
|
313
|
+
}
|
|
314
|
+
const LATENCY_SAMPLES = 20;
|
|
315
|
+
const LATENCY_MIN_SAMPLES = 3;
|
|
316
|
+
const LATENCY_DAYS = 30;
|
|
317
|
+
/**
|
|
318
|
+
* Each model's typical answer time, keyed "account/model": the median of its last 20 successful answers
|
|
319
|
+
* in the last 30 days. A model with fewer than 3 such answers has no typical time yet; failures do not
|
|
320
|
+
* count, because a timeout says nothing about how fast the model answers.
|
|
321
|
+
*/
|
|
322
|
+
export function typicalLatency(records, now = Date.now()) {
|
|
323
|
+
const byModel = new Map();
|
|
324
|
+
for (const r of records) {
|
|
325
|
+
if (!r.ok || r.ts < now - LATENCY_DAYS * DAY || !(r.latencyMs > 0))
|
|
326
|
+
continue;
|
|
327
|
+
const key = `${r.accountId}/${r.model}`;
|
|
328
|
+
const list = byModel.get(key) ?? [];
|
|
329
|
+
list.push(r.ts, r.latencyMs);
|
|
330
|
+
byModel.set(key, list);
|
|
331
|
+
}
|
|
332
|
+
const out = {};
|
|
333
|
+
for (const [key, flat] of byModel) {
|
|
334
|
+
const pairs = [];
|
|
335
|
+
for (let i = 0; i < flat.length; i += 2)
|
|
336
|
+
pairs.push([flat[i], flat[i + 1]]);
|
|
337
|
+
const recent = pairs.sort((a, b) => b[0] - a[0]).slice(0, LATENCY_SAMPLES).map((p) => p[1]).sort((a, b) => a - b);
|
|
338
|
+
if (recent.length < LATENCY_MIN_SAMPLES)
|
|
339
|
+
continue;
|
|
340
|
+
const mid = Math.floor(recent.length / 2);
|
|
341
|
+
out[key] = recent.length % 2 ? recent[mid] : Math.round((recent[mid - 1] + recent[mid]) / 2);
|
|
342
|
+
}
|
|
343
|
+
return out;
|
|
344
|
+
}
|
|
345
|
+
/** "45 min", "1 h 20 min", "2 d 3 h": rounded, because a forecast is never exact. */
|
|
346
|
+
export function roughSpan(ms) {
|
|
347
|
+
const min = Math.max(1, Math.round(ms / 60_000));
|
|
348
|
+
if (min < 60)
|
|
349
|
+
return `${min} min`;
|
|
350
|
+
if (min < 24 * 60)
|
|
351
|
+
return `${Math.floor(min / 60)} h${min % 60 ? ` ${min % 60} min` : ''}`;
|
|
352
|
+
const h = Math.round(min / 60);
|
|
353
|
+
return `${Math.floor(h / 24)} d${h % 24 ? ` ${h % 24} h` : ''}`;
|
|
354
|
+
}
|
|
355
|
+
export function formatTokens(n) {
|
|
356
|
+
if (n >= 1_000_000)
|
|
357
|
+
return `${(n / 1_000_000).toFixed(1)}M`;
|
|
358
|
+
if (n >= 1_000)
|
|
359
|
+
return `${(n / 1_000).toFixed(1)}k`;
|
|
360
|
+
return String(n);
|
|
361
|
+
}
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// omnitrix's own check of a code job: which files changed, whether the task named them, and whether
|
|
2
|
+
// the task's test command passes. It is plain fact for Claude's review, not a verdict.
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { childEnv, killTree, launch, resolveCommand, stripTerminalCodes } from './drivers/cli.js';
|
|
8
|
+
import { redact } from './store.js';
|
|
9
|
+
const MAX_OUTPUT = 4000;
|
|
10
|
+
/** Path as git prints it: relative to the repository, with forward slashes. */
|
|
11
|
+
function norm(p) {
|
|
12
|
+
return p.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '');
|
|
13
|
+
}
|
|
14
|
+
/** The changed files that the task did not name. A named folder ("src/" or "src") covers what is inside it. */
|
|
15
|
+
export function outsideFiles(changed, task, repoRoot) {
|
|
16
|
+
if (!task.files?.length)
|
|
17
|
+
return undefined;
|
|
18
|
+
const named = task.files.map((f) => norm(path.isAbsolute(f) ? path.relative(repoRoot, f) : f));
|
|
19
|
+
return changed.filter((c) => !named.some((n) => c === n || c.startsWith(`${n}/`)));
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* How to start the test program. The name comes from the task, and resolveCommand hands it to a shell on
|
|
23
|
+
* macOS and Linux, so only a plain program name or an existing absolute path is accepted. A name found
|
|
24
|
+
* through a relative PATH entry such as "." would come from the worker's folder, so it is refused too.
|
|
25
|
+
*/
|
|
26
|
+
function findProgram(name) {
|
|
27
|
+
if (path.isAbsolute(name))
|
|
28
|
+
return fs.existsSync(name) ? { file: name, prefix: [], shell: /\.(cmd|bat)$/i.test(name) } : undefined;
|
|
29
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name))
|
|
30
|
+
return undefined;
|
|
31
|
+
const found = resolveCommand(name);
|
|
32
|
+
return found && path.isAbsolute(found.file) ? found : undefined;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The test's environment: no secrets by name or inside addresses, and a home folder of its own, so code
|
|
36
|
+
* that looks for logins under the home folder finds none. This is not a sandbox; the code can still open
|
|
37
|
+
* any file by its full path.
|
|
38
|
+
*/
|
|
39
|
+
function testEnv(home, extra) {
|
|
40
|
+
return childEnv(process.env, {
|
|
41
|
+
...extra,
|
|
42
|
+
HOME: home,
|
|
43
|
+
USERPROFILE: home,
|
|
44
|
+
APPDATA: path.join(home, 'AppData', 'Roaming'),
|
|
45
|
+
XDG_CONFIG_HOME: path.join(home, '.config'),
|
|
46
|
+
// Windows looks for programs in the current folder first, which is the worker's folder here
|
|
47
|
+
...(process.platform === 'win32' ? { NoDefaultCurrentDirectoryInExePath: '1' } : {}),
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/** Run the task's test command in the job's worktree, within `timeoutMs`; `signal` stops it early. */
|
|
51
|
+
export function runTest(command, cwd, timeoutMs, signal) {
|
|
52
|
+
const shown = command.join(' ');
|
|
53
|
+
const t0 = Date.now();
|
|
54
|
+
const refuse = (output) => Promise.resolve({ command: shown, status: 'error', output, durationMs: 0 });
|
|
55
|
+
const resolved = findProgram(command[0]);
|
|
56
|
+
if (!resolved)
|
|
57
|
+
return refuse(`"${command[0]}" is not a program name or path that omnitrix can start`);
|
|
58
|
+
// a .cmd program such as npm.cmd goes through cmd.exe, safely (see launch)
|
|
59
|
+
const start = launch(resolved, command.slice(1));
|
|
60
|
+
if (start.error)
|
|
61
|
+
return refuse(start.error);
|
|
62
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'omnitrix-test-home-'));
|
|
63
|
+
return new Promise((resolve) => {
|
|
64
|
+
let out = '';
|
|
65
|
+
let settled = false;
|
|
66
|
+
const finish = (r) => {
|
|
67
|
+
if (settled)
|
|
68
|
+
return;
|
|
69
|
+
settled = true;
|
|
70
|
+
try {
|
|
71
|
+
fs.rmSync(home, { recursive: true, force: true, maxRetries: 3 });
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// a process the test left behind can still hold a file on Windows; a stray temporary folder is
|
|
75
|
+
// better than a result that never arrives
|
|
76
|
+
}
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
signal?.removeEventListener('abort', onAbort);
|
|
79
|
+
// keys are hidden before the output is cut, so a cut never splits one out of sight; the first,
|
|
80
|
+
// possibly partial line is dropped
|
|
81
|
+
// terminal colour and cursor codes mean nothing to Claude and only take up its context
|
|
82
|
+
let text = redact(stripTerminalCodes(r.output ?? ''));
|
|
83
|
+
if (text.length > MAX_OUTPUT)
|
|
84
|
+
text = text.slice(-MAX_OUTPUT).replace(/^[^\n]*\n/, '');
|
|
85
|
+
resolve({ ...r, output: text, durationMs: Date.now() - t0 });
|
|
86
|
+
};
|
|
87
|
+
let stopped;
|
|
88
|
+
const timer = setTimeout(() => {
|
|
89
|
+
stopped = `stopped after ${Math.round(timeoutMs / 1000)} s`;
|
|
90
|
+
killTree(child?.pid);
|
|
91
|
+
}, timeoutMs);
|
|
92
|
+
const onAbort = () => {
|
|
93
|
+
stopped = 'cancelled';
|
|
94
|
+
killTree(child?.pid);
|
|
95
|
+
};
|
|
96
|
+
let child;
|
|
97
|
+
try {
|
|
98
|
+
child = spawn(start.file, start.args, { cwd, env: testEnv(home, start.env), windowsVerbatimArguments: start.verbatim, windowsHide: true, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
finish({ command: shown, status: 'error', output: `cannot start ${command[0]}: ${err instanceof Error ? err.message : err}` });
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (signal?.aborted)
|
|
105
|
+
onAbort();
|
|
106
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
107
|
+
const keep = (d) => {
|
|
108
|
+
out = (out + d).slice(-MAX_OUTPUT * 4);
|
|
109
|
+
};
|
|
110
|
+
// decoded as one stream, so a character split across two chunks stays whole
|
|
111
|
+
child.stdout.setEncoding('utf8');
|
|
112
|
+
child.stderr.setEncoding('utf8');
|
|
113
|
+
child.stdout.on('data', keep);
|
|
114
|
+
child.stderr.on('data', keep);
|
|
115
|
+
child.on('error', (err) => finish({ command: shown, status: 'error', output: `cannot start ${command[0]}: ${err.message}` }));
|
|
116
|
+
child.on('close', (code) => {
|
|
117
|
+
if (stopped)
|
|
118
|
+
return finish({ command: shown, status: 'error', output: `${out}\n${stopped}` });
|
|
119
|
+
finish({ command: shown, status: code === 0 ? 'passed' : 'failed', exitCode: code ?? undefined, output: out });
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/** Seconds as both the summary and get_results show them: whole seconds, at least 1. */
|
|
124
|
+
export function testSeconds(ms) {
|
|
125
|
+
return Math.max(1, Math.round(ms / 1000));
|
|
126
|
+
}
|
|
127
|
+
/** One line for Claude and the dashboard, such as "changed 2 files, all named in the task; tests passed (npm test, 4 s)". */
|
|
128
|
+
export function verifySummary(v) {
|
|
129
|
+
const n = v.files.length;
|
|
130
|
+
const parts = [n ? `changed ${n} file${n === 1 ? '' : 's'}` : 'changed no files'];
|
|
131
|
+
if (v.outside)
|
|
132
|
+
parts[0] += v.outside.length ? `; ${v.outside.length} not named in the task: ${v.outside.slice(0, 5).join(', ')}${v.outside.length > 5 ? ', ...' : ''}` : n ? ', all named in the task' : '';
|
|
133
|
+
const t = v.test;
|
|
134
|
+
if (t) {
|
|
135
|
+
const took = t.durationMs !== undefined ? `, ${testSeconds(t.durationMs)} s` : '';
|
|
136
|
+
const why = t.exitCode === undefined ? 'stopped by a signal' : `exit code ${t.exitCode}`;
|
|
137
|
+
parts.push(t.status === 'running' ? `tests running (${t.command})`
|
|
138
|
+
: t.status === 'passed' ? `tests passed (${t.command}${took})`
|
|
139
|
+
: t.status === 'failed' ? `tests failed (${why}, ${t.command}${took})`
|
|
140
|
+
: t.status === 'interrupted' ? `tests interrupted (${t.command})`
|
|
141
|
+
: `tests could not run (${t.command})`);
|
|
142
|
+
}
|
|
143
|
+
return parts.join('; ');
|
|
144
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = '0.4.3';
|
package/dist/worktree.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { files } from './store.js';
|
|
5
|
+
function git(cwd, args) {
|
|
6
|
+
const r = spawnSync('git', args, { cwd, encoding: 'utf8', windowsHide: true });
|
|
7
|
+
if (r.status !== 0)
|
|
8
|
+
throw new Error(`git ${args.join(' ')} failed: ${(r.stderr || r.stdout || '').trim()}`);
|
|
9
|
+
return r.stdout.trim();
|
|
10
|
+
}
|
|
11
|
+
export function isGitRepo(dir) {
|
|
12
|
+
const r = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: dir, encoding: 'utf8', windowsHide: true });
|
|
13
|
+
return r.status === 0 && r.stdout.trim() === 'true';
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Give a job its own copy of the repo on a new branch, so parallel workers never touch each other's files.
|
|
17
|
+
* The branch starts from the repo's current HEAD.
|
|
18
|
+
*/
|
|
19
|
+
export function createWorktree(repo, jobId) {
|
|
20
|
+
const root = git(repo, ['rev-parse', '--show-toplevel']);
|
|
21
|
+
const branch = `omnitrix/${jobId}`;
|
|
22
|
+
const dir = path.join(files.worktrees(), jobId);
|
|
23
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
24
|
+
git(root, ['worktree', 'add', '-b', branch, dir, 'HEAD']);
|
|
25
|
+
try {
|
|
26
|
+
// read before any worker runs: afterwards the worker could point .git anywhere
|
|
27
|
+
const gitDir = git(dir, ['rev-parse', '--absolute-git-dir']);
|
|
28
|
+
stripAgentConfig(dir);
|
|
29
|
+
return { path: dir, branch, root, gitDir };
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
discardWorktree(root, dir, branch);
|
|
33
|
+
throw err;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// Options for every git command in a worker's folder. The worker may have edited anything there, so git
|
|
37
|
+
// uses the git folder recorded when the worktree was made, and runs no hooks and no file monitor.
|
|
38
|
+
function workerGit(dir, gitDir) {
|
|
39
|
+
const noHooks = path.join(files.worktrees(), '.no-hooks');
|
|
40
|
+
fs.mkdirSync(noHooks, { recursive: true });
|
|
41
|
+
const where = gitDir ? ['--git-dir', gitDir, '--work-tree', dir] : [];
|
|
42
|
+
return [...where, '-c', 'core.fsmonitor=false', '-c', `core.hooksPath=${noHooks}`];
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A throwaway copy of the repo at its HEAD, on no branch, with agent settings removed. Read-only tasks for
|
|
46
|
+
* agent CLIs run here, so a worker can neither change the real repo nor load the repo's own hooks.
|
|
47
|
+
*/
|
|
48
|
+
export function createScratch(repo, jobId) {
|
|
49
|
+
const root = git(repo, ['rev-parse', '--show-toplevel']);
|
|
50
|
+
// a new name for each attempt, so a copy that Windows would not let go of never blocks the next one
|
|
51
|
+
const dir = path.join(files.worktrees(), `${jobId}-ro-${Date.now().toString(36)}`);
|
|
52
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
53
|
+
git(root, ['worktree', 'add', '--detach', dir, 'HEAD']);
|
|
54
|
+
try {
|
|
55
|
+
stripAgentConfig(dir);
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
removeScratch(root, dir);
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
return { path: dir, root };
|
|
62
|
+
}
|
|
63
|
+
/** Remove a throwaway copy made by createScratch. */
|
|
64
|
+
export function removeScratch(root, dir) {
|
|
65
|
+
removeWorktree(root, dir);
|
|
66
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
67
|
+
spawnSync('git', ['worktree', 'prune'], { cwd: root, windowsHide: true });
|
|
68
|
+
}
|
|
69
|
+
/** Agent settings a repository can carry: hooks, MCP servers, plugins and permission overrides. */
|
|
70
|
+
export const AGENT_CONFIG = ['.claude', '.mcp.json', '.codex', '.gemini', '.qwen', '.opencode', 'opencode.json', 'opencode.jsonc', '.agy', '.antigravity'];
|
|
71
|
+
/**
|
|
72
|
+
* A repo can carry its own agent settings (hooks, MCP servers) that a worker CLI would run.
|
|
73
|
+
* Remove them from the worker's copy so a task can never execute repo-provided hooks.
|
|
74
|
+
*/
|
|
75
|
+
export function stripAgentConfig(dir) {
|
|
76
|
+
for (const name of AGENT_CONFIG) {
|
|
77
|
+
fs.rmSync(path.join(dir, name), { recursive: true, force: true });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Commit whatever the worker changed and report a short diff summary. */
|
|
81
|
+
export function finishWorktree(dir, message, gitDir) {
|
|
82
|
+
const safe = workerGit(dir, gitDir);
|
|
83
|
+
git(dir, [...safe, 'add', '-A']);
|
|
84
|
+
// the files removed by stripAgentConfig must not show up as deletions
|
|
85
|
+
for (const name of AGENT_CONFIG) {
|
|
86
|
+
spawnSync('git', [...safe, 'reset', '-q', 'HEAD', '--', name], { cwd: dir, windowsHide: true });
|
|
87
|
+
}
|
|
88
|
+
const staged = spawnSync('git', [...safe, 'diff', '--cached', '--quiet'], { cwd: dir, windowsHide: true });
|
|
89
|
+
if (staged.status === 0)
|
|
90
|
+
return { diffStat: 'no changes', changed: false };
|
|
91
|
+
// use the repo owner's git identity; only fall back when none is set
|
|
92
|
+
const hasIdentity = spawnSync('git', [...safe, 'config', 'user.email'], { cwd: dir, encoding: 'utf8', windowsHide: true }).stdout.trim() !== '';
|
|
93
|
+
const identity = hasIdentity ? [] : ['-c', 'user.name=omnitrix', '-c', 'user.email=omnitrix@localhost'];
|
|
94
|
+
git(dir, [...safe, ...identity, 'commit', '-q', '--no-verify', '-m', message]);
|
|
95
|
+
const stat = git(dir, [...safe, 'diff', '--stat', 'HEAD~1', 'HEAD']);
|
|
96
|
+
return { diffStat: stat, changed: true };
|
|
97
|
+
}
|
|
98
|
+
/** The files changed by the last commit on the worker's branch, read with the recorded git folder. */
|
|
99
|
+
export function changedFiles(dir, gitDir) {
|
|
100
|
+
// without rename detection a moved file shows both its old and its new path, so a move cannot hide a
|
|
101
|
+
// change to a file the task did not name; -z keeps unusual names exactly as they are
|
|
102
|
+
const out = spawnSync('git', [...workerGit(dir, gitDir), 'diff', '--name-only', '--no-renames', '-z', 'HEAD~1', 'HEAD'], { cwd: dir, encoding: 'utf8', windowsHide: true });
|
|
103
|
+
return out.status === 0 ? out.stdout.split('\0').filter(Boolean) : [];
|
|
104
|
+
}
|
|
105
|
+
export function removeWorktree(repoRoot, dir) {
|
|
106
|
+
spawnSync('git', ['worktree', 'remove', '--force', dir], { cwd: repoRoot, windowsHide: true });
|
|
107
|
+
}
|
|
108
|
+
/** Throw away a worker's copy and its branch (used before retrying a job on another account). */
|
|
109
|
+
export function discardWorktree(repoRoot, dir, branch) {
|
|
110
|
+
removeWorktree(repoRoot, dir);
|
|
111
|
+
spawnSync('git', ['branch', '-D', branch], { cwd: repoRoot, windowsHide: true });
|
|
112
|
+
try {
|
|
113
|
+
fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3 });
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
// a process the worker left behind can still hold a file on Windows; `omnitrix clean` removes it later
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** The git object id of a file at a revision, or '' when the file or the revision does not exist there. */
|
|
120
|
+
export function fileVersion(repo, rev, file) {
|
|
121
|
+
const out = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${rev}:${file}`], { cwd: repo, encoding: 'utf8', windowsHide: true });
|
|
122
|
+
return out.status === 0 ? out.stdout.trim() : '';
|
|
123
|
+
}
|
|
124
|
+
/** True when everything on the branch is already in the repo's current HEAD. */
|
|
125
|
+
export function branchMerged(repo, branch) {
|
|
126
|
+
return spawnSync('git', ['merge-base', '--is-ancestor', `refs/heads/${branch}`, 'HEAD'], { cwd: repo, windowsHide: true }).status === 0;
|
|
127
|
+
}
|
|
128
|
+
export function branchExists(repo, branch) {
|
|
129
|
+
return spawnSync('git', ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], { cwd: repo, windowsHide: true }).status === 0;
|
|
130
|
+
}
|
|
131
|
+
export function deleteBranch(repo, branch) {
|
|
132
|
+
return spawnSync('git', ['branch', '-D', branch], { cwd: repo, windowsHide: true }).status === 0;
|
|
133
|
+
}
|
|
134
|
+
/** Remove a finished job's checkout but keep its branch, so accepted work can still be merged later. */
|
|
135
|
+
export function pruneWorktree(dir) {
|
|
136
|
+
if (!fs.existsSync(dir))
|
|
137
|
+
return false;
|
|
138
|
+
const common = spawnSync('git', ['rev-parse', '--git-common-dir'], { cwd: dir, encoding: 'utf8', windowsHide: true });
|
|
139
|
+
if (common.status === 0) {
|
|
140
|
+
const root = path.dirname(path.resolve(dir, common.stdout.trim()));
|
|
141
|
+
removeWorktree(root, dir);
|
|
142
|
+
spawnSync('git', ['worktree', 'prune'], { cwd: root, windowsHide: true });
|
|
143
|
+
}
|
|
144
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
145
|
+
return true;
|
|
146
|
+
}
|