vectorbench 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,122 @@
1
+ // The owner's Codex account, through `codex app-server` (JSON-RPC over stdio):
2
+ // the plan's usage windows and its earned rate-limit resets, and spending one.
3
+ // The app-server runs with a Codex home of its own that holds only a link to
4
+ // the ChatGPT login, as the drawing runs do (harness/codex.mjs).
5
+ //
6
+ // const limits = await readLimits(); // { rateLimits, rateLimitsByLimitId, rateLimitResetCredits }
7
+ // const outcome = await useReset(); // 'reset' | 'alreadyRedeemed' | 'nothingToReset' | 'noCredit'
8
+
9
+ import { spawn } from 'node:child_process';
10
+ import { randomUUID } from 'node:crypto';
11
+ import { mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
12
+ import { homedir, tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+
15
+ const bin = () => process.env.CODEX_BIN || 'codex';
16
+
17
+ /** Sends one request to a fresh app-server and returns its result. */
18
+ export async function call(method, params, { timeoutMs = 60_000 } = {}) {
19
+ const home = await mkdtemp(join(tmpdir(), 'vb-codex-account-'));
20
+ try {
21
+ await symlink(join(process.env.CODEX_AUTH_HOME || join(homedir(), '.codex'), 'auth.json'), join(home, 'auth.json'));
22
+ await writeFile(join(home, 'config.toml'), 'check_for_update_on_startup = false\n');
23
+ return await new Promise((resolve, reject) => {
24
+ const env = { PATH: process.env.PATH, HOME: process.env.HOME, TERM: 'dumb', CODEX_HOME: home };
25
+ const child = spawn(bin(), ['app-server'], { env, stdio: ['pipe', 'pipe', 'pipe'] });
26
+ const send = (message) => child.stdin.write(`${JSON.stringify(message)}\n`);
27
+ const timer = setTimeout(() => finish(new Error(`codex app-server did not answer ${method} within ${timeoutMs / 1000} s`)), timeoutMs);
28
+ let stderr = '';
29
+ let pending = '';
30
+ let done = false;
31
+ function finish(error, result) {
32
+ if (done) return;
33
+ done = true;
34
+ clearTimeout(timer);
35
+ child.kill('SIGTERM');
36
+ error ? reject(error) : resolve(result);
37
+ }
38
+ child.stderr.on('data', (chunk) => (stderr = (stderr + chunk).slice(-4000)));
39
+ child.on('error', (error) => finish(error));
40
+ child.on('close', (code) => finish(new Error(`codex app-server exited (${code}) before answering ${method}: ${stderr.trim().split('\n').at(-1) ?? ''}`)));
41
+ child.stdout.setEncoding('utf8');
42
+ child.stdout.on('data', (chunk) => {
43
+ pending += chunk;
44
+ let newline;
45
+ while ((newline = pending.indexOf('\n')) >= 0) {
46
+ const line = pending.slice(0, newline);
47
+ pending = pending.slice(newline + 1);
48
+ let message;
49
+ try {
50
+ message = JSON.parse(line);
51
+ } catch {
52
+ continue;
53
+ }
54
+ if (message.id === 0) {
55
+ if (message.error) return finish(new Error(`initialize: ${message.error.message}`));
56
+ send({ method: 'initialized', params: {} });
57
+ send({ method, id: 1, ...(params && { params }) });
58
+ } else if (message.id === 1) {
59
+ if (message.error) return finish(new Error(`${method}: ${message.error.message}`));
60
+ finish(null, message.result);
61
+ }
62
+ }
63
+ });
64
+ send({ method: 'initialize', id: 0, params: { clientInfo: { name: 'vectorbench', title: 'VectorBench drawing runs', version: '1.0.0' } } });
65
+ });
66
+ } finally {
67
+ await rm(home, { recursive: true, force: true });
68
+ }
69
+ }
70
+
71
+ /** The plan's usage windows and earned resets. */
72
+ export const readLimits = () => call('account/rateLimits/read');
73
+
74
+ /** Spends one earned rate-limit reset. Returns the outcome. */
75
+ export async function useReset() {
76
+ const result = await call('account/rateLimitResetCredit/consume', { idempotencyKey: randomUUID() });
77
+ return result?.outcome ?? 'unknown';
78
+ }
79
+
80
+ /** How many earned resets are left (0 when the service doesn't say). */
81
+ export const resetsLeft = (limits) => limits?.rateLimitResetCredits?.availableCount ?? 0;
82
+
83
+ /** One line per usage window: "codex: 100% used, 300-min window, resets 11:54". */
84
+ export function describe(limits) {
85
+ const lines = [];
86
+ const buckets = limits?.rateLimitsByLimitId ?? (limits?.rateLimits ? { [limits.rateLimits.limitId ?? 'codex']: limits.rateLimits } : {});
87
+ for (const [id, bucket] of Object.entries(buckets)) {
88
+ for (const [which, window] of [['primary', bucket.primary], ['secondary', bucket.secondary]]) {
89
+ if (!window) continue;
90
+ const at = window.resetsAt ? new Date(window.resetsAt * 1000).toLocaleString() : 'unknown';
91
+ lines.push(`${id} ${which}: ${window.usedPercent}% used of a ${window.windowDurationMins}-minute window, resets ${at}${bucket.rateLimitReachedType ? ` (${bucket.rateLimitReachedType})` : ''}`);
92
+ }
93
+ }
94
+ lines.push(`earned resets available: ${resetsLeft(limits)}`);
95
+ return lines.join('\n');
96
+ }
97
+
98
+ /**
99
+ * Waits while the plan is at, or within a run of, its usage limit, so a Codex
100
+ * run is not started only to be cut off partway (a run cut off is not an
101
+ * answer, and its share of the plan is lost). Sleeps until the fullest window
102
+ * resets. The thresholds match scripts/harness.mjs's Codex route: a run takes
103
+ * about a fifth of the 5-hour window and a few percent of the week.
104
+ */
105
+ export async function waitForPlan(say = () => {}, nearlyFull = { short: 80, week: 95 }) {
106
+ for (;;) {
107
+ let windows = [];
108
+ try {
109
+ const limits = await readLimits();
110
+ windows = Object.values(limits?.rateLimitsByLimitId ?? {})
111
+ .flatMap((b) => [b?.primary, b?.secondary])
112
+ .filter((w) => w?.resetsAt && w.usedPercent >= (w.windowDurationMins > 1440 ? nearlyFull.week : nearlyFull.short));
113
+ } catch (error) {
114
+ say(`couldn't read the plan's usage (${error.message}); going ahead`);
115
+ return;
116
+ }
117
+ if (!windows.length) return;
118
+ const until = Math.max(...windows.map((w) => w.resetsAt * 1000)) + 60_000;
119
+ say(`the ChatGPT plan is nearly at its limit; waiting until ${new Date(until).toLocaleString()}`);
120
+ await new Promise((resolve) => setTimeout(resolve, Math.max(60_000, until - Date.now())));
121
+ }
122
+ }