omnitrix 0.0.0-stage → 0.5.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/dist/quota.js ADDED
@@ -0,0 +1,215 @@
1
+ // Read live account quota from the Codex app server.
2
+ import { spawn } from 'node:child_process';
3
+ import os from 'node:os';
4
+ import { createInterface } from 'node:readline';
5
+ import { childEnv, killTree, launch, resolveCommand } from './drivers/cli.js';
6
+ import { files, readJson, withLock, writeJson } from './store.js';
7
+ import { VERSION } from './version.js';
8
+ function isRecord(value) {
9
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
10
+ }
11
+ export function parseCodexRateLimits(result, now = Date.now()) {
12
+ try {
13
+ if (!isRecord(result) || !isRecord(result.rateLimits))
14
+ return undefined;
15
+ const limits = result.rateLimits;
16
+ const windows = [];
17
+ for (const value of [limits.primary, limits.secondary]) {
18
+ if (!isRecord(value))
19
+ continue;
20
+ const { usedPercent, windowDurationMins: mins, resetsAt } = value;
21
+ if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent)
22
+ || typeof mins !== 'number' || !Number.isFinite(mins) || mins <= 0)
23
+ continue;
24
+ const window = {
25
+ name: mins === 300 ? '5 hours' : mins === 10080 ? '7 days' : `${mins} minutes`,
26
+ minutes: mins,
27
+ usedPercent: Math.max(0, Math.min(100, usedPercent)),
28
+ };
29
+ // A window cannot reset later than its own length from now. A later time (or one in milliseconds)
30
+ // would keep a stale reading in use for years, so drop it and let the reading age out instead.
31
+ if (typeof resetsAt === 'number' && Number.isFinite(resetsAt) && resetsAt * 1000 <= now + (mins + 60) * 60_000) {
32
+ window.resetsAt = resetsAt * 1000;
33
+ }
34
+ windows.push(window);
35
+ }
36
+ if (!windows.length)
37
+ return undefined;
38
+ const quota = { at: now, windows };
39
+ // The plan name reaches Claude in pool_status, so only a short plain word is allowed through.
40
+ if (typeof limits.planType === 'string' && /^[a-z0-9_-]{1,24}$/i.test(limits.planType))
41
+ quota.plan = limits.planType;
42
+ return quota;
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ }
48
+ function validWindow(w) {
49
+ return isRecord(w) && typeof w.name === 'string' && w.name.length <= 80 && typeof w.usedPercent === 'number' && Number.isFinite(w.usedPercent)
50
+ && (w.minutes === undefined || (typeof w.minutes === 'number' && Number.isFinite(w.minutes)))
51
+ && (w.resetsAt === undefined || (typeof w.resetsAt === 'number' && Number.isFinite(w.resetsAt)));
52
+ }
53
+ /** Saved readings; an entry that is not a well-formed reading counts as no reading. */
54
+ export function loadQuotas() {
55
+ const raw = readJson(files.quota(), {});
56
+ const out = {};
57
+ if (!isRecord(raw))
58
+ return out;
59
+ for (const [id, q] of Object.entries(raw)) {
60
+ if (!isRecord(q) || typeof q.at !== 'number' || !Array.isArray(q.windows) || !q.windows.every(validWindow))
61
+ continue;
62
+ if (q.plan !== undefined && typeof q.plan !== 'string')
63
+ continue;
64
+ if (q.failedAt !== undefined && typeof q.failedAt !== 'number')
65
+ continue;
66
+ out[id] = q;
67
+ }
68
+ return out;
69
+ }
70
+ const reading = new Map();
71
+ // Failed reads count too, or a logged-out account would start Codex on every dashboard poll.
72
+ const lastTried = new Map();
73
+ /**
74
+ * Note a failed read. The last good reading stays, with its own time, so the dashboard can still show it
75
+ * and say how old it is; the failure time throttles the other omnitrix processes too.
76
+ */
77
+ export function saveQuotaFailure(accountId, now = Date.now()) {
78
+ withLock(files.quota(), () => {
79
+ const all = loadQuotas();
80
+ all[accountId] = { ...(all[accountId] ?? { at: 0, windows: [] }), failedAt: now };
81
+ writeJson(files.quota(), all);
82
+ });
83
+ }
84
+ async function refreshOne(account, profileDir) {
85
+ try {
86
+ const quota = await readCodexQuota(profileDir);
87
+ if (quota)
88
+ withLock(files.quota(), () => writeJson(files.quota(), { ...loadQuotas(), [account.id]: quota }));
89
+ else
90
+ saveQuotaFailure(account.id);
91
+ }
92
+ catch {
93
+ // Quota is a nice-to-have; a failed read must never fail the caller.
94
+ }
95
+ finally {
96
+ reading.delete(account.id);
97
+ }
98
+ }
99
+ /**
100
+ * Never rejects, so callers can start it without waiting. After `waitMs` it returns even if a read
101
+ * is still running; that read finishes in the background and saves its result for the next caller.
102
+ */
103
+ export async function refreshQuotas(accounts, maxAgeMs = 60_000, waitMs = Infinity) {
104
+ const now = Date.now();
105
+ const saved = loadQuotas();
106
+ const pending = [];
107
+ for (const account of accounts) {
108
+ if (!account.enabled || account.provider !== 'codex' || !account.profileDir)
109
+ continue;
110
+ let read = reading.get(account.id);
111
+ if (!read) {
112
+ if (now - Math.max(saved[account.id]?.at ?? 0, saved[account.id]?.failedAt ?? 0, lastTried.get(account.id) ?? 0) < maxAgeMs)
113
+ continue;
114
+ lastTried.set(account.id, now);
115
+ read = refreshOne(account, account.profileDir);
116
+ reading.set(account.id, read);
117
+ }
118
+ pending.push(read);
119
+ }
120
+ if (!pending.length)
121
+ return;
122
+ let timer;
123
+ const deadline = Number.isFinite(waitMs) ? new Promise((resolve) => { timer = setTimeout(resolve, waitMs); }) : undefined;
124
+ await Promise.race(deadline ? [Promise.all(pending), deadline] : [Promise.all(pending)]);
125
+ clearTimeout(timer);
126
+ }
127
+ export async function readCodexQuota(profileDir, timeoutMs = 20000) {
128
+ try {
129
+ const resolved = resolveCommand('codex');
130
+ if (!resolved)
131
+ return undefined;
132
+ return await new Promise((resolve) => {
133
+ // An exported API key would make Codex report that key's limits instead of this account's plan.
134
+ const start = launch(resolved, ['app-server']);
135
+ const env = childEnv(process.env, { CODEX_HOME: profileDir, ...start.env });
136
+ const child = spawn(start.file, start.args, {
137
+ env: env,
138
+ // A neutral folder, so a project's own Codex settings can't change what the app server does.
139
+ cwd: os.tmpdir(),
140
+ windowsHide: true,
141
+ windowsVerbatimArguments: start.verbatim,
142
+ detached: process.platform !== 'win32',
143
+ stdio: ['pipe', 'pipe', 'pipe'],
144
+ });
145
+ let finished = false;
146
+ let initialized = false;
147
+ const lines = createInterface({ input: child.stdout });
148
+ const finish = (quota) => {
149
+ if (finished)
150
+ return;
151
+ finished = true;
152
+ clearTimeout(timer);
153
+ lines.close();
154
+ try {
155
+ // Killing a shell wrapper can leave Codex running, but Codex exits by itself when stdin closes.
156
+ child.stdin.end();
157
+ child.kill();
158
+ }
159
+ catch {
160
+ // The process may already be gone.
161
+ }
162
+ resolve(quota);
163
+ };
164
+ // A Codex that never answers may also ignore stdin closing, so take down its whole process tree.
165
+ const timer = setTimeout(() => {
166
+ killTree(child.pid);
167
+ finish();
168
+ }, timeoutMs);
169
+ const send = (message) => {
170
+ try {
171
+ child.stdin.write(`${JSON.stringify(message)}\n`);
172
+ }
173
+ catch {
174
+ finish();
175
+ }
176
+ };
177
+ child.on('error', () => finish());
178
+ child.on('exit', () => finish());
179
+ child.stdin.on('error', () => finish());
180
+ child.stdout.on('error', () => finish());
181
+ child.stderr.on('error', () => finish());
182
+ child.stderr.resume();
183
+ lines.on('line', (line) => {
184
+ if (finished)
185
+ return;
186
+ let msg;
187
+ try {
188
+ msg = JSON.parse(line);
189
+ }
190
+ catch {
191
+ return;
192
+ }
193
+ if (!isRecord(msg) || (msg.id !== 1 && msg.id !== 2))
194
+ return;
195
+ if (msg.error !== undefined) {
196
+ finish();
197
+ }
198
+ else if (msg.id === 1 && !initialized) {
199
+ initialized = true;
200
+ send({ method: 'initialized' });
201
+ send({ id: 2, method: 'account/rateLimits/read' });
202
+ }
203
+ else if (msg.id === 2) {
204
+ finish(parseCodexRateLimits(msg.result));
205
+ }
206
+ });
207
+ send({ id: 1, method: 'initialize', params: {
208
+ clientInfo: { name: 'omnitrix', title: 'omnitrix', version: VERSION },
209
+ } });
210
+ });
211
+ }
212
+ catch {
213
+ return undefined;
214
+ }
215
+ }
package/dist/router.js ADDED
@@ -0,0 +1,246 @@
1
+ // Picks the account and model for a task. Hard rules go first (privacy, health, quota, what the driver
2
+ // can do); whatever is left gets a score, and the highest score gets the task.
3
+ import { basisOf, statsKey } from './models.js';
4
+ import { acceptanceFactor } from './stats.js';
5
+ import { headroom, roughSpan } from './usage.js';
6
+ /** How much each skill matters for each kind of task. Each row adds up to 1. */
7
+ const WEIGHTS = {
8
+ code: { coding: 0.7, reasoning: 0.2, speed: 0.1 },
9
+ code_snippet: { coding: 0.7, reasoning: 0.2, speed: 0.1 },
10
+ review: { reasoning: 0.5, coding: 0.4, longContext: 0.1 },
11
+ reasoning: { reasoning: 0.8, coding: 0.1, writing: 0.1 },
12
+ long_context: { longContext: 0.6, reasoning: 0.3, speed: 0.1 },
13
+ bulk: { speed: 0.5, writing: 0.3, reasoning: 0.2 },
14
+ writing: { writing: 0.7, reasoning: 0.2, speed: 0.1 },
15
+ vision: { vision: 0.7, reasoning: 0.3 },
16
+ };
17
+ // a local model larger than the graphics card's memory runs mostly on the processor, many times slower
18
+ const TOO_BIG_FOR_GPU = 0.4;
19
+ /** True when the address is this computer, so a "local" account really keeps prompts here. */
20
+ export function loopback(baseUrl) {
21
+ try {
22
+ const host = new URL(baseUrl ?? '').hostname.replace(/^\[|\]$/g, '');
23
+ return host === 'localhost' || host === '::1' || /^127\.\d+\.\d+\.\d+$/.test(host);
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ export function fit(skills, type) {
30
+ let total = 0;
31
+ for (const [skill, w] of Object.entries(WEIGHTS[type]))
32
+ total += (skills[skill] ?? 0) * (w ?? 0);
33
+ return total / 10;
34
+ }
35
+ function costFactor(model, account, mode, type) {
36
+ if (mode === 'quality')
37
+ return 1;
38
+ const price = (model.inputPrice ?? 0) + (model.outputPrice ?? 0) * 3;
39
+ if (account.local || price === 0)
40
+ return 1; // free, local, or already paid for by a plan
41
+ // bulk work is where paying per token adds up, so cost counts for more there
42
+ const strength = mode === 'saver' ? 1 : type === 'bulk' ? 0.6 : 0.25;
43
+ return 1 / (1 + (price / 20) * strength);
44
+ }
45
+ // These multiply the score after the quota factor. They can reorder accounts of similar fit, not
46
+ // overturn a large difference in fit, and a pin still outranks them.
47
+ const RESET_SOON_MS = 60 * 60_000;
48
+ const RESET_SOON_MIN_LEFT = 0.2;
49
+ // Big enough to beat an account with somewhat more quota left, since the quota factor otherwise counts
50
+ // soon-to-vanish quota against the account that should spend it.
51
+ const RESET_SOON_BONUS = 1.25;
52
+ const RUNNING_OUT_PENALTY = 0.75;
53
+ const PUBLIC_ONLY_BONUS = 1.15;
54
+ /** No price is known. Prices are only set by hand, so this does not prove the model is free. */
55
+ function unpriced(model) {
56
+ return !model.inputPrice && !model.outputPrice;
57
+ }
58
+ /**
59
+ * An account forecast to run dry is spared; otherwise quota that resets soon is used before it is lost.
60
+ * `room` is the account's tightest window, so a nearly spent weekly window blocks the bonus of a
61
+ * 5-hour window: spending the 5-hour quota would spend the weekly quota too.
62
+ */
63
+ function timing(usage, room, now) {
64
+ const windows = usage?.windows ?? [];
65
+ const dry = windows.filter((w) => w.runsOutAt && w.runsOutAt > now).sort((a, b) => a.runsOutAt - b.runsOutAt)[0];
66
+ if (dry)
67
+ return { factor: RUNNING_OUT_PENALTY, why: [`${dry.name} runs out in about ${roughSpan(dry.runsOutAt - now)} at this pace`] };
68
+ const soon = room >= RESET_SOON_MIN_LEFT && windows.find((w) => w.resetsAt && w.resetsAt > now && w.resetsAt - now <= RESET_SOON_MS);
69
+ if (soon)
70
+ return { factor: RESET_SOON_BONUS, why: [`${soon.name} resets in ${roughSpan(soon.resetsAt - now)} with ${Math.round(room * 100)}% left`] };
71
+ return { factor: 1, why: [] };
72
+ }
73
+ export function effectivePrivacy(task) {
74
+ return task.privacy ?? 'private';
75
+ }
76
+ /** Rank every account+model that can do this task. Best first. */
77
+ export function route(task, ctx) {
78
+ const now = ctx.now ?? Date.now();
79
+ const { settings } = ctx.config;
80
+ const privacy = effectivePrivacy(task);
81
+ const pins = settings.pins[task.type] ?? [];
82
+ const [forcedAccount, forcedModel] = task.use ? splitUse(task.use) : [undefined, undefined];
83
+ const candidates = [];
84
+ // the quickest typical time seen, which a model's own typical time is compared with
85
+ const fastest = task.fast ? Math.min(...Object.values(ctx.latency ?? {})) : Infinity;
86
+ const rejected = [];
87
+ for (const account of ctx.config.accounts) {
88
+ const reject = (reason, model) => rejected.push({ accountId: account.id, model, reason });
89
+ if (forcedAccount && account.id !== forcedAccount)
90
+ continue;
91
+ if (task.avoid?.includes(account.id)) {
92
+ reject('avoided for this task');
93
+ continue;
94
+ }
95
+ // only a team account is held to the team's budgets, even when the developer has an account with the same id
96
+ if (account.team && ctx.blocked?.[account.id]) {
97
+ reject(ctx.blocked[account.id]);
98
+ continue;
99
+ }
100
+ if (task.textOnly && account.driver === 'cli') {
101
+ reject('this task runs without tools, so agent CLIs are not used');
102
+ continue;
103
+ }
104
+ if (!account.enabled) {
105
+ reject('disabled');
106
+ continue;
107
+ }
108
+ if (settings.bannedProviders.includes(account.provider)) {
109
+ reject('provider is banned in settings');
110
+ continue;
111
+ }
112
+ const h = ctx.health[account.id];
113
+ if (h && (h.state === 'auth_error' || h.state === 'disabled')) {
114
+ reject(`${h.state}: ${h.reason ?? ''}`.trim());
115
+ continue;
116
+ }
117
+ if (h && (h.state === 'cooling' || h.state === 'exhausted' || h.state === 'offline') && (h.until ?? 0) > now) {
118
+ reject(`${h.state} until ${new Date(h.until).toLocaleTimeString()}`);
119
+ continue;
120
+ }
121
+ if (task.type === 'code' && account.driver !== 'cli') {
122
+ reject('code tasks need an agent CLI that can edit files');
123
+ continue;
124
+ }
125
+ if (privacy === 'secret' && !(account.local && loopback(account.baseUrl))) {
126
+ reject('secret task: local models only');
127
+ continue;
128
+ }
129
+ if (privacy === 'private' && settings.protectPrivate && account.trainsOnData) {
130
+ reject('private task: this provider may train on prompts');
131
+ continue;
132
+ }
133
+ const usage = ctx.usage[account.id];
134
+ const room = usage ? headroom(usage) : 0.8;
135
+ if (room <= 0) {
136
+ reject('no quota left in the current window');
137
+ continue;
138
+ }
139
+ const models = forcedModel ? account.models.filter((m) => m.id === forcedModel) : account.models;
140
+ if (models.length === 0) {
141
+ reject(forcedModel ? `model ${forcedModel} not on this account` : 'no models configured');
142
+ continue;
143
+ }
144
+ const busy = (ctx.running[account.id] ?? 0) >= account.concurrency;
145
+ // only the API drivers attach pictures; an agent CLI would get the file name and nothing else
146
+ if (task.type === 'vision' && account.driver !== 'openai' && account.driver !== 'anthropic') {
147
+ reject('this account cannot send images');
148
+ continue;
149
+ }
150
+ for (const model of models) {
151
+ if (task.avoid?.includes(`${account.id}/${model.id}`)) {
152
+ reject('avoided for this task', model.id);
153
+ continue;
154
+ }
155
+ const paused = ctx.health[modelHealthKey(account.id, model.id)];
156
+ if (paused && paused.state === 'cooling' && (paused.until ?? 0) > now) {
157
+ reject(`paused until ${new Date(paused.until).toLocaleTimeString()} (${paused.reason ?? 'not answering'})`, model.id);
158
+ continue;
159
+ }
160
+ // Ollama's "-cloud" models run on Ollama's servers, even through a local Ollama
161
+ if (privacy === 'secret' && /[-:]cloud$/i.test(model.id)) {
162
+ reject('secret task: this model runs in the cloud', model.id);
163
+ continue;
164
+ }
165
+ if (task.type === 'vision' && account.local && !model.visionChecked && !model.pinned) {
166
+ reject('the server has not reported that this model reads images', model.id);
167
+ continue;
168
+ }
169
+ if (task.type === 'vision' && model.skills.vision < 5) {
170
+ reject('model cannot read images', model.id);
171
+ continue;
172
+ }
173
+ const why = [];
174
+ const f = fit(model.skills, task.type);
175
+ if (task.minFit !== undefined && f < task.minFit) {
176
+ reject(`weaker at ${task.type} (fit ${f.toFixed(2)}) than the worker it would check`, model.id);
177
+ continue;
178
+ }
179
+ let score = settings.mode === 'quality' ? f * f : f;
180
+ const basis = basisOf(model);
181
+ why.push(`fit ${f.toFixed(2)}${basis === 'untested' ? ' (untested scores)' : basis === 'estimated' ? ' (estimated scores)' : ''}`);
182
+ // an account with little quota left still qualifies, it just stops being the first pick
183
+ const q = 0.4 + 0.6 * room;
184
+ score *= q;
185
+ // without a known limit, the share is an assumption (see headroom), not a reading
186
+ why.push(usage?.percentUsed === undefined
187
+ ? `no known limit (counted as ${(room * 100).toFixed(0)}% left)`
188
+ : `quota ${(room * 100).toFixed(0)}% left${usage.source === 'measured' ? ' (measured)' : usage.source === 'estimated' ? ' (estimated)' : ''}`);
189
+ const t = timing(usage, room, now);
190
+ score *= t.factor;
191
+ why.push(...t.why);
192
+ // An account that may train on prompts can only take public work, so it gets public work first and
193
+ // the other accounts keep their quota for private work. A known price leaves this to the cost factor.
194
+ if (privacy === 'public' && account.trainsOnData && !account.local && unpriced(model) && settings.mode !== 'quality') {
195
+ score *= PUBLIC_ONLY_BONUS;
196
+ why.push('takes public work only, so it goes first');
197
+ }
198
+ const c = costFactor(model, account, settings.mode, task.type);
199
+ score *= c;
200
+ if (c < 1)
201
+ why.push(`cost x${c.toFixed(2)}`);
202
+ // verdicts saved before versions were recorded still count until the version has its own
203
+ const exact = acceptanceFactor(ctx.stats, statsKey(model), task.type, now);
204
+ const acc = exact.samples || !model.digest ? exact : acceptanceFactor(ctx.stats, model.id, task.type, now);
205
+ score *= acc.factor;
206
+ if (acc.samples)
207
+ why.push(`past results x${acc.factor.toFixed(2)} (${acc.samples} rated)`);
208
+ const size = account.local ? ctx.localSizes?.[`${account.id}/${model.id}`] : undefined;
209
+ if (size && ctx.gpuBytes && size > ctx.gpuBytes) {
210
+ score *= TOO_BIG_FOR_GPU;
211
+ why.push(`about ${Math.round(size / 1024 ** 3)} GB, more than this computer's ${Math.round(ctx.gpuBytes / 1024 ** 3)} GB of GPU memory, so it runs mostly on the processor and slowly`);
212
+ }
213
+ // A fast task prefers models that answered quickly before: the quickest keeps its score and one ten
214
+ // times slower loses about half. Without a typical time, the speed score stands in, a little below
215
+ // the quickest measured model, since a guess should not beat a measurement.
216
+ if (task.fast) {
217
+ const typical = ctx.latency?.[`${account.id}/${model.id}`];
218
+ const known = typical !== undefined && Number.isFinite(fastest);
219
+ score *= known ? 0.5 + 0.5 * Math.min(1, fastest / typical) : 0.5 + 0.05 * Math.min(9, model.skills.speed);
220
+ why.push(known ? `typical ${(typical / 1000).toFixed(typical < 10_000 ? 1 : 0).replace(/\.0$/, '')} s` : 'speed not measured yet');
221
+ }
222
+ if (busy) {
223
+ score *= 0.5;
224
+ why.push('busy, will queue');
225
+ }
226
+ const pinIndex = pins.findIndex((p) => p === account.id || p === `${account.id}/${model.id}`);
227
+ if (pinIndex >= 0) {
228
+ score += 10 - pinIndex;
229
+ why.push('pinned');
230
+ }
231
+ // tiny tie-breaker so the order is stable
232
+ score -= account.priority * 0.0001;
233
+ candidates.push({ accountId: account.id, model: model.id, score, why });
234
+ }
235
+ }
236
+ candidates.sort((a, b) => b.score - a.score);
237
+ return { candidates, rejected };
238
+ }
239
+ /** Health entries for one model sit next to the account entries, keyed "account/model". */
240
+ export function modelHealthKey(accountId, modelId) {
241
+ return `${accountId}/${modelId}`;
242
+ }
243
+ export function splitUse(use) {
244
+ const i = use.indexOf('/');
245
+ return i < 0 ? [use, undefined] : [use.slice(0, i), use.slice(i + 1)];
246
+ }
package/dist/seats.js ADDED
@@ -0,0 +1,119 @@
1
+ // Seats cap how many jobs run on one account at once, across every omnitrix process on this computer.
2
+ // Each running job holds an empty file named `<pid>-<job id>` in the account's folder.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { ownerAlive } from './owner.js';
6
+ import { files, processAlive, readJson, slug } from './store.js';
7
+ const pause = new Int32Array(new SharedArrayBuffer(4));
8
+ // Windows reports a file that is being deleted as EPERM, EBUSY or EACCES rather than EEXIST.
9
+ const BUSY = new Set(['EEXIST', 'EPERM', 'EBUSY', 'EACCES']);
10
+ function remove(file) {
11
+ try {
12
+ fs.rmSync(file, { force: true });
13
+ }
14
+ catch {
15
+ // still held open on Windows; the next pass cleans it up
16
+ }
17
+ }
18
+ /**
19
+ * Counting the seats and taking one must happen as one step, or two processes could both see a free
20
+ * seat. A lock file made with an exclusive create gives that; it is held only for a few file operations.
21
+ * After 10 tries (about 100 ms) this gives up and the caller tries again on its next pass.
22
+ */
23
+ function withLock(dir, fn) {
24
+ const lock = path.join(dir, '.lock');
25
+ const mark = `${process.pid}-${Math.random().toString(36).slice(2)}`;
26
+ for (let attempt = 0; attempt < 10; attempt++) {
27
+ try {
28
+ fs.writeFileSync(lock, mark, { flag: 'wx' });
29
+ }
30
+ catch (err) {
31
+ if (!BUSY.has(err.code ?? ''))
32
+ return undefined;
33
+ breakIfStale(lock);
34
+ Atomics.wait(pause, 0, 0, 10);
35
+ continue;
36
+ }
37
+ try {
38
+ return fn();
39
+ }
40
+ finally {
41
+ // only remove our own lock; if ours was broken as stale, the file now belongs to someone else
42
+ try {
43
+ if (fs.readFileSync(lock, 'utf8') === mark)
44
+ remove(lock);
45
+ }
46
+ catch {
47
+ // already gone
48
+ }
49
+ }
50
+ }
51
+ return undefined;
52
+ }
53
+ /**
54
+ * A lock this old means its holder crashed or hung. A younger one may still be mid-write, with no pid
55
+ * in it yet, so it is never broken. The age is checked again right before removing, so a fresh lock
56
+ * that replaced the stale one in between is left alone.
57
+ */
58
+ function breakIfStale(lock) {
59
+ try {
60
+ const age = Date.now() - fs.statSync(lock).mtimeMs;
61
+ const holder = Number(fs.readFileSync(lock, 'utf8').split('-')[0]);
62
+ if (age <= 2000 || (processAlive(holder) && age <= 10_000))
63
+ return;
64
+ if (Date.now() - fs.statSync(lock).mtimeMs > 2000)
65
+ remove(lock);
66
+ }
67
+ catch {
68
+ // released meanwhile
69
+ }
70
+ }
71
+ /**
72
+ * A seat still counts while its process is alive and its job has not moved on. Checking the job record
73
+ * as well frees a seat whose pid was reused by an unrelated process.
74
+ */
75
+ function seatHeld(name) {
76
+ const dash = name.indexOf('-');
77
+ const pid = Number(name.slice(0, dash));
78
+ if (!processAlive(pid))
79
+ return false;
80
+ const job = readJson(path.join(files.jobs(), `${name.slice(dash + 1)}.json`), null);
81
+ if (!job)
82
+ return true;
83
+ return job.pid === pid && ownerAlive(job.owner, job.pid) && (job.status === 'queued' || job.status === 'running');
84
+ }
85
+ /** Returns the seat to pass to freeSeat, or undefined when the account is full (or the lock is busy). */
86
+ export function takeSeat(accountId, limit, jobId) {
87
+ const dir = path.join(files.seats(), slug(accountId));
88
+ try {
89
+ fs.mkdirSync(dir, { recursive: true });
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ try {
95
+ return withLock(dir, () => {
96
+ let taken = 0;
97
+ for (const name of fs.readdirSync(dir)) {
98
+ if (name === '.lock')
99
+ continue;
100
+ if (seatHeld(name))
101
+ taken++;
102
+ else
103
+ remove(path.join(dir, name));
104
+ }
105
+ if (taken >= limit)
106
+ return undefined;
107
+ const seat = path.join(dir, `${process.pid}-${jobId}`);
108
+ fs.writeFileSync(seat, '');
109
+ return seat;
110
+ });
111
+ }
112
+ catch {
113
+ return undefined;
114
+ }
115
+ }
116
+ export function freeSeat(seat) {
117
+ if (seat)
118
+ remove(seat);
119
+ }
package/dist/stats.js ADDED
@@ -0,0 +1,47 @@
1
+ import { files, readJson, withLock, writeJson } from './store.js';
2
+ const HALF_LIFE = 30 * 24 * 3600_000;
3
+ function key(model, type) {
4
+ return `${model}|${type}`;
5
+ }
6
+ function decay(cell, now) {
7
+ const f = Math.pow(0.5, (now - cell.at) / HALF_LIFE);
8
+ return { ok: cell.ok * f, bad: cell.bad * f, at: now };
9
+ }
10
+ export function loadStats() {
11
+ return readJson(files.stats(), {});
12
+ }
13
+ /** Count a verdict. With `changed`, the job's earlier opposite verdict is taken back first. */
14
+ export function recordVerdict(model, type, accepted, now = Date.now(), changed = false) {
15
+ withLock(files.stats(), () => countVerdict(model, type, accepted, now, changed));
16
+ }
17
+ function countVerdict(model, type, accepted, now, changed) {
18
+ const all = loadStats();
19
+ const k = key(model, type);
20
+ const cell = decay(all[k] ?? { ok: 0, bad: 0, at: now }, now);
21
+ if (changed) {
22
+ if (accepted)
23
+ cell.bad = Math.max(0, cell.bad - 1);
24
+ else
25
+ cell.ok = Math.max(0, cell.ok - 1);
26
+ }
27
+ if (accepted)
28
+ cell.ok += 1;
29
+ else
30
+ cell.bad += 1;
31
+ all[k] = cell;
32
+ writeJson(files.stats(), all);
33
+ }
34
+ /**
35
+ * Multiplier between 0.6 and 1.4.
36
+ * With no data it is 1.0. Two prior "virtual" results keep one lucky run from deciding everything.
37
+ */
38
+ export function acceptanceFactor(stats, model, type, now = Date.now()) {
39
+ const raw = stats[key(model, type)];
40
+ if (!raw)
41
+ return { factor: 1, samples: 0 };
42
+ const c = decay(raw, now);
43
+ const rate = (c.ok + 1) / (c.ok + c.bad + 2);
44
+ // rate 0.5 (no signal) -> 1.0; all accepted -> up to 1.4; all rejected -> down to 0.6
45
+ const factor = Math.min(1.4, Math.max(0.6, 0.5 + rate));
46
+ return { factor, samples: Math.round(c.ok + c.bad) };
47
+ }