@causyne/agent 1.20.19 → 1.20.22

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/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 CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
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
- if (options.stateFile) return path.resolve(options.stateFile);
24
- const env = options.env || process.env;
25
- const root = env.CAUSYNE_HOME && String(env.CAUSYNE_HOME).trim()
26
- ? path.resolve(String(env.CAUSYNE_HOME).trim())
27
- : causyneHome();
28
- return path.join(root, 'update-state.json');
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
- function versionParts(version) {
32
- const match = String(version || '').trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
33
- if (!match) return null;
34
- return { numbers: match.slice(1, 4).map(Number), prerelease: match[4] || '' };
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
- const a = versionParts(left);
39
- const b = versionParts(right);
40
- if (!a || !b) return 0;
41
- for (let index = 0; index < 3; index++) {
42
- if (a.numbers[index] !== b.numbers[index]) return a.numbers[index] > b.numbers[index] ? 1 : -1;
43
- }
44
- if (a.prerelease === b.prerelease) return 0;
45
- if (!a.prerelease) return 1;
46
- if (!b.prerelease) return -1;
47
- const aParts = a.prerelease.split('.');
48
- const bParts = b.prerelease.split('.');
49
- const length = Math.max(aParts.length, bParts.length);
50
- for (let index = 0; index < length; index++) {
51
- if (aParts[index] === undefined) return -1;
52
- if (bParts[index] === undefined) return 1;
53
- if (aParts[index] === bParts[index]) continue;
54
- const aNumeric = /^\d+$/.test(aParts[index]);
55
- const bNumeric = /^\d+$/.test(bParts[index]);
56
- if (aNumeric && bNumeric) return Number(aParts[index]) > Number(bParts[index]) ? 1 : -1;
57
- if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
58
- return aParts[index].localeCompare(bParts[index]);
59
- }
60
- return 0;
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
- if (env.CAUSYNE_INSTALL_ROOT) return path.resolve(env.CAUSYNE_INSTALL_ROOT);
65
-
66
- const markers = [
67
- path.join('lib', 'node_modules', '@causyne', 'agent'),
68
- path.join('node_modules', '@causyne', 'agent')
69
- ];
70
- for (const marker of markers) {
71
- const index = packageRoot.lastIndexOf(marker);
72
- if (index >= 0 && index + marker.length === packageRoot.length) {
73
- return packageRoot.slice(0, index).replace(/[\\/]$/, '');
74
- }
75
- }
76
- return null;
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
- const env = options.env || process.env;
81
- const packageRoot = options.packageRoot || PACKAGE_ROOT;
82
- const prefix = managedPrefix(packageRoot, env);
83
- return {
84
- managed: Boolean(prefix),
85
- type: env.CAUSYNE_INSTALL_ROOT ? 'causyne.com installer' : (prefix ? 'global npm' : 'source checkout'),
86
- prefix,
87
- packageRoot,
88
- npmCommand: env.CAUSYNE_NPM_COMMAND || (process.platform === 'win32' ? 'npm.cmd' : 'npm')
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
- try {
94
- return JSON.parse(fs.readFileSync(updateStateFile(options), 'utf8'));
95
- } catch {
96
- return {};
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
- try {
102
- const stateFile = updateStateFile(options);
103
- fs.mkdirSync(path.dirname(stateFile), { recursive: true, mode: 0o700 });
104
- fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), { mode: 0o600 });
105
- } catch {
106
- // Update state is an optimisation. Failure must never stop the CLI.
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
- const fetchImpl = options.fetchImpl || globalThis.fetch;
112
- if (typeof fetchImpl !== 'function') throw new Error('This Node.js runtime has no fetch implementation.');
113
- const timeoutMs = options.timeoutMs || 3500;
114
- const signal = options.signal || AbortSignal.timeout(timeoutMs);
115
- const response = await fetchImpl(REGISTRY_LATEST, {
116
- headers: { accept: 'application/json', 'user-agent': `causyne/${getPackageVersion()}` },
117
- signal
118
- });
119
- if (!response.ok) throw new Error(`npm registry returned HTTP ${response.status}`);
120
- const metadata = await response.json();
121
- if (metadata.name !== PACKAGE_NAME || !versionParts(metadata.version)) {
122
- throw new Error('npm registry returned invalid package metadata');
123
- }
124
- return metadata.version;
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
- const runner = options.spawnSyncImpl || spawnSync;
129
- const args = [
130
- 'install', '--global', '--prefix', info.prefix,
131
- `${PACKAGE_NAME}@${options.version}`, '--ignore-scripts', '--no-audit', '--no-fund'
132
- ];
133
- const result = runner(info.npmCommand, args, {
134
- shell: false,
135
- stdio: options.verbose ? 'inherit' : 'pipe',
136
- encoding: 'utf8',
137
- env: options.env || process.env
138
- });
139
- if (result.error) throw result.error;
140
- if (result.status !== 0) {
141
- const detail = String(result.stderr || result.stdout || '').trim();
142
- throw new Error(detail || `npm exited with status ${result.status}`);
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
- const current = options.currentVersion || getPackageVersion();
148
- const latest = await latestPackageVersion(options);
149
- return { current, latest, available: compareVersions(latest, current) > 0 };
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
- const info = installationInfo(options);
154
- if (!info.managed) {
155
- if (verbose) UI.printInfo('This is a source checkout. Update it with Git; Causyne will not rewrite developer source.');
156
- return { updated: false, reason: 'source-checkout', ...info };
157
- }
158
-
159
- try {
160
- const status = await checkForUpdate(options);
161
- if (!status.available) {
162
- writeState({ checkedAt: Date.now(), latest: status.latest }, options);
163
- if (verbose) UI.printSuccess(`Causyne ${status.current} is up to date.`);
164
- return { updated: false, reason: 'current', ...status, ...info };
165
- }
166
-
167
- if (verbose) UI.printInfo(`Updating Causyne ${status.current} → ${status.latest}...`);
168
- installLatest(info, { ...options, version: status.latest, verbose });
169
- writeState({ checkedAt: Date.now(), latest: status.latest, installedAt: Date.now() }, options);
170
- if (verbose) UI.printSuccess(`Updated to Causyne ${status.latest}.`);
171
- return { updated: true, ...status, ...info };
172
- } catch (error) {
173
- writeState({ checkedAt: Date.now(), error: error.message }, options);
174
- if (verbose) UI.printError(`Update failed: ${error.message}`);
175
- return { updated: false, reason: 'failed', error: error.message, ...info };
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
- const env = options.env || process.env;
182
- if (env.CAUSYNE_DISABLE_AUTOUPDATE === '1' || env.CAUSYNE_DISABLE_AUTOUPDATE === 'true') {
183
- return { updated: false, reason: 'disabled' };
184
- }
185
-
186
- const info = installationInfo(options);
187
- if (!info.managed) return { updated: false, reason: 'source-checkout', ...info };
188
-
189
- const state = readState(options);
190
- if (!options.force && Number.isFinite(state.checkedAt)
191
- && Date.now() - state.checkedAt < CHECK_INTERVAL_MS) {
192
- return { updated: false, reason: 'recently-checked', latest: state.latest, ...info };
193
- }
194
-
195
- return runSelfUpdate(false, options);
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
- const info = installationInfo(options);
200
- let update;
201
- try {
202
- update = await checkForUpdate(options);
203
- } catch (error) {
204
- update = { current: getPackageVersion(), latest: null, available: false, error: error.message };
205
- }
206
- return {
207
- ...info,
208
- ...update,
209
- autoUpdates: !['1', 'true'].includes(String((options.env || process.env).CAUSYNE_DISABLE_AUTOUPDATE || '').toLowerCase())
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
- const rows = [
215
- `Version : ${status.current}`,
216
- `Latest : ${status.latest || `unavailable (${status.error || 'unknown error'})`}`,
217
- `Installation : ${status.type}`,
218
- `Package root : ${status.packageRoot}`,
219
- `Node.js : ${runtime.version}`,
220
- `Platform : ${runtime.platform} ${runtime.arch}`,
221
- `Auto updates : ${status.autoUpdates ? 'enabled' : 'disabled'}`,
222
- `Workspace : ${runtime.cwd()}`
223
- ];
224
- if (status.available) rows.push('Update : available — run `causyne update`');
225
- return rows.join('\n');
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
  }