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.
@@ -0,0 +1,76 @@
1
+ import { loadQuotas } from './quota.js';
2
+ import { loadConfig, loadHealth } from './store.js';
3
+ import { headroom, readLedger, summarize } from './usage.js';
4
+ /**
5
+ * Claude Code runs this often, so it must be fast and must never throw.
6
+ * It reads files only; it never calls a provider.
7
+ */
8
+ export function renderStatusLine(stdinJson, now = Date.now()) {
9
+ const parts = [];
10
+ try {
11
+ const cfg = loadConfig();
12
+ const health = loadHealth();
13
+ const records = readLedger(now - 32 * 24 * 3600_000);
14
+ const quotas = loadQuotas();
15
+ const accounts = cfg.accounts.filter((a) => a.enabled);
16
+ // grouped once, so each account reads only its own records
17
+ const byAccount = new Map();
18
+ for (const r of records) {
19
+ const list = byAccount.get(r.accountId);
20
+ if (list)
21
+ list.push(r);
22
+ else
23
+ byAccount.set(r.accountId, [r]);
24
+ }
25
+ if (accounts.length) {
26
+ let ready = 0;
27
+ const shown = [];
28
+ for (const a of accounts) {
29
+ const h = health[a.id];
30
+ const blocked = h && (h.state === 'auth_error' || ((h.state === 'cooling' || h.state === 'exhausted' || h.state === 'offline') && (h.until ?? 0) > now));
31
+ const s = summarize(a, byAccount.get(a.id) ?? [], h, now, quotas[a.id]);
32
+ // the router's own test, so the line never calls ready an account the router skips
33
+ const full = headroom(s) <= 0;
34
+ if (!blocked && !full)
35
+ ready++;
36
+ let tag;
37
+ if (blocked)
38
+ tag = h.state === 'auth_error' ? 'login?' : h.state === 'offline' ? 'off' : 'wait';
39
+ else if (s.measured?.remainingRequests !== undefined)
40
+ tag = `${s.measured.remainingRequests} left`;
41
+ else if (s.percentUsed !== undefined)
42
+ tag = `${100 - s.percentUsed}%`;
43
+ else
44
+ tag = `${s.requestsToday}req`;
45
+ shown.push(`${a.id} ${tag}`);
46
+ }
47
+ const max = 4;
48
+ parts.push(`omnitrix ${ready}/${accounts.length} ready · ${shown.slice(0, max).join(' · ')}${shown.length > max ? ` +${shown.length - max}` : ''}`);
49
+ }
50
+ else {
51
+ parts.push('omnitrix: no accounts (omnitrix add)');
52
+ }
53
+ }
54
+ catch {
55
+ parts.push('omnitrix: ?');
56
+ }
57
+ // Claude's own plan usage, which Claude Code passes on stdin (Pro/Max/Ultra only).
58
+ try {
59
+ if (stdinJson.trim()) {
60
+ const j = JSON.parse(stdinJson);
61
+ const five = j?.rate_limits?.five_hour?.used_percentage;
62
+ const week = j?.rate_limits?.seven_day?.used_percentage;
63
+ const bits = [];
64
+ if (typeof five === 'number')
65
+ bits.push(`5h ${Math.round(five)}%`);
66
+ if (typeof week === 'number')
67
+ bits.push(`7d ${Math.round(week)}%`);
68
+ if (bits.length)
69
+ parts.push(`Claude ${bits.join(' ')}`);
70
+ }
71
+ }
72
+ catch {
73
+ /* not JSON; ignore */
74
+ }
75
+ return parts.join(' │ ');
76
+ }
package/dist/store.js ADDED
@@ -0,0 +1,303 @@
1
+ // Everything omnitrix keeps lives in one folder, ~/.omnitrix unless OMNITRIX_HOME says otherwise.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { loadTeam } from './team.js';
6
+ export function homeDir() {
7
+ return process.env.OMNITRIX_HOME || path.join(os.homedir(), '.omnitrix');
8
+ }
9
+ export const files = {
10
+ config: () => path.join(homeDir(), 'config.json'),
11
+ secrets: () => path.join(homeDir(), 'secrets.json'),
12
+ ledger: () => path.join(homeDir(), 'usage.jsonl'),
13
+ health: () => path.join(homeDir(), 'health.json'),
14
+ quota: () => path.join(homeDir(), 'quota.json'),
15
+ stats: () => path.join(homeDir(), 'stats.json'),
16
+ jobs: () => path.join(homeDir(), 'jobs'),
17
+ outputs: () => path.join(homeDir(), 'outputs'),
18
+ profiles: () => path.join(homeDir(), 'profiles'),
19
+ worktrees: () => path.join(homeDir(), 'worktrees'),
20
+ seats: () => path.join(homeDir(), 'seats'),
21
+ owners: () => path.join(homeDir(), 'owners'),
22
+ };
23
+ /** What job ids look like (see newId in engine.ts). Anything else could name a file outside the jobs folder. */
24
+ export const JOB_ID = /^j[0-9a-z]{4,40}$/;
25
+ /** A path with links followed as far as it exists; the missing rest is added back unchanged. */
26
+ function realish(p) {
27
+ const full = path.resolve(p);
28
+ try {
29
+ return fs.realpathSync.native(full);
30
+ }
31
+ catch {
32
+ const up = path.dirname(full);
33
+ return up === full ? full : path.join(realish(up), path.basename(full));
34
+ }
35
+ }
36
+ /** True when `child` is `parent` or inside it, after following links as far as each path exists. */
37
+ export function inside(child, parent) {
38
+ try {
39
+ const c = realish(child);
40
+ const p = realish(parent);
41
+ const rel = path.relative(p, c);
42
+ return rel === '' || (!!rel && !rel.startsWith('..') && !path.isAbsolute(rel));
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
48
+ export function processAlive(pid) {
49
+ if (!pid || !Number.isFinite(pid))
50
+ return false;
51
+ if (pid === process.pid)
52
+ return true;
53
+ try {
54
+ process.kill(pid, 0); // signal 0 only checks that the process exists
55
+ return true;
56
+ }
57
+ catch (err) {
58
+ // EPERM means it exists but belongs to someone else
59
+ return err.code === 'EPERM';
60
+ }
61
+ }
62
+ export const defaultSettings = {
63
+ protectPrivate: true,
64
+ resultPreviewChars: 1500,
65
+ jobTimeoutSec: 900,
66
+ mode: 'balanced',
67
+ bannedProviders: [],
68
+ pins: {},
69
+ };
70
+ export function ensureHome() {
71
+ for (const dir of [homeDir(), files.jobs(), files.outputs(), files.profiles(), files.worktrees()]) {
72
+ // keys, prompts and results live here; on macOS and Linux only the owner may read them
73
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
74
+ }
75
+ // a folder made by an older version keeps its old permissions unless they are tightened
76
+ if (process.platform !== 'win32')
77
+ fs.chmodSync(homeDir(), 0o700);
78
+ }
79
+ const pause = new Int32Array(new SharedArrayBuffer(4));
80
+ // A lock that names no readable process and is older than this was left half-written by a crash.
81
+ const STALE_LOCK_MS = 10_000;
82
+ // After this long, the change goes ahead without the lock rather than hang the caller.
83
+ const LOCK_WAIT_MS = 5_000;
84
+ /** True when a lock was left by a process that is gone, so it can be taken over at once. */
85
+ function abandoned(lock) {
86
+ let text;
87
+ try {
88
+ text = fs.readFileSync(lock, 'utf8');
89
+ }
90
+ catch {
91
+ return false; // gone already, or being replaced
92
+ }
93
+ const pid = Number(text.split(' ')[0]);
94
+ if (Number.isInteger(pid) && pid > 0)
95
+ return !processAlive(pid);
96
+ try {
97
+ return Date.now() - fs.statSync(lock).mtimeMs > STALE_LOCK_MS;
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ }
103
+ /**
104
+ * Run `fn` while holding a lock file beside `file`. Several omnitrix processes change the same files
105
+ * (verdicts, account health, quota readings, keys) by reading, changing and writing them; without the
106
+ * lock, one process's write silently replaces another's.
107
+ */
108
+ export function withLock(file, fn) {
109
+ const lock = `${file}.lock`;
110
+ fs.mkdirSync(path.dirname(file), { recursive: true });
111
+ const deadline = Date.now() + LOCK_WAIT_MS;
112
+ let fd;
113
+ // the lock names its holder, so a lock left by a crashed process is recognised at once
114
+ const mine = `${process.pid} ${Math.random().toString(36).slice(2)}`;
115
+ while (fd === undefined) {
116
+ try {
117
+ fd = fs.openSync(lock, 'wx');
118
+ fs.writeSync(fd, mine);
119
+ }
120
+ catch (err) {
121
+ const code = err.code;
122
+ // Windows answers EPERM while another process is deleting the lock
123
+ if (code !== 'EEXIST' && code !== 'EPERM')
124
+ throw err;
125
+ // Read again right before deleting: a lock just taken by a live process names that process and stays.
126
+ if (abandoned(lock) && abandoned(lock))
127
+ fs.rmSync(lock, { force: true });
128
+ if (Date.now() > deadline) {
129
+ process.stderr.write(`omnitrix: ${path.basename(file)} stayed locked for ${LOCK_WAIT_MS / 1000} s; changing it without the lock\n`);
130
+ break;
131
+ }
132
+ Atomics.wait(pause, 0, 0, 5);
133
+ }
134
+ }
135
+ try {
136
+ return fn();
137
+ }
138
+ finally {
139
+ if (fd !== undefined) {
140
+ fs.closeSync(fd);
141
+ fs.rmSync(lock, { force: true });
142
+ }
143
+ }
144
+ }
145
+ /** Write to a temp file then rename, so no reader ever sees half a file. */
146
+ export function writeJson(file, data, mode) {
147
+ fs.mkdirSync(path.dirname(file), { recursive: true });
148
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
149
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode });
150
+ // Windows refuses the rename while a virus scanner or indexer has the target open. That clears within
151
+ // moments, so wait and retry. Writing the target in place instead would let other processes read it empty.
152
+ for (let attempt = 1;; attempt++) {
153
+ try {
154
+ fs.renameSync(tmp, file);
155
+ return;
156
+ }
157
+ catch (err) {
158
+ const code = err.code;
159
+ if (attempt >= 20 || (code !== 'EPERM' && code !== 'EBUSY' && code !== 'EACCES')) {
160
+ fs.rmSync(tmp, { force: true });
161
+ throw err;
162
+ }
163
+ Atomics.wait(pause, 0, 0, 25);
164
+ }
165
+ }
166
+ }
167
+ export function readJson(file, fallback) {
168
+ try {
169
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
170
+ }
171
+ catch {
172
+ return fallback;
173
+ }
174
+ }
175
+ export function loadConfig() {
176
+ const cfg = readJson(files.config(), null);
177
+ if (!cfg)
178
+ return { version: 1, accounts: [], settings: { ...defaultSettings } };
179
+ cfg.settings = { ...defaultSettings, ...cfg.settings };
180
+ cfg.accounts ??= [];
181
+ if (cfg.settings.team) {
182
+ // the developer's own account wins when an id is used by both
183
+ const own = new Set(cfg.accounts.map((a) => a.id));
184
+ cfg.accounts.push(...loadTeam(cfg.settings.team).accounts.filter((a) => !own.has(a.id)));
185
+ }
186
+ return cfg;
187
+ }
188
+ export function saveConfig(cfg) {
189
+ ensureHome();
190
+ // team accounts come from the team file on every load; saving them would freeze an old copy here
191
+ writeJson(files.config(), { ...cfg, accounts: cfg.accounts.filter((a) => !a.team) });
192
+ }
193
+ /**
194
+ * Change the configuration under its lock: read the latest copy, apply `change`, save. Every change goes
195
+ * through here, so a command that waited for a provider never writes back a copy that is out of date.
196
+ * `change` must not wait for anything; fetch first, then change.
197
+ */
198
+ export function updateConfig(change) {
199
+ ensureHome();
200
+ return withLock(files.config(), () => {
201
+ const cfg = loadConfig();
202
+ const result = change(cfg);
203
+ saveConfig(cfg);
204
+ return result;
205
+ });
206
+ }
207
+ /** Remove a model the provider no longer serves, so the router stops choosing it. */
208
+ export function dropModel(accountId, modelId) {
209
+ updateConfig((cfg) => {
210
+ const acc = findAccount(cfg, accountId);
211
+ // a team account is rebuilt from the team file on every load; its model rests instead (see the engine)
212
+ if (!acc || acc.team || !acc.models.some((m) => m.id === modelId))
213
+ return;
214
+ acc.models = acc.models.filter((m) => m.id !== modelId);
215
+ });
216
+ }
217
+ export function findAccount(cfg, id) {
218
+ return cfg.accounts.find((a) => a.id === id);
219
+ }
220
+ export function setSecret(accountId, value) {
221
+ ensureHome();
222
+ withLock(files.secrets(), () => {
223
+ const all = readJson(files.secrets(), {});
224
+ all[accountId] = value;
225
+ writeJson(files.secrets(), all, 0o600);
226
+ });
227
+ }
228
+ export function deleteSecret(accountId) {
229
+ withLock(files.secrets(), () => {
230
+ const all = readJson(files.secrets(), {});
231
+ if (accountId in all) {
232
+ delete all[accountId];
233
+ writeJson(files.secrets(), all, 0o600);
234
+ }
235
+ });
236
+ }
237
+ /** Resolve the API key of an account. Never log the return value. */
238
+ export function resolveKey(account) {
239
+ const ref = account.apiKey;
240
+ if (!ref)
241
+ return undefined;
242
+ if (ref.startsWith('env:'))
243
+ return known(process.env[ref.slice(4)] || undefined);
244
+ if (ref === 'secret')
245
+ return known(readJson(files.secrets(), {})[account.id]);
246
+ return undefined;
247
+ }
248
+ // Every key omnitrix has handed to a driver, so redact() can hide it even when it has no familiar prefix.
249
+ const knownKeys = new Set();
250
+ function known(key) {
251
+ if (key && key.length >= 12)
252
+ knownKeys.add(key);
253
+ return key;
254
+ }
255
+ export function loadHealth() {
256
+ return readJson(files.health(), {});
257
+ }
258
+ /** Stamps each entry with the time it was written, so readers can tell which process saw the account last. */
259
+ export function saveHealth(update) {
260
+ withLock(files.health(), () => {
261
+ const now = Date.now();
262
+ const merged = loadHealth();
263
+ for (const [id, h] of Object.entries(update))
264
+ merged[id] = { ...h, at: h.at ?? now };
265
+ // model pauses (keys "account/model") that have run out carry no information, so they are dropped
266
+ for (const [id, h] of Object.entries(merged))
267
+ if (id.includes('/') && h.state === 'cooling' && (h.until ?? 0) <= now)
268
+ delete merged[id];
269
+ writeJson(files.health(), merged);
270
+ });
271
+ }
272
+ export function slug(text) {
273
+ return text
274
+ .toLowerCase()
275
+ .replace(/[^a-z0-9]+/g, '-')
276
+ .replace(/^-+|-+$/g, '')
277
+ .slice(0, 40) || 'account';
278
+ }
279
+ export function uniqueAccountId(cfg, base) {
280
+ const root = slug(base);
281
+ let id = root;
282
+ let n = 2;
283
+ while (findAccount(cfg, id))
284
+ id = `${root}-${n++}`;
285
+ return id;
286
+ }
287
+ /** Hide anything that looks like a secret before it is shown or saved. */
288
+ export function redact(text) {
289
+ let out = text;
290
+ for (const key of knownKeys)
291
+ out = out.split(key).join('***');
292
+ return out
293
+ .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '-----PRIVATE KEY***-----')
294
+ .replace(/\b(ghp|gho|ghu|ghs|ghr|github_pat)_[A-Za-z0-9_]{20,}/g, '$1_***')
295
+ .replace(/\bAKIA[0-9A-Z]{16}\b/g, 'AKIA***')
296
+ .replace(/\b(xox[abprs])-[A-Za-z0-9-]{10,}/g, '$1-***')
297
+ .replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, 'jwt-***')
298
+ .replace(/\bAIza[0-9A-Za-z_-]{30,}/g, 'AIza***')
299
+ .replace(/\bfw_[A-Za-z0-9]{16,}/g, 'fw_***')
300
+ .replace(/\b(sk|pk|rk|gsk|xai|nvapi|hf)[-_][A-Za-z0-9_\-]{12,}/g, '$1-***')
301
+ .replace(/(Bearer\s+)[A-Za-z0-9._\-]{12,}/gi, '$1***')
302
+ .replace(/("?(api[_-]?key|authorization|x-api-key|token)"?\s*[:=]\s*"?)[^"\s,}]{8,}/gi, '$1***');
303
+ }