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/dist/team.js ADDED
@@ -0,0 +1,406 @@
1
+ // Team mode: a company shares its API accounts, prices and budgets through one file that every developer
2
+ // joins. Keys never appear in the file; each account names the environment variable that holds the key on
3
+ // every developer's machine. Personal subscriptions (ChatGPT Plus, Claude Pro) cannot be shared this way.
4
+ //
5
+ // The file and the shared folder sit where colleagues can edit them, so both are treated as untrusted:
6
+ // the file is pinned to the contents a developer reviewed, and records from the folder are checked one by one.
7
+ import { createHash } from 'node:crypto';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { makeModel } from './models.js';
11
+ import { getProvider, PROVIDERS } from './providers.js';
12
+ const ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
13
+ const ENV = /^[A-Z_][A-Z0-9_]{0,63}$/;
14
+ const MODEL = /^[\w.:/@-]{1,120}$/;
15
+ const USER = /^[\w.@+-]{1,80}$/;
16
+ // a key in the file would be readable by everyone who can read the file
17
+ const SECRET_FIELD = /^(api[_-]?key|key|secret|token|password|authorization)$/i;
18
+ // Variables that hold credentials for something other than an AI provider. A team file naming one would
19
+ // make every developer send that secret to the account's server as if it were an API key.
20
+ const NOT_AI_KEY = /^(AWS_|AZURE_|GOOGLE_APPLICATION_CREDENTIALS$|GH_TOKEN$|GITHUB_|GITLAB_|NPM_TOKEN$|DOCKER_|SSH_|PATH$|HOME$|USERPROFILE$|APPDATA$|TEMP$|TMP$)|PASSWORD|PASSWD/;
21
+ // The variables omnitrix itself suggests for personal keys; a team should use names of its own.
22
+ const PERSONAL_KEYS = new Set(PROVIDERS.map((p) => p.keyEnv).filter((k) => !!k));
23
+ // letters, digits, spaces and common punctuation; no control or direction characters
24
+ const TEXT = /^[^\p{Cc}\p{Cf}\u2028\u2029]{1,80}$/u;
25
+ const MAX_SHARED_BYTES = 10 * 1024 * 1024;
26
+ function fail(where, message) {
27
+ throw new Error(`team file: ${where}: ${message}`);
28
+ }
29
+ function money(where, name, v) {
30
+ if (v === undefined)
31
+ return undefined;
32
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0)
33
+ fail(where, `${name} must be a number of US dollars, 0 or more`);
34
+ return v;
35
+ }
36
+ function budget(where, v) {
37
+ if (v === undefined)
38
+ return {};
39
+ if (typeof v !== 'object' || v === null)
40
+ fail(where, 'must be an object');
41
+ const b = v;
42
+ return { usdPerDay: money(where, 'usdPerDay', b.usdPerDay), usdPerMonth: money(where, 'usdPerMonth', b.usdPerMonth) };
43
+ }
44
+ function httpsUrl(where, v) {
45
+ let u;
46
+ try {
47
+ u = new URL(String(v));
48
+ }
49
+ catch {
50
+ fail(where, 'baseUrl must be a valid https:// address');
51
+ }
52
+ if (typeof v !== 'string' || u.protocol !== 'https:' || !u.hostname)
53
+ fail(where, 'baseUrl must be a valid https:// address');
54
+ return v;
55
+ }
56
+ /** The host a provider is reached at by default, or undefined for custom providers. */
57
+ export function officialHost(provider) {
58
+ const url = getProvider(provider)?.baseUrl;
59
+ return url ? new URL(url).host : undefined;
60
+ }
61
+ /** Parse and check a team file. Throws a message that says exactly what to fix. */
62
+ export function parseTeam(text) {
63
+ let raw;
64
+ try {
65
+ raw = JSON.parse(text);
66
+ }
67
+ catch {
68
+ fail('file', 'is not valid JSON');
69
+ }
70
+ if (typeof raw !== 'object' || raw === null)
71
+ fail('file', 'must be a JSON object');
72
+ const t = raw;
73
+ if (t.version !== 1)
74
+ fail('version', 'must be 1');
75
+ if (typeof t.name !== 'string' || !TEXT.test(t.name.trim()))
76
+ fail('name', 'must be a short text without control characters');
77
+ if (!Array.isArray(t.accounts) || !t.accounts.length)
78
+ fail('accounts', 'must list at least one account');
79
+ const seen = new Set();
80
+ const accounts = t.accounts.map((v, i) => {
81
+ const where = `accounts[${i}]`;
82
+ if (typeof v !== 'object' || v === null)
83
+ fail(where, 'must be an object');
84
+ const a = v;
85
+ for (const [k, val] of Object.entries(a))
86
+ if (SECRET_FIELD.test(k) && val !== undefined)
87
+ fail(where, `"${k}": keys must never be in the team file; name the environment variable in "keyEnv" instead`);
88
+ if (typeof a.id !== 'string' || !ID.test(a.id))
89
+ fail(where, 'id must be lower-case letters, digits and dashes');
90
+ if (seen.has(a.id))
91
+ fail(where, `id "${a.id}" is used twice`);
92
+ seen.add(a.id);
93
+ const spec = typeof a.provider === 'string' ? getProvider(a.provider) : undefined;
94
+ if (!spec)
95
+ fail(where, `unknown provider "${String(a.provider)}"`);
96
+ if (spec.driver === 'cli')
97
+ fail(where, `${spec.id} is a personal subscription and cannot be shared; only API accounts can be team accounts`);
98
+ if (spec.local)
99
+ fail(where, `${spec.id} is a local model server, which each developer runs on their own machine`);
100
+ if (typeof a.keyEnv !== 'string' || !ENV.test(a.keyEnv))
101
+ fail(where, 'keyEnv must name an environment variable, such as ACME_OPENAI_KEY');
102
+ if (NOT_AI_KEY.test(a.keyEnv))
103
+ fail(where, `${a.keyEnv} holds a credential that is not an AI provider key`);
104
+ let baseUrl;
105
+ if (a.baseUrl !== undefined)
106
+ baseUrl = httpsUrl(where, a.baseUrl);
107
+ else if (!spec.baseUrl)
108
+ fail(where, `baseUrl is required for ${spec.id}`);
109
+ const host = new URL(baseUrl ?? spec.baseUrl).host;
110
+ if (PERSONAL_KEYS.has(a.keyEnv) && host !== officialHost(spec.id))
111
+ fail(where, `${a.keyEnv} usually holds a personal key and must not be sent to ${host}; use a company variable name such as ACME_${a.keyEnv}`);
112
+ if (!Array.isArray(a.models) || !a.models.length || !a.models.every((m) => typeof m === 'string' && MODEL.test(m)))
113
+ fail(where, 'models must list at least one model id');
114
+ if (a.label !== undefined && (typeof a.label !== 'string' || !TEXT.test(a.label)))
115
+ fail(where, 'label must be a short text without control characters');
116
+ if (a.concurrency !== undefined && (!Number.isInteger(a.concurrency) || a.concurrency < 1 || a.concurrency > 32))
117
+ fail(where, 'concurrency must be a whole number from 1 to 32');
118
+ if (a.trainsOnData !== undefined && typeof a.trainsOnData !== 'boolean')
119
+ fail(where, 'trainsOnData must be true or false');
120
+ // private work goes only to providers that do not train on it; a shared file may not loosen that
121
+ if (a.trainsOnData === false && spec.trainsOnData)
122
+ fail(where, `${spec.id} may train on prompts, and a team file cannot mark it as safe for private work`);
123
+ if (a.limits !== undefined && (typeof a.limits !== 'object' || a.limits === null || !Object.values(a.limits).every((n) => Number.isInteger(n) && n > 0)))
124
+ fail(where, 'limits must hold whole numbers above 0');
125
+ return {
126
+ id: a.id, provider: spec.id, label: a.label, keyEnv: a.keyEnv, baseUrl,
127
+ models: a.models, limits: a.limits, concurrency: a.concurrency,
128
+ trainsOnData: a.trainsOnData, usdPerDay: money(where, 'usdPerDay', a.usdPerDay), usdPerMonth: money(where, 'usdPerMonth', a.usdPerMonth),
129
+ };
130
+ });
131
+ // maps without a prototype, so a model or person named "__proto__" or "constructor" is just a name
132
+ const prices = Object.create(null);
133
+ if (t.prices !== undefined) {
134
+ if (typeof t.prices !== 'object' || t.prices === null)
135
+ fail('prices', 'must be an object of model ids');
136
+ for (const [model, p] of Object.entries(t.prices)) {
137
+ const where = `prices.${model}`;
138
+ if (typeof p !== 'object' || p === null)
139
+ fail(where, 'must hold "input" and "output"');
140
+ const q = p;
141
+ prices[model] = { input: money(where, 'input', q.input) ?? fail(where, 'input is missing'), output: money(where, 'output', q.output) ?? fail(where, 'output is missing') };
142
+ }
143
+ }
144
+ let budgets;
145
+ if (t.budgets !== undefined) {
146
+ const b = budget('budgets', t.budgets);
147
+ const people = Object.create(null);
148
+ const raw = t.budgets.people;
149
+ if (raw !== undefined) {
150
+ if (typeof raw !== 'object' || raw === null)
151
+ fail('budgets.people', 'must be an object of names');
152
+ for (const [person, pb] of Object.entries(raw))
153
+ people[person] = budget(`budgets.people.${person}`, pb);
154
+ }
155
+ budgets = { ...b, people };
156
+ }
157
+ if (t.auditDir !== undefined && (typeof t.auditDir !== 'string' || !path.isAbsolute(t.auditDir)))
158
+ fail('auditDir', 'must be an absolute path to a shared folder');
159
+ return { version: 1, name: t.name.trim(), accounts, prices, budgets, auditDir: t.auditDir };
160
+ }
161
+ export function fingerprint(text) {
162
+ return createHash('sha256').update(text).digest('hex');
163
+ }
164
+ /** The short form of the fingerprint that `team join` shows and asks for. */
165
+ export function reviewCode(text) {
166
+ return fingerprint(text).slice(0, 8);
167
+ }
168
+ /** Models listed for an account that the file gives no price for; their requests count as costing nothing. */
169
+ export function unpricedModels(team) {
170
+ return [...new Set(team.accounts.flatMap((a) => a.models))].filter((m) => !Object.hasOwn(team.prices, m));
171
+ }
172
+ /** The team's accounts as omnitrix accounts. They are rebuilt from the file on every load and never saved locally. */
173
+ export function teamAccounts(team) {
174
+ return team.accounts.map((a, i) => {
175
+ const spec = getProvider(a.provider);
176
+ const price = (id) => {
177
+ const p = Object.hasOwn(team.prices, id) ? team.prices[id] : undefined;
178
+ return p ? { inputPrice: p.input, outputPrice: p.output } : {};
179
+ };
180
+ return {
181
+ id: a.id,
182
+ label: a.label ?? `${team.name} ${spec.name}`,
183
+ owner: team.name,
184
+ provider: spec.id,
185
+ driver: spec.driver,
186
+ baseUrl: a.baseUrl ?? spec.baseUrl,
187
+ apiKey: `env:${a.keyEnv}`,
188
+ models: a.models.map((m) => makeModel(m, price(m))),
189
+ limits: a.limits ?? spec.limits ?? {},
190
+ concurrency: a.concurrency ?? 2,
191
+ enabled: true,
192
+ trainsOnData: a.trainsOnData ?? !!spec.trainsOnData,
193
+ local: false,
194
+ // after the developer's own accounts when scores tie
195
+ priority: 1000 + i,
196
+ addedAt: 'team',
197
+ team: true,
198
+ };
199
+ });
200
+ }
201
+ /** A person's own budget overrides the team's, field by field. */
202
+ export function budgetFor(team, user) {
203
+ const own = team.budgets && Object.hasOwn(team.budgets.people, user) ? team.budgets.people[user] : undefined;
204
+ const day = own?.usdPerDay ?? team.budgets?.usdPerDay;
205
+ const month = own?.usdPerMonth ?? team.budgets?.usdPerMonth;
206
+ return { ...(day !== undefined ? { day } : {}), ...(month !== undefined ? { month } : {}) };
207
+ }
208
+ /** US dollars for a request, from the model's price per million tokens; undefined when no price is known. */
209
+ export function estimateCost(model, inputTokens, outputTokens) {
210
+ if (!model || (model.inputPrice === undefined && model.outputPrice === undefined))
211
+ return undefined;
212
+ return (inputTokens * (model.inputPrice ?? 0) + outputTokens * (model.outputPrice ?? 0)) / 1_000_000;
213
+ }
214
+ let cache;
215
+ // a team file on a network share is looked at no more than this often, so a slow share cannot stall routing
216
+ const RECHECK_MS = 5_000;
217
+ function copy(state) {
218
+ // callers change accounts (a test points one at a mock, dropModel trims models); the cached copy must not change
219
+ return { ...state, accounts: structuredClone(state.accounts) };
220
+ }
221
+ /**
222
+ * Load the team file the developer joined. Its accounts load only while the file still has the exact
223
+ * contents that were reviewed at join: anyone who can edit a shared file could otherwise point an account
224
+ * at their own server and collect the keys.
225
+ */
226
+ export function loadTeam(membership) {
227
+ const now = Date.now();
228
+ const same = cache && cache.key.startsWith(`${membership.file}|${membership.sha256}|`);
229
+ if (same && now - cache.checkedAt < RECHECK_MS)
230
+ return copy(cache.state);
231
+ let stat;
232
+ try {
233
+ stat = fs.statSync(membership.file);
234
+ }
235
+ catch {
236
+ // not cached: a share that comes back is picked up at the next look
237
+ return { membership, accounts: [], error: `the team file ${membership.file} cannot be read` };
238
+ }
239
+ const key = `${membership.file}|${membership.sha256}|${stat.size}|${stat.mtimeMs}`;
240
+ if (cache?.key === key) {
241
+ cache.checkedAt = now;
242
+ return copy(cache.state);
243
+ }
244
+ let text;
245
+ try {
246
+ text = fs.readFileSync(membership.file, 'utf8');
247
+ }
248
+ catch {
249
+ return { membership, accounts: [], error: `the team file ${membership.file} cannot be read` };
250
+ }
251
+ let state;
252
+ if (fingerprint(text) !== membership.sha256) {
253
+ state = { membership, accounts: [], error: `the team file has changed since you joined; run "omnitrix team join ${membership.file}" to review it again` };
254
+ }
255
+ else {
256
+ try {
257
+ const team = parseTeam(text);
258
+ state = { membership, team, accounts: teamAccounts(team) };
259
+ }
260
+ catch (err) {
261
+ state = { membership, accounts: [], error: err instanceof Error ? err.message : String(err) };
262
+ }
263
+ }
264
+ cache = { key, checkedAt: now, state };
265
+ return copy(state);
266
+ }
267
+ const usd = (v) => `$${v.toFixed(2)}`;
268
+ /** A cost that counts: a finite amount of 0 or more. Anything else in a record is ignored. */
269
+ function cost(r) {
270
+ return typeof r.costUsd === 'number' && Number.isFinite(r.costUsd) && r.costUsd >= 0 ? r.costUsd : 0;
271
+ }
272
+ /** Spending in US dollars since `from`, for the records that match. */
273
+ export function spent(records, from, match) {
274
+ let total = 0;
275
+ for (const r of records)
276
+ if (r.ts >= from && match(r))
277
+ total += cost(r);
278
+ return total;
279
+ }
280
+ /** Start of the local calendar day or month. */
281
+ export function periodStart(now, period) {
282
+ const d = new Date(now);
283
+ return (period === 'day' ? new Date(d.getFullYear(), d.getMonth(), d.getDate()) : new Date(d.getFullYear(), d.getMonth(), 1)).getTime();
284
+ }
285
+ /** The person's team spending today and this month, from their own records. */
286
+ export function personSpend(team, user, records, now = Date.now()) {
287
+ const mine = (r) => r.team === team.name && r.user === user;
288
+ return { day: spent(records, periodStart(now, 'day'), mine), month: spent(records, periodStart(now, 'month'), mine) };
289
+ }
290
+ /**
291
+ * Which team accounts are out of budget, and why. A person's budget counts their own spending on this
292
+ * machine; an account's limit counts everyone's records from the shared folder (or only the person's own
293
+ * when there is none). Requests still running count with their estimated cost.
294
+ */
295
+ export function budgetBlocks(team, user, own, everyone, now = Date.now(), reserved = {}) {
296
+ const blocked = {};
297
+ const b = budgetFor(team, user);
298
+ const s = personSpend(team, user, own, now);
299
+ const running = Object.values(reserved).reduce((x, y) => x + y, 0);
300
+ const day = s.day + running;
301
+ const month = s.month + running;
302
+ const personal = b.day !== undefined && day >= b.day ? `your ${team.name} budget for today is used up (${usd(day)} of ${usd(b.day)})`
303
+ : b.month !== undefined && month >= b.month ? `your ${team.name} budget for this month is used up (${usd(month)} of ${usd(b.month)})` : undefined;
304
+ for (const a of team.accounts) {
305
+ if (personal) {
306
+ blocked[a.id] = personal;
307
+ continue;
308
+ }
309
+ const on = (r) => r.accountId === a.id && r.team === team.name;
310
+ const extra = reserved[a.id] ?? 0;
311
+ const aDay = spent(everyone, periodStart(now, 'day'), on) + extra;
312
+ const aMonth = spent(everyone, periodStart(now, 'month'), on) + extra;
313
+ if (a.usdPerDay !== undefined && aDay >= a.usdPerDay)
314
+ blocked[a.id] = `the team's daily limit for this account is used up (${usd(aDay)} of ${usd(a.usdPerDay)})`;
315
+ else if (a.usdPerMonth !== undefined && aMonth >= a.usdPerMonth)
316
+ blocked[a.id] = `the team's monthly limit for this account is used up (${usd(aMonth)} of ${usd(a.usdPerMonth)})`;
317
+ }
318
+ return blocked;
319
+ }
320
+ /** One file per person, so developers never write to the same file at the same time. */
321
+ function personName(user) {
322
+ return user.replace(/[^\w.@-]+/g, '_').slice(0, 80) || 'unknown';
323
+ }
324
+ /** Copy a team record to the shared folder. A shared folder that is not reachable must never fail a job. */
325
+ export function shareRecord(auditDir, user, rec) {
326
+ try {
327
+ fs.mkdirSync(auditDir, { recursive: true });
328
+ const file = path.join(auditDir, `${personName(user)}.jsonl`);
329
+ // never write through a link a colleague put in place of the file
330
+ try {
331
+ if (fs.lstatSync(file).isSymbolicLink())
332
+ return;
333
+ }
334
+ catch {
335
+ // no file yet
336
+ }
337
+ const flags = fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | (process.platform === 'win32' ? 0 : fs.constants.O_NOFOLLOW);
338
+ const fd = fs.openSync(file, flags, 0o644);
339
+ try {
340
+ // the leading newline ends a line that another machine left half written, so this record stays whole
341
+ fs.writeSync(fd, '\n' + JSON.stringify(rec) + '\n');
342
+ }
343
+ finally {
344
+ fs.closeSync(fd);
345
+ }
346
+ }
347
+ catch {
348
+ // the local ledger still has it
349
+ }
350
+ }
351
+ const int = (v) => typeof v === 'number' && Number.isInteger(v) && v >= 0;
352
+ /** A record from the shared folder that is well formed and belongs to the file it was found in. */
353
+ function trusted(r, owner, now) {
354
+ if (typeof r !== 'object' || r === null)
355
+ return false;
356
+ const x = r;
357
+ return typeof x.ts === 'number' && Number.isFinite(x.ts) && x.ts <= now + 5 * 60_000
358
+ && typeof x.accountId === 'string' && ID.test(x.accountId)
359
+ && typeof x.model === 'string' && MODEL.test(x.model)
360
+ && typeof x.user === 'string' && USER.test(x.user) && personName(x.user) === owner
361
+ && typeof x.team === 'string' && TEXT.test(x.team)
362
+ && int(x.inputTokens) && int(x.outputTokens) && typeof x.ok === 'boolean'
363
+ && (x.costUsd === undefined || (typeof x.costUsd === 'number' && Number.isFinite(x.costUsd) && x.costUsd >= 0));
364
+ }
365
+ /**
366
+ * Every well-formed record in the shared folder since `from`. Colleagues can write there, so links,
367
+ * folders, oversized files and records that do not belong to their file are skipped.
368
+ */
369
+ export function readShared(auditDir, from = 0) {
370
+ const out = [];
371
+ const now = Date.now();
372
+ let names = [];
373
+ try {
374
+ names = fs.readdirSync(auditDir).filter((n) => n.endsWith('.jsonl'));
375
+ }
376
+ catch {
377
+ return out;
378
+ }
379
+ for (const n of names) {
380
+ const file = path.join(auditDir, n);
381
+ let raw = '';
382
+ try {
383
+ const st = fs.lstatSync(file);
384
+ if (!st.isFile() || st.size > MAX_SHARED_BYTES || st.mtimeMs < from)
385
+ continue;
386
+ raw = fs.readFileSync(file, 'utf8');
387
+ }
388
+ catch {
389
+ continue;
390
+ }
391
+ const owner = n.slice(0, -'.jsonl'.length);
392
+ for (const line of raw.split('\n')) {
393
+ if (!line)
394
+ continue;
395
+ try {
396
+ const r = JSON.parse(line);
397
+ if (trusted(r, owner, now) && r.ts >= from)
398
+ out.push(r);
399
+ }
400
+ catch {
401
+ // a half-written line from a machine that is still writing
402
+ }
403
+ }
404
+ }
405
+ return out;
406
+ }
package/dist/types.js ADDED
@@ -0,0 +1,24 @@
1
+ /** What a piece of work is about. The router uses this to pick a model. */
2
+ export const TASK_TYPES = [
3
+ 'code', // edit files in a repo (needs an agent CLI: codex, claude, qwen...)
4
+ 'code_snippet', // write code as text, no repo access
5
+ 'review', // check someone else's work
6
+ 'reasoning', // hard thinking, planning, math, debugging logic
7
+ 'long_context', // read a lot of input and answer about it
8
+ 'bulk', // cheap work: summarize, translate, extract, format
9
+ 'writing', // docs, prose, messages
10
+ 'vision', // the input includes images
11
+ ];
12
+ export const EFFORTS = ['low', 'medium', 'high'];
13
+ export class DriverError extends Error {
14
+ kind;
15
+ status;
16
+ retryAfterMs;
17
+ constructor(message, kind, status, retryAfterMs) {
18
+ super(message);
19
+ this.kind = kind;
20
+ this.status = status;
21
+ this.retryAfterMs = retryAfterMs;
22
+ this.name = 'DriverError';
23
+ }
24
+ }