ai-agentmanager 1.42.0 → 1.44.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.
package/src/update.js CHANGED
@@ -22,6 +22,36 @@ const run = (cmd, args, { cwd = root, timeoutMs = 120_000 } = {}) =>
22
22
  });
23
23
  });
24
24
 
25
+ /** Like run, with each line of output (stdout and stderr) passed to `onLine` as it comes. */
26
+ const runLines = (cmd, args, { cwd = root, timeoutMs = 120_000, onLine = () => {} } = {}) =>
27
+ new Promise((resolve, reject) => {
28
+ const child = spawn(cmd, args, { cwd, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
29
+ let tail = '';
30
+ let buf = '';
31
+ const feed = (d) => {
32
+ buf += d;
33
+ const lines = buf.split(/\r?\n/);
34
+ buf = lines.pop();
35
+ for (const line of lines.map((l) => l.trim()).filter(Boolean)) {
36
+ tail = `${tail}\n${line}`.slice(-4000);
37
+ onLine(line);
38
+ }
39
+ };
40
+ const timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
41
+ child.stdout.on('data', feed);
42
+ child.stderr.on('data', feed);
43
+ const fail = (why) => reject(Object.assign(new Error(`${cmd} ${args.join(' ')}: ${why}`), { status: 500 }));
44
+ child.on('error', (e) => (clearTimeout(timer), fail(e.message)));
45
+ child.on('close', (code, signal) => {
46
+ clearTimeout(timer);
47
+ if (code === 0) return resolve(tail.trim());
48
+ // npm's own summary of what went wrong, not the progress lines around it.
49
+ const lines = `${tail}\n${buf}`.split('\n').filter(Boolean);
50
+ const errors = lines.filter((l) => /^npm (error|ERR!)/.test(l));
51
+ fail(signal ? `stopped after ${Math.round(timeoutMs / 1000)} s without finishing` : (errors.length ? errors.slice(0, 3).join('; ') : lines.pop() ?? `exit ${code}`));
52
+ });
53
+ });
54
+
25
55
  const pkg = (dir = root) => JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
26
56
 
27
57
  /** The newest release tag (vX.Y.Z, no pre-releases) among `tags`, or null. */
@@ -61,9 +91,12 @@ export async function checkUpdate({ dir = root, fetchTags = true } = {}) {
61
91
  return { kind, current, latest: r.latest, newer: r.newer, blocker: null, checkedAt: new Date().toISOString() };
62
92
  }
63
93
 
64
- /** Put the newest release in place (no restart). Returns { from, to } or { upToDate }. */
65
- export async function installUpdate({ dir = root, log = () => {} } = {}) {
66
- const info = await checkUpdate({ dir });
94
+ /**
95
+ * Put the newest release in place (no restart). Returns { from, to } or { upToDate }. `info`: a
96
+ * check made just now, to skip making another; `onLine`: the installer's output as it comes.
97
+ */
98
+ export async function installUpdate({ dir = root, log = () => {}, onLine = () => {}, info = null } = {}) {
99
+ info ??= await checkUpdate({ dir });
67
100
  if (!info.newer) return { upToDate: true, current: info.current };
68
101
  if (info.blocker) throw err(409, info.blocker);
69
102
  if (info.kind === 'git') {
@@ -73,12 +106,13 @@ export async function installUpdate({ dir = root, log = () => {} } = {}) {
73
106
  const lockAfter = await run('git', ['rev-parse', 'HEAD:package-lock.json'], { cwd: dir }).catch(() => '');
74
107
  if (lockAfter !== lockBefore || !fs.existsSync(path.join(dir, 'node_modules'))) {
75
108
  log('installing dependencies');
76
- await run('npm', ['install', '--no-audit', '--no-fund'], { cwd: dir, timeoutMs: 600_000 });
109
+ await runLines('npm', ['install', '--no-audit', '--no-fund', '--loglevel=http'], { cwd: dir, timeoutMs: 600_000, onLine });
77
110
  }
78
111
  } else {
79
112
  const name = pkg(dir).name;
80
113
  log(`npm install -g ${name}@${info.latest}`);
81
- await run('npm', ['install', '-g', `${name}@${info.latest}`], { timeoutMs: 600_000 }).catch((e) => {
114
+ // --loglevel=http: a line per package fetched, so a long install shows that it is moving.
115
+ await runLines('npm', ['install', '-g', `${name}@${info.latest}`, '--no-audit', '--no-fund', '--loglevel=http'], { timeoutMs: 600_000, onLine }).catch((e) => {
82
116
  throw err(500, `${e.message}${/EACCES|permission/i.test(e.message) ? ' (npm needs write access to its global folder)' : ''}`);
83
117
  });
84
118
  }
@@ -100,6 +134,7 @@ export class Updates {
100
134
  this.check = check;
101
135
  this.last = null;
102
136
  this.busy = null;
137
+ this.progress = null;
103
138
  this.schedule();
104
139
  }
105
140
 
@@ -139,22 +174,55 @@ export class Updates {
139
174
  }
140
175
 
141
176
  status() {
142
- return { check: this.enabled, updating: Boolean(this.busy), ...(this.last ?? {}) };
177
+ return { check: this.enabled, updating: Boolean(this.busy), progress: this.progress, ...(this.last ?? {}) };
143
178
  }
144
179
 
145
- /** Install the newest release, then restart onto it. Answers before the restart begins. */
146
- async apply({ restart = restartDetached } = {}) {
180
+ /**
181
+ * Install the newest release, then restart onto it. Answers once it knows there is something to
182
+ * install ({ started, from, to }); the install goes on in the background and status().progress
183
+ * says where it is: step "install" (with the installer's last line and how many packages it
184
+ * fetched), "restart", or "failed" with the error.
185
+ */
186
+ async apply({ restart = restartDetached, install = installUpdate, check = checkUpdate } = {}) {
147
187
  if (this.busy) throw err(409, 'An update is already running');
148
- this.busy = installUpdate({ log: (m) => this.log(`update: ${m}`) });
188
+ this.busy = true; // held through the check, so a second click can't start another
189
+ let info;
149
190
  try {
150
- const r = await this.busy;
151
- if (r.upToDate) return r;
152
- this.log(`update: ${r.from} → ${r.to} installed; restarting`);
153
- this.last = { ...(this.last ?? {}), current: r.to, newer: false };
154
- setTimeout(restart, 200);
155
- return { ...r, restarting: true };
156
- } finally {
191
+ info = await check();
192
+ } catch (e) {
193
+ this.busy = null;
194
+ throw e;
195
+ }
196
+ this.last = info;
197
+ if (!info.newer || info.blocker) {
157
198
  this.busy = null;
199
+ if (info.blocker) throw err(409, info.blocker);
200
+ return { upToDate: true, current: info.current };
158
201
  }
202
+ const p = { step: 'install', from: info.current, to: info.latest, kind: info.kind, startedAt: new Date().toISOString(), detail: '', fetched: 0, error: null };
203
+ this.progress = p;
204
+ this.busy = install({
205
+ info,
206
+ log: (m) => {
207
+ p.detail = m;
208
+ this.log(`update: ${m}`);
209
+ },
210
+ onLine: (line) => {
211
+ if (/^npm http /.test(line)) p.fetched++;
212
+ else if (!/^npm notice/.test(line)) p.detail = line.slice(0, 200);
213
+ },
214
+ })
215
+ .then((r) => {
216
+ this.log(`update: ${r.from} → ${r.to} installed; restarting`);
217
+ this.last = { ...(this.last ?? {}), current: r.to, newer: false };
218
+ Object.assign(p, { step: 'restart', detail: '', installedAt: new Date().toISOString() });
219
+ setTimeout(restart, 200);
220
+ })
221
+ .catch((e) => {
222
+ this.log(`update: failed: ${e.message}`);
223
+ Object.assign(p, { step: 'failed', error: e.message, manual: info.kind === 'npm' ? `npm install -g ${pkg().name}@${info.latest} && agentmgr restart` : null });
224
+ })
225
+ .finally(() => (this.busy = null));
226
+ return { started: true, from: info.current, to: info.latest };
159
227
  }
160
228
  }