ai-agentmanager 1.41.0 → 1.43.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/server.js CHANGED
@@ -57,6 +57,7 @@ import { BugHunts } from './bughunt.js';
57
57
  import { ModuleBenchmarks } from './benchmarks.js';
58
58
  import { Evals, readTail, stateHash } from './eval.js';
59
59
  import { engineOf } from './engines/index.js';
60
+ import { Mcp } from './mcp.js';
60
61
  import * as git from './git.js';
61
62
 
62
63
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -181,6 +182,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
181
182
  const review = new Review({ manager });
182
183
  // The walkthrough explains the same diff the review screen shows.
183
184
  manager.changesSource = (id) => review.get(id);
185
+ const mcp = new Mcp({ manager });
184
186
  const studio = new Studio({ manager, review });
185
187
  const teams = new Teams({ manager, store, config });
186
188
  const cleanup = new Cleanup({ manager, store, config, teams });
@@ -955,6 +957,14 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
955
957
  // Your action on issues: assign (starts an agent from the proposal), skip, done, remove, or null to clear.
956
958
  api.post('/issues/action', wrap((req) => proposed.setAction(Array.isArray(req.body?.keys) ? req.body.keys.map(String) : [], req.body?.action ?? null, { until: req.body?.until ?? null })));
957
959
  // Design docs of all agents; the same ?group= and ?format=markdown.
960
+ // MCP servers and their tools as Claude Code sees them in an agent's folder (or the home folder), in that
961
+ // folder's own MCP session: listing, signing in, reconnecting one, and running a tool.
962
+ api.get('/mcp', wrap((req) => mcp.list(req.query.agent, { refresh: req.query.refresh === '1' })));
963
+ api.post('/mcp/run', wrap((req) => mcp.run(req.body?.agent, req.body ?? {})));
964
+ api.post('/mcp/reconnect', wrap((req) => mcp.reconnect(req.body?.agent, req.body?.server)));
965
+ // Signing in: Claude Code runs the OAuth flow and keeps the tokens; this only hands over the address to open.
966
+ api.post('/mcp/signin', wrap((req) => mcp.signIn(req.body?.agent, req.body?.server)));
967
+ api.post('/mcp/signin/callback', wrap((req) => mcp.signInCallback(req.body?.agent, req.body?.server, req.body?.url)));
958
968
  api.get('/designs', wrap((req) => {
959
969
  const v = manager.designs();
960
970
  const group = req.query.group ? String(req.query.group) : null;
@@ -1426,6 +1436,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1426
1436
  // ---------------------------------------------------------- listeners
1427
1437
 
1428
1438
  const server = http.createServer(app);
1439
+ // The MCP sessions are processes of ours: they end with the server.
1440
+ server.on('close', () => mcp.close());
1429
1441
  // Outlive clients' idle keep-alive sockets (Node fetch keeps them ~4s+): with the 5s
1430
1442
  // default, a request sent on a socket just as the server closes it fails with ECONNRESET.
1431
1443
  server.keepAliveTimeout = 65_000;
@@ -1483,6 +1495,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1483
1495
  budgets.close();
1484
1496
  playbooks.close();
1485
1497
  updates.close();
1498
+ mcp.close();
1486
1499
  assistant.close();
1487
1500
  console.log(`[agentmgr] shutting down (${reason}); closing agents so their sessions are saved`);
1488
1501
  builder.stopAll();
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
  }