@causyne/agent 1.20.19 → 1.20.20
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/bin/causyne.js +7 -1
- package/package.json +1 -1
- package/src/autoUpdate.js +251 -183
- package/src/autoUpdate.ts +360 -0
- package/src/utils/cli_ui.d.ts +19 -0
package/bin/causyne.js
CHANGED
|
@@ -8,7 +8,13 @@ try {
|
|
|
8
8
|
const { startUpdateChecker } = await import('../src/autoUpdate.js');
|
|
9
9
|
const update = await startUpdateChecker();
|
|
10
10
|
if (update && update.updated) {
|
|
11
|
-
process.stderr.write(`Causyne updated to ${update.latest}.
|
|
11
|
+
process.stderr.write(`Causyne Agent updated to ${update.latest}. Restarting...\n`);
|
|
12
|
+
const { spawnSync } = await import('node:child_process');
|
|
13
|
+
const child = spawnSync(process.execPath, process.argv.slice(1), {
|
|
14
|
+
stdio: 'inherit',
|
|
15
|
+
env: process.env
|
|
16
|
+
});
|
|
17
|
+
process.exit(child.status ?? 0);
|
|
12
18
|
}
|
|
13
19
|
await import('../src/entrypoint.js');
|
|
14
20
|
} catch (error) {
|
package/package.json
CHANGED
package/src/autoUpdate.js
CHANGED
|
@@ -4,223 +4,291 @@
|
|
|
4
4
|
// causyne.com installer. A source checkout is never rewritten. Commands are
|
|
5
5
|
// passed as argv arrays with shell disabled, and the only accepted package is
|
|
6
6
|
// the public @causyne/agent package from the npm registry.
|
|
7
|
-
|
|
8
7
|
import fs from 'node:fs';
|
|
9
8
|
import path from 'node:path';
|
|
10
9
|
import { fileURLToPath } from 'node:url';
|
|
11
10
|
import { spawnSync } from 'node:child_process';
|
|
12
|
-
|
|
13
11
|
import { UI } from './utils/cli_ui.js';
|
|
14
12
|
import { causyneHome } from './utils/paths.js';
|
|
15
13
|
import { getPackageVersion } from './version.js';
|
|
16
|
-
|
|
17
14
|
const PACKAGE_NAME = '@causyne/agent';
|
|
18
15
|
const REGISTRY_LATEST = 'https://registry.npmjs.org/@causyne%2fagent/latest';
|
|
19
|
-
const
|
|
16
|
+
const DEFAULT_CHECK_INTERVAL_MS = 60 * 60 * 1000; // 1 hour for active developer agility
|
|
17
|
+
const ERROR_RETRY_INTERVAL_MS = 2 * 60 * 1000; // 2 minutes retry on network error
|
|
20
18
|
const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
21
|
-
|
|
22
19
|
function updateStateFile(options = {}) {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
20
|
+
if (options.stateFile)
|
|
21
|
+
return path.resolve(options.stateFile);
|
|
22
|
+
const env = options.env || process.env;
|
|
23
|
+
const root = env.CAUSYNE_HOME && String(env.CAUSYNE_HOME).trim()
|
|
24
|
+
? path.resolve(String(env.CAUSYNE_HOME).trim())
|
|
25
|
+
: causyneHome();
|
|
26
|
+
return path.join(root, 'update-state.json');
|
|
29
27
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
28
|
+
export function versionParts(version) {
|
|
29
|
+
const match = String(version || '').trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
|
|
30
|
+
if (!match)
|
|
31
|
+
return null;
|
|
32
|
+
const num1 = Number(match[1]);
|
|
33
|
+
const num2 = Number(match[2]);
|
|
34
|
+
const num3 = Number(match[3]);
|
|
35
|
+
return { numbers: [num1, num2, num3], prerelease: match[4] || '' };
|
|
35
36
|
}
|
|
36
|
-
|
|
37
37
|
export function compareVersions(left, right) {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if (
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
38
|
+
const a = versionParts(left);
|
|
39
|
+
const b = versionParts(right);
|
|
40
|
+
if (!a || !b)
|
|
41
|
+
return 0;
|
|
42
|
+
for (let index = 0; index < 3; index++) {
|
|
43
|
+
const aNum = a.numbers[index] ?? 0;
|
|
44
|
+
const bNum = b.numbers[index] ?? 0;
|
|
45
|
+
if (aNum !== bNum)
|
|
46
|
+
return aNum > bNum ? 1 : -1;
|
|
47
|
+
}
|
|
48
|
+
if (a.prerelease === b.prerelease)
|
|
49
|
+
return 0;
|
|
50
|
+
if (!a.prerelease)
|
|
51
|
+
return 1;
|
|
52
|
+
if (!b.prerelease)
|
|
53
|
+
return -1;
|
|
54
|
+
const aParts = a.prerelease.split('.');
|
|
55
|
+
const bParts = b.prerelease.split('.');
|
|
56
|
+
const length = Math.max(aParts.length, bParts.length);
|
|
57
|
+
for (let index = 0; index < length; index++) {
|
|
58
|
+
const aPart = aParts[index];
|
|
59
|
+
const bPart = bParts[index];
|
|
60
|
+
if (aPart === undefined)
|
|
61
|
+
return -1;
|
|
62
|
+
if (bPart === undefined)
|
|
63
|
+
return 1;
|
|
64
|
+
if (aPart === bPart)
|
|
65
|
+
continue;
|
|
66
|
+
const aNumeric = /^\d+$/.test(aPart);
|
|
67
|
+
const bNumeric = /^\d+$/.test(bPart);
|
|
68
|
+
if (aNumeric && bNumeric)
|
|
69
|
+
return Number(aPart) > Number(bPart) ? 1 : -1;
|
|
70
|
+
if (aNumeric !== bNumeric)
|
|
71
|
+
return aNumeric ? -1 : 1;
|
|
72
|
+
return aPart.localeCompare(bPart);
|
|
73
|
+
}
|
|
74
|
+
return 0;
|
|
61
75
|
}
|
|
62
|
-
|
|
63
76
|
function managedPrefix(packageRoot = PACKAGE_ROOT, env = process.env) {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
+
if (env.CAUSYNE_INSTALL_ROOT)
|
|
78
|
+
return path.resolve(env.CAUSYNE_INSTALL_ROOT);
|
|
79
|
+
const markers = [
|
|
80
|
+
path.join('lib', 'node_modules', '@causyne', 'agent'),
|
|
81
|
+
path.join('node_modules', '@causyne', 'agent')
|
|
82
|
+
];
|
|
83
|
+
for (const marker of markers) {
|
|
84
|
+
const index = packageRoot.lastIndexOf(marker);
|
|
85
|
+
if (index >= 0 && index + marker.length === packageRoot.length) {
|
|
86
|
+
return packageRoot.slice(0, index).replace(/[\\/]$/, '');
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
export function resolveNpmExecutable(env = process.env) {
|
|
92
|
+
if (env.CAUSYNE_NPM_COMMAND && String(env.CAUSYNE_NPM_COMMAND).trim()) {
|
|
93
|
+
return String(env.CAUSYNE_NPM_COMMAND).trim();
|
|
94
|
+
}
|
|
95
|
+
const isWin = process.platform === 'win32';
|
|
96
|
+
const npmName = isWin ? 'npm.cmd' : 'npm';
|
|
97
|
+
// 1. Sibling of running node binary (most reliable across all Node version managers: nvm, fnm, volta, mise)
|
|
98
|
+
if (process.execPath) {
|
|
99
|
+
const sibling = path.join(path.dirname(process.execPath), npmName);
|
|
100
|
+
if (fs.existsSync(sibling)) {
|
|
101
|
+
return sibling;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// 2. Private Causyne runtime if provisioned
|
|
105
|
+
const privateNpm = path.join(causyneHome(), 'runtime', 'node', isWin ? '' : 'bin', npmName);
|
|
106
|
+
if (fs.existsSync(privateNpm)) {
|
|
107
|
+
return privateNpm;
|
|
108
|
+
}
|
|
109
|
+
// 3. Default fallback to system PATH
|
|
110
|
+
return npmName;
|
|
77
111
|
}
|
|
78
|
-
|
|
79
112
|
export function installationInfo(options = {}) {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
113
|
+
const env = options.env || process.env;
|
|
114
|
+
const packageRoot = options.packageRoot || PACKAGE_ROOT;
|
|
115
|
+
const prefix = managedPrefix(packageRoot, env);
|
|
116
|
+
const npmCommand = resolveNpmExecutable(env);
|
|
117
|
+
return {
|
|
118
|
+
managed: Boolean(prefix),
|
|
119
|
+
type: env.CAUSYNE_INSTALL_ROOT ? 'causyne.com installer' : (prefix ? 'global npm' : 'source checkout'),
|
|
120
|
+
prefix,
|
|
121
|
+
packageRoot,
|
|
122
|
+
npmCommand
|
|
123
|
+
};
|
|
90
124
|
}
|
|
91
|
-
|
|
92
125
|
function readState(options = {}) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
126
|
+
try {
|
|
127
|
+
return JSON.parse(fs.readFileSync(updateStateFile(options), 'utf8'));
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return {};
|
|
131
|
+
}
|
|
98
132
|
}
|
|
99
|
-
|
|
100
133
|
function writeState(state, options = {}) {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
134
|
+
try {
|
|
135
|
+
const stateFile = updateStateFile(options);
|
|
136
|
+
fs.mkdirSync(path.dirname(stateFile), { recursive: true, mode: 0o700 });
|
|
137
|
+
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), { mode: 0o600 });
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// Update state is an optimisation. Failure must never stop the CLI.
|
|
141
|
+
}
|
|
108
142
|
}
|
|
109
|
-
|
|
110
143
|
export async function latestPackageVersion(options = {}) {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
144
|
+
const fetchImpl = options.fetchImpl || globalThis.fetch;
|
|
145
|
+
if (typeof fetchImpl !== 'function')
|
|
146
|
+
throw new Error('This Node.js runtime has no fetch implementation.');
|
|
147
|
+
const timeoutMs = options.timeoutMs || 3500;
|
|
148
|
+
const signal = options.signal || AbortSignal.timeout(timeoutMs);
|
|
149
|
+
const response = await fetchImpl(REGISTRY_LATEST, {
|
|
150
|
+
headers: { accept: 'application/json', 'user-agent': `causyne/${getPackageVersion()}` },
|
|
151
|
+
signal
|
|
152
|
+
});
|
|
153
|
+
if (!response.ok)
|
|
154
|
+
throw new Error(`npm registry returned HTTP ${response.status}`);
|
|
155
|
+
const metadata = (await response.json());
|
|
156
|
+
if (metadata.name !== PACKAGE_NAME || !versionParts(metadata.version)) {
|
|
157
|
+
throw new Error('npm registry returned invalid package metadata');
|
|
158
|
+
}
|
|
159
|
+
return metadata.version;
|
|
125
160
|
}
|
|
126
|
-
|
|
127
161
|
function installLatest(info, options = {}) {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
162
|
+
if (!info.prefix) {
|
|
163
|
+
throw new Error('Cannot install package: prefix is not defined for this installation.');
|
|
164
|
+
}
|
|
165
|
+
const runner = options.spawnSyncImpl || spawnSync;
|
|
166
|
+
const targetVersion = options.version;
|
|
167
|
+
if (!targetVersion) {
|
|
168
|
+
throw new Error('Target version must be specified for installation.');
|
|
169
|
+
}
|
|
170
|
+
const args = [
|
|
171
|
+
'install', '--global', '--prefix', info.prefix,
|
|
172
|
+
`${PACKAGE_NAME}@${targetVersion}`, '--ignore-scripts', '--no-audit', '--no-fund'
|
|
173
|
+
];
|
|
174
|
+
// Prepend the directory containing node and npm to PATH so child npm executes smoothly
|
|
175
|
+
const env = { ...(options.env || process.env) };
|
|
176
|
+
const extraPaths = [path.dirname(process.execPath)];
|
|
177
|
+
if (info.npmCommand.includes('/') || info.npmCommand.includes('\\')) {
|
|
178
|
+
extraPaths.push(path.dirname(info.npmCommand));
|
|
179
|
+
}
|
|
180
|
+
const delimiter = process.platform === 'win32' ? ';' : ':';
|
|
181
|
+
const currentPath = env.PATH || env.Path || '';
|
|
182
|
+
env.PATH = [...extraPaths, currentPath].filter(Boolean).join(delimiter);
|
|
183
|
+
const result = runner(info.npmCommand, args, {
|
|
184
|
+
shell: false,
|
|
185
|
+
stdio: options.verbose ? 'inherit' : 'pipe',
|
|
186
|
+
encoding: 'utf8',
|
|
187
|
+
env
|
|
188
|
+
});
|
|
189
|
+
if (result.error)
|
|
190
|
+
throw result.error;
|
|
191
|
+
if (result.status !== 0) {
|
|
192
|
+
const detail = String(result.stderr || result.stdout || '').trim();
|
|
193
|
+
throw new Error(detail || `npm exited with status ${result.status}`);
|
|
194
|
+
}
|
|
144
195
|
}
|
|
145
|
-
|
|
146
196
|
export async function checkForUpdate(options = {}) {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
197
|
+
const current = options.currentVersion || getPackageVersion();
|
|
198
|
+
const latest = await latestPackageVersion(options);
|
|
199
|
+
return { current, latest, available: compareVersions(latest, current) > 0 };
|
|
150
200
|
}
|
|
151
|
-
|
|
152
201
|
export async function runSelfUpdate(verbose = false, options = {}) {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
202
|
+
const info = installationInfo(options);
|
|
203
|
+
if (!info.managed) {
|
|
204
|
+
if (verbose)
|
|
205
|
+
UI.printInfo('This is a source checkout. Update it with Git; Causyne will not rewrite developer source.');
|
|
206
|
+
return { updated: false, reason: 'source-checkout', ...info };
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
const status = await checkForUpdate(options);
|
|
210
|
+
if (!status.available) {
|
|
211
|
+
writeState({ checkedAt: Date.now(), latest: status.latest }, options);
|
|
212
|
+
if (verbose)
|
|
213
|
+
UI.printSuccess(`Causyne ${status.current} is up to date.`);
|
|
214
|
+
return { updated: false, reason: 'current', ...status, ...info };
|
|
215
|
+
}
|
|
216
|
+
if (verbose)
|
|
217
|
+
UI.printInfo(`Updating Causyne ${status.current} → ${status.latest}...`);
|
|
218
|
+
installLatest(info, { ...options, version: status.latest, verbose });
|
|
219
|
+
writeState({ checkedAt: Date.now(), latest: status.latest, installedAt: Date.now() }, options);
|
|
220
|
+
if (verbose)
|
|
221
|
+
UI.printSuccess(`Updated to Causyne ${status.latest}.`);
|
|
222
|
+
return { updated: true, ...status, ...info };
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
226
|
+
writeState({ checkedAt: Date.now(), error: message }, options);
|
|
227
|
+
if (verbose)
|
|
228
|
+
UI.printError(`Update failed: ${message}`);
|
|
229
|
+
return { updated: false, reason: 'failed', error: message, ...info };
|
|
230
|
+
}
|
|
177
231
|
}
|
|
178
|
-
|
|
179
|
-
/** Check on launch, at most once every six hours. */
|
|
232
|
+
/** Check on launch, defaulting to at most once per hour with fast retry on error. */
|
|
180
233
|
export async function startUpdateChecker(options = {}) {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
234
|
+
const env = options.env || process.env;
|
|
235
|
+
if (env.CAUSYNE_DISABLE_AUTOUPDATE === '1' || env.CAUSYNE_DISABLE_AUTOUPDATE === 'true') {
|
|
236
|
+
return {
|
|
237
|
+
updated: false,
|
|
238
|
+
reason: 'disabled',
|
|
239
|
+
managed: false,
|
|
240
|
+
type: 'source checkout',
|
|
241
|
+
prefix: null,
|
|
242
|
+
packageRoot: PACKAGE_ROOT,
|
|
243
|
+
npmCommand: resolveNpmExecutable(env)
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
const info = installationInfo(options);
|
|
247
|
+
if (!info.managed)
|
|
248
|
+
return { updated: false, reason: 'source-checkout', ...info };
|
|
249
|
+
const customInterval = Number(env.CAUSYNE_UPDATE_INTERVAL_MS);
|
|
250
|
+
const checkInterval = Number.isFinite(customInterval) && customInterval > 0
|
|
251
|
+
? customInterval
|
|
252
|
+
: DEFAULT_CHECK_INTERVAL_MS;
|
|
253
|
+
const state = readState(options);
|
|
254
|
+
if (!options.force && Number.isFinite(state.checkedAt)) {
|
|
255
|
+
const elapsed = Date.now() - state.checkedAt;
|
|
256
|
+
const intervalToUse = state.error ? ERROR_RETRY_INTERVAL_MS : checkInterval;
|
|
257
|
+
if (elapsed < intervalToUse) {
|
|
258
|
+
return { updated: false, reason: 'recently-checked', latest: state.latest, ...info };
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return runSelfUpdate(false, options);
|
|
196
262
|
}
|
|
197
|
-
|
|
198
263
|
export async function diagnoseInstallation(options = {}) {
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
264
|
+
const info = installationInfo(options);
|
|
265
|
+
let update;
|
|
266
|
+
try {
|
|
267
|
+
update = await checkForUpdate(options);
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
271
|
+
update = { current: getPackageVersion(), latest: null, available: false, error: message };
|
|
272
|
+
}
|
|
273
|
+
return {
|
|
274
|
+
...info,
|
|
275
|
+
...update,
|
|
276
|
+
autoUpdates: !['1', 'true'].includes(String((options.env || process.env).CAUSYNE_DISABLE_AUTOUPDATE || '').toLowerCase())
|
|
277
|
+
};
|
|
211
278
|
}
|
|
212
|
-
|
|
213
279
|
export function formatDoctorReport(status, runtime = process) {
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
280
|
+
const rows = [
|
|
281
|
+
`Version : ${status.current || 'unknown'}`,
|
|
282
|
+
`Latest : ${status.latest || `unavailable (${status.error || 'unknown error'})`}`,
|
|
283
|
+
`Installation : ${status.type}`,
|
|
284
|
+
`Package root : ${status.packageRoot}`,
|
|
285
|
+
`NPM command : ${status.npmCommand}`,
|
|
286
|
+
`Node.js : ${runtime.version}`,
|
|
287
|
+
`Platform : ${runtime.platform} ${runtime.arch}`,
|
|
288
|
+
`Auto updates : ${status.autoUpdates ? 'enabled' : 'disabled'}`,
|
|
289
|
+
`Workspace : ${runtime.cwd()}`
|
|
290
|
+
];
|
|
291
|
+
if (status.available)
|
|
292
|
+
rows.push('Update : available — run `causyne update`');
|
|
293
|
+
return rows.join('\n');
|
|
226
294
|
}
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
// Causyne package updates.
|
|
2
|
+
//
|
|
3
|
+
// Updates are intentionally limited to installations managed by npm or by the
|
|
4
|
+
// causyne.com installer. A source checkout is never rewritten. Commands are
|
|
5
|
+
// passed as argv arrays with shell disabled, and the only accepted package is
|
|
6
|
+
// the public @causyne/agent package from the npm registry.
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { spawnSync, type SpawnSyncReturns } from 'node:child_process';
|
|
12
|
+
|
|
13
|
+
import { UI } from './utils/cli_ui.js';
|
|
14
|
+
import { causyneHome } from './utils/paths.js';
|
|
15
|
+
import { getPackageVersion } from './version.js';
|
|
16
|
+
|
|
17
|
+
const PACKAGE_NAME = '@causyne/agent';
|
|
18
|
+
const REGISTRY_LATEST = 'https://registry.npmjs.org/@causyne%2fagent/latest';
|
|
19
|
+
const DEFAULT_CHECK_INTERVAL_MS = 60 * 60 * 1000; // 1 hour for active developer agility
|
|
20
|
+
const ERROR_RETRY_INTERVAL_MS = 2 * 60 * 1000; // 2 minutes retry on network error
|
|
21
|
+
const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
22
|
+
|
|
23
|
+
export interface VersionParts {
|
|
24
|
+
numbers: [number, number, number];
|
|
25
|
+
prerelease: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface InstallationInfo {
|
|
29
|
+
managed: boolean;
|
|
30
|
+
type: 'causyne.com installer' | 'global npm' | 'source checkout';
|
|
31
|
+
prefix: string | null;
|
|
32
|
+
packageRoot: string;
|
|
33
|
+
npmCommand: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface UpdateState {
|
|
37
|
+
checkedAt?: number;
|
|
38
|
+
latest?: string;
|
|
39
|
+
installedAt?: number;
|
|
40
|
+
error?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface CheckUpdateOptions {
|
|
44
|
+
currentVersion?: string;
|
|
45
|
+
fetchImpl?: typeof fetch;
|
|
46
|
+
timeoutMs?: number;
|
|
47
|
+
signal?: AbortSignal;
|
|
48
|
+
env?: NodeJS.ProcessEnv;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface SelfUpdateOptions extends CheckUpdateOptions {
|
|
52
|
+
force?: boolean;
|
|
53
|
+
stateFile?: string;
|
|
54
|
+
packageRoot?: string;
|
|
55
|
+
spawnSyncImpl?: (command: string, args: readonly string[], options: Record<string, unknown>) => SpawnSyncReturns<string | Buffer>;
|
|
56
|
+
verbose?: boolean;
|
|
57
|
+
version?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface CheckResult {
|
|
61
|
+
current: string;
|
|
62
|
+
latest: string;
|
|
63
|
+
available: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface UpdateResult extends InstallationInfo {
|
|
67
|
+
current?: string | undefined;
|
|
68
|
+
latest?: string | undefined;
|
|
69
|
+
available?: boolean | undefined;
|
|
70
|
+
updated: boolean;
|
|
71
|
+
reason?: 'disabled' | 'source-checkout' | 'recently-checked' | 'current' | 'failed' | undefined;
|
|
72
|
+
error?: string | undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface DiagnosisResult extends InstallationInfo {
|
|
76
|
+
current?: string | undefined;
|
|
77
|
+
latest?: string | null | undefined;
|
|
78
|
+
available?: boolean | undefined;
|
|
79
|
+
autoUpdates: boolean;
|
|
80
|
+
error?: string | undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function updateStateFile(options: { stateFile?: string; env?: NodeJS.ProcessEnv } = {}): string {
|
|
84
|
+
if (options.stateFile) return path.resolve(options.stateFile);
|
|
85
|
+
const env = options.env || process.env;
|
|
86
|
+
const root = env.CAUSYNE_HOME && String(env.CAUSYNE_HOME).trim()
|
|
87
|
+
? path.resolve(String(env.CAUSYNE_HOME).trim())
|
|
88
|
+
: causyneHome();
|
|
89
|
+
return path.join(root, 'update-state.json');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function versionParts(version: string | undefined): VersionParts | null {
|
|
93
|
+
const match = String(version || '').trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
|
|
94
|
+
if (!match) return null;
|
|
95
|
+
const num1 = Number(match[1]);
|
|
96
|
+
const num2 = Number(match[2]);
|
|
97
|
+
const num3 = Number(match[3]);
|
|
98
|
+
return { numbers: [num1, num2, num3], prerelease: match[4] || '' };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function compareVersions(left: string | undefined, right: string | undefined): number {
|
|
102
|
+
const a = versionParts(left);
|
|
103
|
+
const b = versionParts(right);
|
|
104
|
+
if (!a || !b) return 0;
|
|
105
|
+
for (let index = 0; index < 3; index++) {
|
|
106
|
+
const aNum = a.numbers[index] ?? 0;
|
|
107
|
+
const bNum = b.numbers[index] ?? 0;
|
|
108
|
+
if (aNum !== bNum) return aNum > bNum ? 1 : -1;
|
|
109
|
+
}
|
|
110
|
+
if (a.prerelease === b.prerelease) return 0;
|
|
111
|
+
if (!a.prerelease) return 1;
|
|
112
|
+
if (!b.prerelease) return -1;
|
|
113
|
+
const aParts = a.prerelease.split('.');
|
|
114
|
+
const bParts = b.prerelease.split('.');
|
|
115
|
+
const length = Math.max(aParts.length, bParts.length);
|
|
116
|
+
for (let index = 0; index < length; index++) {
|
|
117
|
+
const aPart = aParts[index];
|
|
118
|
+
const bPart = bParts[index];
|
|
119
|
+
if (aPart === undefined) return -1;
|
|
120
|
+
if (bPart === undefined) return 1;
|
|
121
|
+
if (aPart === bPart) continue;
|
|
122
|
+
const aNumeric = /^\d+$/.test(aPart);
|
|
123
|
+
const bNumeric = /^\d+$/.test(bPart);
|
|
124
|
+
if (aNumeric && bNumeric) return Number(aPart) > Number(bPart) ? 1 : -1;
|
|
125
|
+
if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
|
|
126
|
+
return aPart.localeCompare(bPart);
|
|
127
|
+
}
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function managedPrefix(packageRoot: string = PACKAGE_ROOT, env: NodeJS.ProcessEnv = process.env): string | null {
|
|
132
|
+
if (env.CAUSYNE_INSTALL_ROOT) return path.resolve(env.CAUSYNE_INSTALL_ROOT);
|
|
133
|
+
|
|
134
|
+
const markers = [
|
|
135
|
+
path.join('lib', 'node_modules', '@causyne', 'agent'),
|
|
136
|
+
path.join('node_modules', '@causyne', 'agent')
|
|
137
|
+
];
|
|
138
|
+
for (const marker of markers) {
|
|
139
|
+
const index = packageRoot.lastIndexOf(marker);
|
|
140
|
+
if (index >= 0 && index + marker.length === packageRoot.length) {
|
|
141
|
+
return packageRoot.slice(0, index).replace(/[\\/]$/, '');
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function resolveNpmExecutable(env: NodeJS.ProcessEnv = process.env): string {
|
|
148
|
+
if (env.CAUSYNE_NPM_COMMAND && String(env.CAUSYNE_NPM_COMMAND).trim()) {
|
|
149
|
+
return String(env.CAUSYNE_NPM_COMMAND).trim();
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const isWin = process.platform === 'win32';
|
|
153
|
+
const npmName = isWin ? 'npm.cmd' : 'npm';
|
|
154
|
+
|
|
155
|
+
// 1. Sibling of running node binary (most reliable across all Node version managers: nvm, fnm, volta, mise)
|
|
156
|
+
if (process.execPath) {
|
|
157
|
+
const sibling = path.join(path.dirname(process.execPath), npmName);
|
|
158
|
+
if (fs.existsSync(sibling)) {
|
|
159
|
+
return sibling;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// 2. Private Causyne runtime if provisioned
|
|
164
|
+
const privateNpm = path.join(causyneHome(), 'runtime', 'node', isWin ? '' : 'bin', npmName);
|
|
165
|
+
if (fs.existsSync(privateNpm)) {
|
|
166
|
+
return privateNpm;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 3. Default fallback to system PATH
|
|
170
|
+
return npmName;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function installationInfo(options: { env?: NodeJS.ProcessEnv; packageRoot?: string } = {}): InstallationInfo {
|
|
174
|
+
const env = options.env || process.env;
|
|
175
|
+
const packageRoot = options.packageRoot || PACKAGE_ROOT;
|
|
176
|
+
const prefix = managedPrefix(packageRoot, env);
|
|
177
|
+
const npmCommand = resolveNpmExecutable(env);
|
|
178
|
+
return {
|
|
179
|
+
managed: Boolean(prefix),
|
|
180
|
+
type: env.CAUSYNE_INSTALL_ROOT ? 'causyne.com installer' : (prefix ? 'global npm' : 'source checkout'),
|
|
181
|
+
prefix,
|
|
182
|
+
packageRoot,
|
|
183
|
+
npmCommand
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function readState(options: { stateFile?: string; env?: NodeJS.ProcessEnv } = {}): UpdateState {
|
|
188
|
+
try {
|
|
189
|
+
return JSON.parse(fs.readFileSync(updateStateFile(options), 'utf8')) as UpdateState;
|
|
190
|
+
} catch {
|
|
191
|
+
return {};
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function writeState(state: UpdateState, options: { stateFile?: string; env?: NodeJS.ProcessEnv } = {}): void {
|
|
196
|
+
try {
|
|
197
|
+
const stateFile = updateStateFile(options);
|
|
198
|
+
fs.mkdirSync(path.dirname(stateFile), { recursive: true, mode: 0o700 });
|
|
199
|
+
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), { mode: 0o600 });
|
|
200
|
+
} catch {
|
|
201
|
+
// Update state is an optimisation. Failure must never stop the CLI.
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export async function latestPackageVersion(options: CheckUpdateOptions = {}): Promise<string> {
|
|
206
|
+
const fetchImpl = options.fetchImpl || globalThis.fetch;
|
|
207
|
+
if (typeof fetchImpl !== 'function') throw new Error('This Node.js runtime has no fetch implementation.');
|
|
208
|
+
const timeoutMs = options.timeoutMs || 3500;
|
|
209
|
+
const signal = options.signal || AbortSignal.timeout(timeoutMs);
|
|
210
|
+
const response = await fetchImpl(REGISTRY_LATEST, {
|
|
211
|
+
headers: { accept: 'application/json', 'user-agent': `causyne/${getPackageVersion()}` },
|
|
212
|
+
signal
|
|
213
|
+
});
|
|
214
|
+
if (!response.ok) throw new Error(`npm registry returned HTTP ${response.status}`);
|
|
215
|
+
const metadata = (await response.json()) as { name?: string; version?: string };
|
|
216
|
+
if (metadata.name !== PACKAGE_NAME || !versionParts(metadata.version)) {
|
|
217
|
+
throw new Error('npm registry returned invalid package metadata');
|
|
218
|
+
}
|
|
219
|
+
return metadata.version as string;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function installLatest(info: InstallationInfo, options: SelfUpdateOptions = {}): void {
|
|
223
|
+
if (!info.prefix) {
|
|
224
|
+
throw new Error('Cannot install package: prefix is not defined for this installation.');
|
|
225
|
+
}
|
|
226
|
+
const runner = options.spawnSyncImpl || spawnSync;
|
|
227
|
+
const targetVersion = options.version;
|
|
228
|
+
if (!targetVersion) {
|
|
229
|
+
throw new Error('Target version must be specified for installation.');
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const args = [
|
|
233
|
+
'install', '--global', '--prefix', info.prefix,
|
|
234
|
+
`${PACKAGE_NAME}@${targetVersion}`, '--ignore-scripts', '--no-audit', '--no-fund'
|
|
235
|
+
];
|
|
236
|
+
|
|
237
|
+
// Prepend the directory containing node and npm to PATH so child npm executes smoothly
|
|
238
|
+
const env = { ...(options.env || process.env) };
|
|
239
|
+
const extraPaths = [path.dirname(process.execPath)];
|
|
240
|
+
if (info.npmCommand.includes('/') || info.npmCommand.includes('\\')) {
|
|
241
|
+
extraPaths.push(path.dirname(info.npmCommand));
|
|
242
|
+
}
|
|
243
|
+
const delimiter = process.platform === 'win32' ? ';' : ':';
|
|
244
|
+
const currentPath = env.PATH || env.Path || '';
|
|
245
|
+
env.PATH = [...extraPaths, currentPath].filter(Boolean).join(delimiter);
|
|
246
|
+
|
|
247
|
+
const result = runner(info.npmCommand, args, {
|
|
248
|
+
shell: false,
|
|
249
|
+
stdio: options.verbose ? 'inherit' : 'pipe',
|
|
250
|
+
encoding: 'utf8',
|
|
251
|
+
env
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
if (result.error) throw result.error;
|
|
255
|
+
if (result.status !== 0) {
|
|
256
|
+
const detail = String(result.stderr || result.stdout || '').trim();
|
|
257
|
+
throw new Error(detail || `npm exited with status ${result.status}`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export async function checkForUpdate(options: CheckUpdateOptions = {}): Promise<CheckResult> {
|
|
262
|
+
const current = options.currentVersion || getPackageVersion();
|
|
263
|
+
const latest = await latestPackageVersion(options);
|
|
264
|
+
return { current, latest, available: compareVersions(latest, current) > 0 };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export async function runSelfUpdate(verbose: boolean = false, options: SelfUpdateOptions = {}): Promise<UpdateResult> {
|
|
268
|
+
const info = installationInfo(options);
|
|
269
|
+
if (!info.managed) {
|
|
270
|
+
if (verbose) UI.printInfo('This is a source checkout. Update it with Git; Causyne will not rewrite developer source.');
|
|
271
|
+
return { updated: false, reason: 'source-checkout', ...info };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
try {
|
|
275
|
+
const status = await checkForUpdate(options);
|
|
276
|
+
if (!status.available) {
|
|
277
|
+
writeState({ checkedAt: Date.now(), latest: status.latest }, options);
|
|
278
|
+
if (verbose) UI.printSuccess(`Causyne ${status.current} is up to date.`);
|
|
279
|
+
return { updated: false, reason: 'current', ...status, ...info };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (verbose) UI.printInfo(`Updating Causyne ${status.current} → ${status.latest}...`);
|
|
283
|
+
installLatest(info, { ...options, version: status.latest, verbose });
|
|
284
|
+
writeState({ checkedAt: Date.now(), latest: status.latest, installedAt: Date.now() }, options);
|
|
285
|
+
if (verbose) UI.printSuccess(`Updated to Causyne ${status.latest}.`);
|
|
286
|
+
return { updated: true, ...status, ...info };
|
|
287
|
+
} catch (error) {
|
|
288
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
289
|
+
writeState({ checkedAt: Date.now(), error: message }, options);
|
|
290
|
+
if (verbose) UI.printError(`Update failed: ${message}`);
|
|
291
|
+
return { updated: false, reason: 'failed', error: message, ...info };
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Check on launch, defaulting to at most once per hour with fast retry on error. */
|
|
296
|
+
export async function startUpdateChecker(options: SelfUpdateOptions = {}): Promise<UpdateResult> {
|
|
297
|
+
const env = options.env || process.env;
|
|
298
|
+
if (env.CAUSYNE_DISABLE_AUTOUPDATE === '1' || env.CAUSYNE_DISABLE_AUTOUPDATE === 'true') {
|
|
299
|
+
return {
|
|
300
|
+
updated: false,
|
|
301
|
+
reason: 'disabled',
|
|
302
|
+
managed: false,
|
|
303
|
+
type: 'source checkout',
|
|
304
|
+
prefix: null,
|
|
305
|
+
packageRoot: PACKAGE_ROOT,
|
|
306
|
+
npmCommand: resolveNpmExecutable(env)
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const info = installationInfo(options);
|
|
311
|
+
if (!info.managed) return { updated: false, reason: 'source-checkout', ...info };
|
|
312
|
+
|
|
313
|
+
const customInterval = Number(env.CAUSYNE_UPDATE_INTERVAL_MS);
|
|
314
|
+
const checkInterval = Number.isFinite(customInterval) && customInterval > 0
|
|
315
|
+
? customInterval
|
|
316
|
+
: DEFAULT_CHECK_INTERVAL_MS;
|
|
317
|
+
|
|
318
|
+
const state = readState(options);
|
|
319
|
+
if (!options.force && Number.isFinite(state.checkedAt)) {
|
|
320
|
+
const elapsed = Date.now() - (state.checkedAt as number);
|
|
321
|
+
const intervalToUse = state.error ? ERROR_RETRY_INTERVAL_MS : checkInterval;
|
|
322
|
+
if (elapsed < intervalToUse) {
|
|
323
|
+
return { updated: false, reason: 'recently-checked', latest: state.latest, ...info };
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
return runSelfUpdate(false, options);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export async function diagnoseInstallation(options: CheckUpdateOptions = {}): Promise<DiagnosisResult> {
|
|
331
|
+
const info = installationInfo(options);
|
|
332
|
+
let update: CheckResult | { current: string; latest: null; available: false; error: string };
|
|
333
|
+
try {
|
|
334
|
+
update = await checkForUpdate(options);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
337
|
+
update = { current: getPackageVersion(), latest: null, available: false, error: message };
|
|
338
|
+
}
|
|
339
|
+
return {
|
|
340
|
+
...info,
|
|
341
|
+
...update,
|
|
342
|
+
autoUpdates: !['1', 'true'].includes(String((options.env || process.env).CAUSYNE_DISABLE_AUTOUPDATE || '').toLowerCase())
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function formatDoctorReport(status: DiagnosisResult, runtime: typeof process = process): string {
|
|
347
|
+
const rows = [
|
|
348
|
+
`Version : ${status.current || 'unknown'}`,
|
|
349
|
+
`Latest : ${status.latest || `unavailable (${status.error || 'unknown error'})`}`,
|
|
350
|
+
`Installation : ${status.type}`,
|
|
351
|
+
`Package root : ${status.packageRoot}`,
|
|
352
|
+
`NPM command : ${status.npmCommand}`,
|
|
353
|
+
`Node.js : ${runtime.version}`,
|
|
354
|
+
`Platform : ${runtime.platform} ${runtime.arch}`,
|
|
355
|
+
`Auto updates : ${status.autoUpdates ? 'enabled' : 'disabled'}`,
|
|
356
|
+
`Workspace : ${runtime.cwd()}`
|
|
357
|
+
];
|
|
358
|
+
if (status.available) rows.push('Update : available — run `causyne update`');
|
|
359
|
+
return rows.join('\n');
|
|
360
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface UIInterface {
|
|
2
|
+
colors: Record<string, string>;
|
|
3
|
+
box: Record<string, string>;
|
|
4
|
+
printHeader(title: string, subtitle?: string): void;
|
|
5
|
+
printCard(title: string, bodyLines: string | string[], highlight?: boolean): void;
|
|
6
|
+
printSuccess(msg: string): void;
|
|
7
|
+
printInfo(msg: string): void;
|
|
8
|
+
printWarning(msg: string): void;
|
|
9
|
+
printError(msg: string): void;
|
|
10
|
+
printFatalBox(title: string, lines: string[]): void;
|
|
11
|
+
createSpinner(text: string): {
|
|
12
|
+
start(): unknown;
|
|
13
|
+
stop(text?: string): void;
|
|
14
|
+
fail(text?: string): void;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export declare const UI: UIInterface;
|
|
19
|
+
export default UI;
|