korveniq 1.0.2 → 1.0.4
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/README.md +34 -5
- package/bin/index.js +39 -0
- package/lib/build-profile.json +2 -2
- package/lib/chat.js +11 -1
- package/lib/settings.js +35 -1
- package/lib/tool-parser.js +2 -1
- package/lib/update-commands.js +125 -0
- package/lib/update-install.js +287 -0
- package/lib/update-recover.js +251 -0
- package/lib/update-semver.js +56 -0
- package/lib/update-source.js +221 -0
- package/lib/update-state.js +341 -0
- package/lib/update-tar.js +140 -0
- package/lib/update-view.js +124 -0
- package/lib/update.js +243 -0
- package/package.json +1 -1
package/lib/update.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* lib/update.js
|
|
5
|
+
* -----------------------------------------------------------------------------
|
|
6
|
+
* When to look for a new version and what to do about it.
|
|
7
|
+
*
|
|
8
|
+
* check the newest stable release, from a cache that is at most `updateCheckInterval` old
|
|
9
|
+
* stage download and verify it, next to the installation (lib/update-install.js)
|
|
10
|
+
* Session the same, in the background of an interactive chat:
|
|
11
|
+
*
|
|
12
|
+
* idle → checking → current
|
|
13
|
+
* → available (automatic updates off, or this installation cannot be changed)
|
|
14
|
+
* → downloading → staged → (on exit) installed | waiting | failed
|
|
15
|
+
* → failed
|
|
16
|
+
* checking → unverifiable npm signs with a key this version does not know (said once, nothing installed)
|
|
17
|
+
* → rejected the release failed verification (said once, nothing installed)
|
|
18
|
+
*
|
|
19
|
+
* The session never prints while it works: the REPL calls notice() between turns (never during a reply, a tool or an
|
|
20
|
+
* approval question) and finish() after the conversation is over, which is the only time files are replaced.
|
|
21
|
+
* Nothing automatic happens outside an interactive terminal (-p, --agent, pipes, CI), so machine-readable output is
|
|
22
|
+
* never touched. This module is not a tool: the AI has no way to call it.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const fs = require('fs');
|
|
26
|
+
const path = require('path');
|
|
27
|
+
const source = require('./update-source');
|
|
28
|
+
const semver = require('./update-semver');
|
|
29
|
+
const state = require('./update-state');
|
|
30
|
+
const installer = require('./update-install');
|
|
31
|
+
const view = require('./update-view');
|
|
32
|
+
const settings = require('./settings');
|
|
33
|
+
const config = require('./config');
|
|
34
|
+
const ui = require('./ui');
|
|
35
|
+
const pkg = require('../package.json');
|
|
36
|
+
|
|
37
|
+
const { UpdateError } = source;
|
|
38
|
+
const CACHE_FILE = path.join(config.CONFIG_DIR, 'update-check.json');
|
|
39
|
+
const FAILURE_RETRY_MS = 15 * 60_000;
|
|
40
|
+
const MAX_BACKOFF_MS = 24 * 60 * 60_000;
|
|
41
|
+
const FAILED_VERSION_PAUSE_MS = 24 * 60 * 60_000;
|
|
42
|
+
const FINISH_GRACE_MS = 2_000;
|
|
43
|
+
const VERIFICATION = ['KEY_UNKNOWN', 'UNTRUSTED'];
|
|
44
|
+
|
|
45
|
+
const userAgent = `korveniq-cli/${pkg.version}`;
|
|
46
|
+
const debug = (message) => ui.event('DEBUG', `update: ${message}`);
|
|
47
|
+
|
|
48
|
+
function writeCache(file, value) {
|
|
49
|
+
try {
|
|
50
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
51
|
+
state.writeJson(file, value);
|
|
52
|
+
} catch (err) {
|
|
53
|
+
debug(`could not save the check result (${err.code || err.message})`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A cached manifest is verified again: the cache file is only a memory, not a source of trust. */
|
|
58
|
+
function cachedManifest(m) {
|
|
59
|
+
if (!m) return null;
|
|
60
|
+
try {
|
|
61
|
+
return source.checkManifest({ name: m.name, version: m.version, deprecated: m.deprecated, dist: { tarball: m.tarball, integrity: m.integrity, signatures: m.signatures } });
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The latest release. Failures are remembered too, so an offline or rate-limited machine is not asked again and again.
|
|
69
|
+
* @returns {Promise<{ manifest: object, fromCache: boolean } | { manifest: null, error: Error|null, fromCache: boolean }>}
|
|
70
|
+
*/
|
|
71
|
+
async function check({ force = false, signal, now = Date.now, intervalMs, cacheFile = CACHE_FILE, retries = 0, timeoutMs } = {}) {
|
|
72
|
+
const interval = intervalMs === undefined ? settings.updates().checkIntervalMinutes * 60_000 : intervalMs;
|
|
73
|
+
const cache = state.readJson(cacheFile) || {};
|
|
74
|
+
const t = now();
|
|
75
|
+
if (!force) {
|
|
76
|
+
const manifest = cachedManifest(cache.latest);
|
|
77
|
+
if (manifest && cache.checkedAt <= t && t - cache.checkedAt < interval) return { manifest, fromCache: true };
|
|
78
|
+
// (a retry time far in the future is a clock that moved, not an instruction)
|
|
79
|
+
if (cache.retryAt > t && cache.retryAt - t <= MAX_BACKOFF_MS) {
|
|
80
|
+
const problem = VERIFICATION.includes(cache.problem) ? new UpdateError(cache.problem, 'The latest release could not be verified') : null;
|
|
81
|
+
return { manifest: null, error: problem, fromCache: true };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const manifest = await source.fetchLatest({ signal, userAgent, retries, timeoutMs });
|
|
86
|
+
writeCache(cacheFile, { checkedAt: now(), latest: manifest });
|
|
87
|
+
return { manifest, fromCache: false };
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (error.code !== 'ABORTED') {
|
|
90
|
+
const wait = error.code === 'RATE_LIMIT' ? Math.max(error.retryAfterMs || 0, interval) : Math.min(interval, FAILURE_RETRY_MS);
|
|
91
|
+
writeCache(cacheFile, { ...cache, retryAt: now() + Math.min(wait, MAX_BACKOFF_MS), problem: error.code });
|
|
92
|
+
}
|
|
93
|
+
return { manifest: null, error, fromCache: false };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Is `manifest` something to move to from `current`? Deprecated releases are never offered. */
|
|
98
|
+
const isOffer = (manifest, current) => Boolean(manifest) && !manifest.deprecated && semver.isUpgrade(manifest.version, current);
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Download and verify `manifest` and keep it for installation. Only one process downloads at a time.
|
|
102
|
+
* @returns {Promise<'staged'|'busy'>}
|
|
103
|
+
*/
|
|
104
|
+
async function stage(install, manifest, { signal, onProgress, manual = false } = {}) {
|
|
105
|
+
state.ensureStateDir(install);
|
|
106
|
+
const lock = state.acquire(path.join(install.stateDir, 'stage.lock'));
|
|
107
|
+
if (!lock) return 'busy';
|
|
108
|
+
try {
|
|
109
|
+
const already = installer.readStaged(install);
|
|
110
|
+
if (already && already.version === manifest.version && already.integrity === manifest.integrity) {
|
|
111
|
+
if (manual && !already.manual) state.writeJson(path.join(install.stateDir, 'staged.json'), { ...already, manual: true });
|
|
112
|
+
return 'staged';
|
|
113
|
+
}
|
|
114
|
+
for (const name of fs.readdirSync(install.stateDir)) if (name.endsWith('.part')) fs.rmSync(path.join(install.stateDir, name), { force: true });
|
|
115
|
+
const bytes = await source.download(manifest, { signal, userAgent, onProgress });
|
|
116
|
+
installer.writeStaged(install, manifest, bytes, { manual });
|
|
117
|
+
return 'staged';
|
|
118
|
+
} finally {
|
|
119
|
+
lock.release();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** May this run look for updates by itself? Only a person at a terminal, running an installed package. */
|
|
124
|
+
function sessionAllowed({ env = process.env, stdin = process.stdin, stdout = process.stdout, install } = {}) {
|
|
125
|
+
if (!stdin.isTTY || !stdout.isTTY) return false;
|
|
126
|
+
if (env.CI !== undefined && env.CI !== '' && env.CI !== 'false') return false;
|
|
127
|
+
if (!settings.updates().check) return false;
|
|
128
|
+
return install.kind !== 'source';
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
class Session {
|
|
132
|
+
constructor({ install = state.detect(), current = pkg.version, now = Date.now, cacheFile = CACHE_FILE, print = view.print, enabled } = {}) {
|
|
133
|
+
this.install = install;
|
|
134
|
+
this.current = current;
|
|
135
|
+
this.now = now;
|
|
136
|
+
this.cacheFile = cacheFile;
|
|
137
|
+
this.print = print;
|
|
138
|
+
this.enabled = enabled === undefined ? sessionAllowed({ install }) : enabled;
|
|
139
|
+
this.phase = 'idle';
|
|
140
|
+
this.version = null;
|
|
141
|
+
this.progress = null;
|
|
142
|
+
this.announced = new Set();
|
|
143
|
+
this.abort = new AbortController();
|
|
144
|
+
this.work = null;
|
|
145
|
+
this.nextCheckAt = 0;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Start (or, once the cache has aged, repeat) the background check. Returns immediately. */
|
|
149
|
+
tick() {
|
|
150
|
+
if (!this.enabled || this.work || this.abort.signal.aborted || this.now() < this.nextCheckAt) return this.work;
|
|
151
|
+
this.nextCheckAt = this.now() + settings.updates().checkIntervalMinutes * 60_000;
|
|
152
|
+
// Deferred, so even the synchronous part runs after the prompt has been drawn.
|
|
153
|
+
this.work = new Promise((resolve) => setImmediate(resolve))
|
|
154
|
+
.then(() => this.run())
|
|
155
|
+
.catch((err) => {
|
|
156
|
+
debug(err.message);
|
|
157
|
+
// Quiet when the registry simply cannot be asked; reported once when an update was under way.
|
|
158
|
+
if (this.phase === 'downloading' && err.code !== 'ABORTED') this.phase = 'failed';
|
|
159
|
+
else if (this.phase === 'checking') this.phase = 'idle';
|
|
160
|
+
})
|
|
161
|
+
.finally(() => {
|
|
162
|
+
this.work = null;
|
|
163
|
+
});
|
|
164
|
+
return this.work;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async run() {
|
|
168
|
+
if (this.phase === 'staged') return;
|
|
169
|
+
this.phase = 'checking';
|
|
170
|
+
const result = await check({ signal: this.abort.signal, now: this.now, cacheFile: this.cacheFile });
|
|
171
|
+
if (result.error) debug(`${result.error.code}: ${result.error.message}`);
|
|
172
|
+
// Not being able to ask is normal; not being able to believe the answer is something the user must hear about.
|
|
173
|
+
if (result.error && VERIFICATION.includes(result.error.code)) {
|
|
174
|
+
this.phase = result.error.code === 'KEY_UNKNOWN' ? 'unverifiable' : 'rejected';
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const onDisk = this.install.supported ? installer.installedVersion(this.install) : this.current;
|
|
178
|
+
if (!isOffer(result.manifest, onDisk)) {
|
|
179
|
+
this.phase = 'current';
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const manifest = result.manifest;
|
|
183
|
+
this.version = manifest.version;
|
|
184
|
+
if (!this.install.supported || !settings.updates().auto) {
|
|
185
|
+
this.phase = 'available';
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
state.ensureStateDir(this.install);
|
|
189
|
+
const failed = installer.readFailure(this.install);
|
|
190
|
+
if (failed && failed.version === manifest.version && this.now() - failed.at < FAILED_VERSION_PAUSE_MS) {
|
|
191
|
+
this.phase = 'available';
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
this.phase = 'downloading';
|
|
195
|
+
this.progress = null;
|
|
196
|
+
const staged = await stage(this.install, manifest, { signal: this.abort.signal, onProgress: (received, total) => (this.progress = { received, total }) });
|
|
197
|
+
this.phase = staged === 'staged' ? 'staged' : 'current'; // busy: another session is downloading it
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Called while no reply, tool or question is active. Says each thing about a version once. */
|
|
201
|
+
notice() {
|
|
202
|
+
if (!this.enabled) return;
|
|
203
|
+
const kind = ['available', 'downloading', 'staged', 'failed', 'unverifiable', 'rejected'].includes(this.phase) ? this.phase : null;
|
|
204
|
+
if (!kind) return;
|
|
205
|
+
const key = `${kind}:${this.version}`;
|
|
206
|
+
if (this.announced.has(key)) return;
|
|
207
|
+
this.announced.add(key);
|
|
208
|
+
// After "downloading", finishing the download needs no second headline.
|
|
209
|
+
const followUp = kind === 'staged' && this.announced.has(`downloading:${this.version}`);
|
|
210
|
+
this.print(view.notice(kind, { current: this.current, version: this.version, progress: this.progress, followUp, install: this.install, auto: settings.updates().auto }));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* The conversation is over: stop an unfinished download (exit is never held up by the network) and install what is
|
|
215
|
+
* staged, if this is the last session. Never throws.
|
|
216
|
+
*/
|
|
217
|
+
async finish() {
|
|
218
|
+
const allowed = this.enabled && this.install.supported;
|
|
219
|
+
if (this.work && this.phase === 'downloading' && this.progress && this.progress.total === this.progress.received) {
|
|
220
|
+
await Promise.race([this.work, new Promise((resolve) => setTimeout(resolve, FINISH_GRACE_MS).unref())]);
|
|
221
|
+
}
|
|
222
|
+
this.abort.abort();
|
|
223
|
+
if (!allowed) return null;
|
|
224
|
+
try {
|
|
225
|
+
const staged = fs.existsSync(this.install.stateDir) ? installer.readStaged(this.install) : null;
|
|
226
|
+
// A download the user asked for (`korveniq update`) is installed even with automatic updates off.
|
|
227
|
+
if (!staged || !(staged.manual || settings.updates().auto)) return null;
|
|
228
|
+
// From here on this process needs no more installed files, so it no longer counts: of two sessions that end at
|
|
229
|
+
// the same time, the later one always sees the other gone and installs.
|
|
230
|
+
state.endSession(this.install);
|
|
231
|
+
const result = installer.apply(this.install);
|
|
232
|
+
if (result.status === 'installed') this.print(view.installed(result.version));
|
|
233
|
+
else if (result.status === 'busy') this.print(view.waiting(staged.version, result.reason));
|
|
234
|
+
return result;
|
|
235
|
+
} catch (err) {
|
|
236
|
+
debug(err.message);
|
|
237
|
+
this.print(view.failed(err, this.install));
|
|
238
|
+
return { status: 'failed', error: err };
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
module.exports = { check, stage, isOffer, sessionAllowed, Session, UpdateError, CACHE_FILE };
|