acuvo-code 0.2.1 → 0.3.1
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/ENTERPRISE.md +927 -927
- package/README.md +4 -0
- package/bin/acuvo.mjs +3204 -3108
- package/lib/device-login.mjs +208 -0
- package/lib/self-update.mjs +174 -0
- package/package.json +1 -1
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ── ⭐⭐⭐ `acuvo` LOGS ITSELF IN ────────────────────────────────────────────
|
|
3
|
+
*
|
|
4
|
+
* Roman, 2026-08-22: *"paying users should be able to type acuvo into a terminal
|
|
5
|
+
* and then it works... like how I pay and I can type claude and it works, but it
|
|
6
|
+
* probably works for anyone, but they have to log in."*
|
|
7
|
+
*
|
|
8
|
+
* RFC 8628 device-authorization grant, client half. Replaces the five-step
|
|
9
|
+
* manual path (sign in → find Settings → create key → copy → `acuvo --login
|
|
10
|
+
* xxi_live_…`) with: run `acuvo`, approve in the browser, done.
|
|
11
|
+
*
|
|
12
|
+
* ⚠️ EVERY PIECE OF IO IS INJECTED — `fetchImpl`, `openBrowser`, `sleep`, `now`.
|
|
13
|
+
* Not for purity's sake: this module's whole job is a timing loop against a
|
|
14
|
+
* remote service, and a version that can only be tested by actually waiting two
|
|
15
|
+
* seconds a tick against production is a version nobody tests. The CLI's success
|
|
16
|
+
* path had zero coverage once before, for exactly this reason.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { DEFAULT_GATEWAY_URL } from './account.mjs';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The gateway constant points at the completions endpoint; the device endpoints
|
|
23
|
+
* are siblings of it. Derived rather than duplicated so a self-hosted or staging
|
|
24
|
+
* gateway moves all three together.
|
|
25
|
+
*/
|
|
26
|
+
export function deviceEndpoints(gatewayUrl = DEFAULT_GATEWAY_URL) {
|
|
27
|
+
const base = String(gatewayUrl).replace(/\/api\/cli\/v1\/chat\/completions\/?$/, '');
|
|
28
|
+
return {
|
|
29
|
+
code: `${base}/api/cli/v1/device/code`,
|
|
30
|
+
token: `${base}/api/cli/v1/device/token`,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Ask for a device code. Returns the server's payload, or throws a readable error. */
|
|
35
|
+
export async function requestDeviceCode(gatewayUrl = DEFAULT_GATEWAY_URL, { fetchImpl = fetch, timeoutMs = 15000 } = {}) {
|
|
36
|
+
const { code } = deviceEndpoints(gatewayUrl);
|
|
37
|
+
const controller = new AbortController();
|
|
38
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
39
|
+
let res;
|
|
40
|
+
try {
|
|
41
|
+
res = await fetchImpl(code, { method: 'POST', signal: controller.signal });
|
|
42
|
+
} catch (e) {
|
|
43
|
+
throw new Error(`could not reach Acuvo to start a login (${e?.message ?? e}). Check your connection.`);
|
|
44
|
+
} finally {
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* ⚠️ A NON-JSON BODY IS THE SYMPTOM THAT MATTERS HERE. If the middleware ever
|
|
50
|
+
* stops exempting this path, the response is a 307 to an HTML login page —
|
|
51
|
+
* and "unexpected token < in JSON" tells the user nothing they can act on.
|
|
52
|
+
* That exact failure has shipped on this path before.
|
|
53
|
+
*/
|
|
54
|
+
const text = await res.text();
|
|
55
|
+
let json;
|
|
56
|
+
try {
|
|
57
|
+
json = JSON.parse(text);
|
|
58
|
+
} catch {
|
|
59
|
+
throw new Error(
|
|
60
|
+
`Acuvo returned a ${res.status} that was not JSON — the login endpoint is not reachable. ` +
|
|
61
|
+
`This is a server-side problem, not something you can fix locally.`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
if (!res.ok) throw new Error(json?.error ? `login could not start: ${json.error}` : `login could not start (HTTP ${res.status})`);
|
|
65
|
+
if (!json?.device_code || !json?.user_code) throw new Error('Acuvo did not return a login code.');
|
|
66
|
+
return json;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** RFC 8628 statuses that mean "keep waiting" rather than "stop". */
|
|
70
|
+
const PENDING = new Set(['authorization_pending', 'slow_down']);
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Poll until the human approves, denies, or the code expires.
|
|
74
|
+
*
|
|
75
|
+
* @returns {Promise<{api_key: string, tenant_id: string|null}>}
|
|
76
|
+
*/
|
|
77
|
+
export async function pollForKey(
|
|
78
|
+
gatewayUrl,
|
|
79
|
+
deviceCode,
|
|
80
|
+
{
|
|
81
|
+
intervalMs = 2000,
|
|
82
|
+
expiresInMs = 600000,
|
|
83
|
+
fetchImpl = fetch,
|
|
84
|
+
sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
85
|
+
now = () => Date.now(),
|
|
86
|
+
onTick = () => {},
|
|
87
|
+
} = {},
|
|
88
|
+
) {
|
|
89
|
+
const { token } = deviceEndpoints(gatewayUrl);
|
|
90
|
+
const deadline = now() + expiresInMs;
|
|
91
|
+
let wait = intervalMs;
|
|
92
|
+
|
|
93
|
+
while (now() < deadline) {
|
|
94
|
+
await sleep(wait);
|
|
95
|
+
onTick();
|
|
96
|
+
|
|
97
|
+
let res;
|
|
98
|
+
let json = {};
|
|
99
|
+
try {
|
|
100
|
+
res = await fetchImpl(token, {
|
|
101
|
+
method: 'POST',
|
|
102
|
+
headers: { 'content-type': 'application/json' },
|
|
103
|
+
body: JSON.stringify({ device_code: deviceCode }),
|
|
104
|
+
});
|
|
105
|
+
json = await res.json().catch(() => ({}));
|
|
106
|
+
} catch {
|
|
107
|
+
/**
|
|
108
|
+
* ⚠️ A DROPPED POLL IS NOT A FAILED LOGIN. Wifi blips mid-approval are
|
|
109
|
+
* ordinary; aborting here would throw away an approval the user already
|
|
110
|
+
* gave. Keep waiting until the code itself expires.
|
|
111
|
+
*/
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (res.ok && json.api_key) return { api_key: json.api_key, tenant_id: json.tenant_id ?? null };
|
|
116
|
+
|
|
117
|
+
const err = String(json.error ?? '');
|
|
118
|
+
if (err === 'access_denied') throw new Error('login was denied in the browser.');
|
|
119
|
+
if (err === 'expired_token') throw new Error('the login code expired. Run `acuvo --login` again.');
|
|
120
|
+
if (err === 'already_claimed') throw new Error('that login code was already used. Run `acuvo --login` again.');
|
|
121
|
+
if (err === 'invalid_grant') throw new Error('that login code is not recognised. Run `acuvo --login` again.');
|
|
122
|
+
|
|
123
|
+
// `slow_down` is the server asking for room; honouring it is the difference
|
|
124
|
+
// between a polite client and one that gets rate-limited mid-login.
|
|
125
|
+
if (err === 'slow_down') wait = Math.min(wait * 2, 10000);
|
|
126
|
+
else if (!PENDING.has(err) && !res.ok && res.status >= 500) wait = Math.min(wait * 2, 10000);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
throw new Error('the login code expired before it was approved. Run `acuvo --login` again.');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Best-effort browser open. NEVER throws and never blocks the flow.
|
|
134
|
+
*
|
|
135
|
+
* ⚠️ THE URL IS ALWAYS PRINTED TOO, and that is not redundancy — this runs over
|
|
136
|
+
* SSH, in containers, and in terminals with no desktop session, where opening a
|
|
137
|
+
* browser is impossible by definition. A flow that depends on the open
|
|
138
|
+
* succeeding is a flow that strands every remote user.
|
|
139
|
+
*/
|
|
140
|
+
export function openBrowser(url, { platform = process.platform, spawn } = {}) {
|
|
141
|
+
if (!spawn) return false;
|
|
142
|
+
const cmd = platform === 'win32' ? 'cmd' : platform === 'darwin' ? 'open' : 'xdg-open';
|
|
143
|
+
const args = platform === 'win32' ? ['/c', 'start', '', url] : [url];
|
|
144
|
+
try {
|
|
145
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
146
|
+
child.unref?.();
|
|
147
|
+
return true;
|
|
148
|
+
} catch {
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* ── ⭐⭐⭐ ONE LOGIN FLOW, TWO DOORS ─────────────────────────────────────────
|
|
155
|
+
*
|
|
156
|
+
* Drives the whole grant: ask for a code, show it, open a browser, wait, save.
|
|
157
|
+
* Reached from `acuvo --login` AND from a bare `acuvo` that finds no
|
|
158
|
+
* credential — the second of which is what makes typing `acuvo` enough, the
|
|
159
|
+
* way typing `claude` is.
|
|
160
|
+
*
|
|
161
|
+
* ⚠️ IT LIVES HERE, NOT IN `bin/`. The first version was written inline inside
|
|
162
|
+
* the `--login` branch and was needed by a second caller within the hour. A fix
|
|
163
|
+
* that lives inside one caller is a fix for one caller — this codebase has paid
|
|
164
|
+
* for that three times today alone. Extracted before the second copy existed
|
|
165
|
+
* rather than after.
|
|
166
|
+
*
|
|
167
|
+
* ⚠️ IT THROWS RATHER THAN EXITING. `bin/` owns exit codes and phrasing; a
|
|
168
|
+
* library that calls `process.exit` cannot be tested and cannot be reused.
|
|
169
|
+
*
|
|
170
|
+
* @returns {Promise<{token: string, restricted: boolean|null, userCode: string}>}
|
|
171
|
+
*/
|
|
172
|
+
export async function runDeviceLogin({
|
|
173
|
+
gatewayUrl,
|
|
174
|
+
write = (s) => process.stderr.write(s),
|
|
175
|
+
spawn,
|
|
176
|
+
requestCode = requestDeviceCode,
|
|
177
|
+
poll = pollForKey,
|
|
178
|
+
open = openBrowser,
|
|
179
|
+
saveAccount,
|
|
180
|
+
} = {}) {
|
|
181
|
+
const start = await requestCode(gatewayUrl);
|
|
182
|
+
const url = start.verification_uri_complete || start.verification_uri;
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* ⚠️ THE URL AND CODE ARE PRINTED WHETHER OR NOT THE BROWSER OPENS. This runs
|
|
186
|
+
* over SSH, in containers, and in terminals with no desktop session, where
|
|
187
|
+
* opening a browser is impossible by definition — a flow that assumes the
|
|
188
|
+
* open worked strands every remote user.
|
|
189
|
+
*/
|
|
190
|
+
write(`\nYour code: ${start.user_code}\n\n`);
|
|
191
|
+
const opened = open(url, { spawn });
|
|
192
|
+
write(opened
|
|
193
|
+
? `Opened your browser to approve it. If nothing appeared:\n ${url}\n\n`
|
|
194
|
+
: `Open this to approve it:\n ${url}\n\n`);
|
|
195
|
+
write('Waiting for approval… (Ctrl-C to cancel)\n');
|
|
196
|
+
|
|
197
|
+
const granted = await poll(gatewayUrl, start.device_code, {
|
|
198
|
+
intervalMs: (start.interval ?? 2) * 1000,
|
|
199
|
+
expiresInMs: (start.expires_in ?? 600) * 1000,
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
const saved = saveAccount ? saveAccount(granted.api_key) : null;
|
|
203
|
+
return {
|
|
204
|
+
token: granted.api_key,
|
|
205
|
+
restricted: saved && typeof saved.restricted === 'boolean' ? saved.restricted : null,
|
|
206
|
+
userCode: start.user_code,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ── ⭐⭐⭐ USERS GET UPDATES WITHOUT BEING ASKED TO ──────────────────────────
|
|
3
|
+
*
|
|
4
|
+
* Roman, 2026-08-22: *"how do we do self updates so all users get updates as
|
|
5
|
+
* soon as we do it, and we just advertise the new npm version instead of having
|
|
6
|
+
* users constantly download new versions, like Claude."*
|
|
7
|
+
*
|
|
8
|
+
* npm is IMMUTABLE — a published version can never be changed — so shipping a
|
|
9
|
+
* fix means publishing a new version, and without this module every user sits on
|
|
10
|
+
* whatever they first installed, forever. A bug we fixed in an hour would live
|
|
11
|
+
* on their machine for months.
|
|
12
|
+
*
|
|
13
|
+
* ── ⚠️⚠️ WHAT THIS MUST NEVER DO, WHICH IS MOST OF THE DESIGN ───────────────
|
|
14
|
+
*
|
|
15
|
+
* It must never block a run, never throw, never slow the first token, and never
|
|
16
|
+
* swap files underneath a session that is already executing. An update mechanism
|
|
17
|
+
* that can break the tool is worse than no update mechanism: the failure lands
|
|
18
|
+
* on someone who was in the middle of real work and did not ask for any of it.
|
|
19
|
+
*
|
|
20
|
+
* So: the check is THROTTLED to once a day against a cache, the install runs
|
|
21
|
+
* DETACHED after the decision, and the new version applies on the NEXT run —
|
|
22
|
+
* never the current one.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
26
|
+
import { join, dirname } from 'node:path';
|
|
27
|
+
import { accountDir } from './account.mjs';
|
|
28
|
+
|
|
29
|
+
export const PACKAGE_NAME = 'acuvo-code';
|
|
30
|
+
|
|
31
|
+
/** How long between registry checks. A day is plenty and keeps npm quiet. */
|
|
32
|
+
export const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Compare two semver-ish strings.
|
|
36
|
+
*
|
|
37
|
+
* ⚠️ NUMERIC PER SEGMENT, NOT LEXICOGRAPHIC. `'0.10.0' > '0.9.0'` is TRUE
|
|
38
|
+
* numerically and FALSE as strings — so a string compare stops offering updates
|
|
39
|
+
* exactly when the minor version reaches 10, and does it silently.
|
|
40
|
+
*
|
|
41
|
+
* @returns 1 if a > b, -1 if a < b, 0 if equal
|
|
42
|
+
*/
|
|
43
|
+
export function compareVersions(a, b) {
|
|
44
|
+
const parse = (v) =>
|
|
45
|
+
String(v ?? '')
|
|
46
|
+
.trim()
|
|
47
|
+
.replace(/^v/, '')
|
|
48
|
+
// A prerelease suffix (`1.0.0-beta.1`) is dropped rather than ranked. We
|
|
49
|
+
// do not publish them, and inventing an ordering for something that does
|
|
50
|
+
// not exist is how you offer people a "newer" version that is older.
|
|
51
|
+
.split('-')[0]
|
|
52
|
+
.split('.')
|
|
53
|
+
.map((n) => Number.parseInt(n, 10) || 0);
|
|
54
|
+
const [x, y] = [parse(a), parse(b)];
|
|
55
|
+
for (let i = 0; i < Math.max(x.length, y.length); i += 1) {
|
|
56
|
+
const d = (x[i] ?? 0) - (y[i] ?? 0);
|
|
57
|
+
if (d !== 0) return d > 0 ? 1 : -1;
|
|
58
|
+
}
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function updateCachePath(env = process.env) {
|
|
63
|
+
return join(accountDir(env), 'update-check.json');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function readCache(path) {
|
|
67
|
+
try {
|
|
68
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function writeCache(path, value) {
|
|
75
|
+
try {
|
|
76
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
77
|
+
writeFileSync(path, JSON.stringify(value), 'utf8');
|
|
78
|
+
} catch {
|
|
79
|
+
// A read-only home is not a reason to fail a run. Worst case we check again
|
|
80
|
+
// next time, which costs one HTTP request.
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Is there a newer published version?
|
|
86
|
+
*
|
|
87
|
+
* @returns {Promise<{latest: string, isNewer: boolean, checked: boolean}>}
|
|
88
|
+
*/
|
|
89
|
+
export async function checkForUpdate({
|
|
90
|
+
current,
|
|
91
|
+
fetchImpl = fetch,
|
|
92
|
+
now = () => Date.now(),
|
|
93
|
+
cachePath = updateCachePath(),
|
|
94
|
+
intervalMs = CHECK_INTERVAL_MS,
|
|
95
|
+
timeoutMs = 3000,
|
|
96
|
+
force = false,
|
|
97
|
+
} = {}) {
|
|
98
|
+
const cached = readCache(cachePath);
|
|
99
|
+
if (!force && cached && now() - (cached.at ?? 0) < intervalMs) {
|
|
100
|
+
return { latest: cached.latest ?? current, isNewer: compareVersions(cached.latest, current) > 0, checked: false };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
let latest = current;
|
|
104
|
+
try {
|
|
105
|
+
const controller = new AbortController();
|
|
106
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
107
|
+
/**
|
|
108
|
+
* ⚠️ THE `latest` ENDPOINT, NOT THE FULL PACKUMENT. The full document for
|
|
109
|
+
* this package is megabytes of version history; this one is a few hundred
|
|
110
|
+
* bytes. On a slow connection that difference is the whole reason the check
|
|
111
|
+
* finishes inside its timeout instead of being abandoned every run.
|
|
112
|
+
*/
|
|
113
|
+
const res = await fetchImpl(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
|
|
114
|
+
signal: controller.signal,
|
|
115
|
+
headers: { accept: 'application/json' },
|
|
116
|
+
});
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
const json = await res.json();
|
|
119
|
+
if (typeof json?.version === 'string') latest = json.version;
|
|
120
|
+
} catch {
|
|
121
|
+
// Offline, DNS down, npm having a moment. None of these are the user's
|
|
122
|
+
// problem and none should surface.
|
|
123
|
+
return { latest: current, isNewer: false, checked: false };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
writeCache(cachePath, { at: now(), latest });
|
|
127
|
+
return { latest, isNewer: compareVersions(latest, current) > 0, checked: true };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Install the newer version, DETACHED, so it applies to the next run.
|
|
132
|
+
*
|
|
133
|
+
* ⚠️⚠️ NEVER IN-PROCESS AND NEVER AWAITED. Rewriting `lib/*.mjs` underneath a
|
|
134
|
+
* session that is mid-task is how an update becomes a crash in someone else's
|
|
135
|
+
* work — and the person it lands on never asked for the update at all.
|
|
136
|
+
*
|
|
137
|
+
* @returns {boolean} whether the install was successfully STARTED (not finished)
|
|
138
|
+
*/
|
|
139
|
+
export function applyUpdate({ spawn, version = 'latest' } = {}) {
|
|
140
|
+
if (!spawn) return false;
|
|
141
|
+
try {
|
|
142
|
+
const child = spawn(
|
|
143
|
+
process.platform === 'win32' ? 'npm.cmd' : 'npm',
|
|
144
|
+
['install', '-g', `${PACKAGE_NAME}@${version}`],
|
|
145
|
+
{ stdio: 'ignore', detached: true },
|
|
146
|
+
);
|
|
147
|
+
child.unref?.();
|
|
148
|
+
return true;
|
|
149
|
+
} catch {
|
|
150
|
+
// A global install can fail on permissions (a root-owned prefix is common).
|
|
151
|
+
// Silently — the notice below still tells them the command to run.
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The one line a user sees. Deliberately small; nobody wants a changelog here. */
|
|
157
|
+
export function updateNotice(current, latest, applied) {
|
|
158
|
+
return applied
|
|
159
|
+
? `\nacuvo ${latest} is available (you have ${current}) — installing in the background, it will apply next run.\n`
|
|
160
|
+
: `\nacuvo ${latest} is available (you have ${current}) — update with: npm i -g ${PACKAGE_NAME}@latest\n`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Whether we should look at all.
|
|
165
|
+
*
|
|
166
|
+
* ⚠️ OFF FOR CI AND FOR ANYONE WHO SAYS SO. A build machine that silently
|
|
167
|
+
* upgrades its own toolchain mid-pipeline produces results nobody can reproduce,
|
|
168
|
+
* which is precisely the thing CI exists to prevent.
|
|
169
|
+
*/
|
|
170
|
+
export function updatesEnabled(env = process.env) {
|
|
171
|
+
if (String(env.ACUVO_NO_UPDATE ?? '') === '1') return false;
|
|
172
|
+
if (String(env.CI ?? '').toLowerCase() === 'true' || env.CI === '1') return false;
|
|
173
|
+
return true;
|
|
174
|
+
}
|