ai-agentmanager 1.42.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/mcp.js CHANGED
@@ -1,13 +1,18 @@
1
1
  // MCP servers and their tools as Claude Code sees them in a folder: user, project and local
2
- // servers, claude.ai connectors and plugins' servers. Listed through Claude Code's own control
3
- // protocol (no model call), and run in an agent's session, or once in its workspace with only
4
- // that one tool allowed.
2
+ // servers, claude.ai connectors and plugins' servers. Each folder gets its own MCP session: one
3
+ // Claude Code process, apart from any agent's, spoken to through Claude Code's control protocol.
4
+ // It lists the servers, signs in to one, reconnects one and calls a tool directly, all without a
5
+ // model call. A tool can also run in an agent's session, or once through Claude Code (which works
6
+ // out the arguments from plain words) with only that tool allowed.
5
7
  import os from 'node:os';
6
8
  import { spawn } from 'node:child_process';
7
9
  import { DEFAULT_ENGINE, ENGINES } from './engines/index.js';
8
10
 
9
- export const LIST_TTL_MS = 5 * 60_000;
11
+ /** An MCP session closes after this long unused (it starts again when next asked). */
12
+ export const IDLE_MS = 15 * 60_000;
10
13
  const RUN_TIMEOUT_MS = 5 * 60_000;
14
+ const KEEP_RUNS = 30;
15
+ const err = (status, message) => Object.assign(new Error(message), { status });
11
16
 
12
17
  /** Claude Code's name for a tool: mcp__<server>__<tool>, other characters in the server name as "_". */
13
18
  export const toolId = (server, tool) => `mcp__${String(server).replace(/[^\w-]/g, '_')}__${tool}`;
@@ -37,15 +42,18 @@ export function targetOf(config = {}) {
37
42
 
38
43
  /** One server for the UI: no env, headers or other config values. */
39
44
  export function serverView(s) {
45
+ const transport = s.transport ?? s.config?.type ?? null;
40
46
  return {
41
47
  name: String(s.name),
42
48
  status: s.status ?? 'unknown',
43
49
  scope: s.scope ?? null,
44
50
  source: s.source ?? null,
45
- transport: s.transport ?? s.config?.type ?? null,
51
+ transport,
46
52
  target: targetOf(s.config),
47
53
  version: s.serverInfo?.version ?? null,
48
54
  error: s.error ? String(s.error).slice(0, 300) : null,
55
+ // Signing in is OAuth, which only servers reached over HTTP have.
56
+ canSignIn: ['http', 'sse', 'claudeai-proxy'].includes(transport) || Boolean(s.config?.url),
49
57
  tools: (s.tools ?? []).map((t) => ({
50
58
  name: String(t.name),
51
59
  id: toolId(s.name, t.name),
@@ -56,34 +64,54 @@ export function serverView(s) {
56
64
  };
57
65
  }
58
66
 
67
+ /** What a tool returned, as text: its text parts, other parts named, and whether it reported an error. */
68
+ export function resultText(result = {}) {
69
+ const parts = (result.content ?? []).map((c) =>
70
+ c.type === 'text' ? String(c.text ?? '') : c.type === 'resource' ? String(c.resource?.text ?? `[resource ${c.resource?.uri ?? ''}]`) : `[${c.type ?? 'content'}${c.mimeType ? ` ${c.mimeType}` : ''}]`,
71
+ );
72
+ if (!parts.length && result.structuredContent !== undefined) parts.push(JSON.stringify(result.structuredContent, null, 2));
73
+ return { text: parts.join('\n').slice(0, 200_000) || '(no output)', isError: result.isError === true };
74
+ }
75
+
76
+ /**
77
+ * The arguments typed for a direct call: empty or a JSON object means "call it with these"; anything
78
+ * else is a request in plain words, for Claude Code to work the arguments out from.
79
+ */
80
+ export function parseArgs(input) {
81
+ const text = String(input ?? '').trim();
82
+ if (!text) return {};
83
+ if (!text.startsWith('{')) return null;
84
+ try {
85
+ const v = JSON.parse(text);
86
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
59
92
  /**
60
- * Ask Claude Code in `cwd` for its MCP servers: start it in stream-json mode, initialize, and ask
61
- * for their status until none is still connecting. No message is sent, so no model call is made.
93
+ * One folder's MCP session: a Claude Code process in stream-json mode that is only ever sent
94
+ * control requests (never a message, so it makes no model call). It stays up between requests, so
95
+ * servers stay connected and a sign-in's callback has somewhere to land.
62
96
  */
63
- export function mcpStatus({ bin, args = [], cwd, env, timeoutMs = 30_000 }) {
64
- return new Promise((resolve, reject) => {
65
- const child = spawn(bin, [...args, '-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--no-session-persistence'], {
97
+ export class McpSession {
98
+ constructor({ bin, args = [], cwd, env, onClose = () => {} }) {
99
+ this.waiting = new Map(); // request id -> { resolve, reject, timer }
100
+ this.n = 0;
101
+ this.closed = false;
102
+ this.startedAt = Date.now();
103
+ this.usedAt = Date.now();
104
+ this.child = spawn(bin, [...args, '-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--no-session-persistence'], {
66
105
  cwd,
67
106
  env,
68
107
  stdio: ['pipe', 'pipe', 'pipe'],
69
108
  });
109
+ // An idle session never keeps the daemon from exiting; it ends when its input closes.
110
+ this.child.unref();
111
+ for (const pipe of [this.child.stdin, this.child.stdout, this.child.stderr]) pipe.unref?.();
70
112
  let buf = '';
71
- let err = '';
72
- let last = null;
73
- let n = 0;
74
- let done = false;
75
- let poll = null;
76
- const finish = (fn, value) => {
77
- if (done) return;
78
- done = true;
79
- clearTimeout(timer);
80
- clearTimeout(poll);
81
- child.kill();
82
- fn(value);
83
- };
84
- const send = (request) => child.stdin.write(`${JSON.stringify({ type: 'control_request', request_id: `r${++n}`, request })}\n`);
85
- const timer = setTimeout(() => (last ? finish(resolve, last) : finish(reject, new Error('Claude Code did not list its MCP servers in time'))), timeoutMs);
86
- child.stdout.on('data', (d) => {
113
+ let stderr = '';
114
+ this.child.stdout.on('data', (d) => {
87
115
  buf += d;
88
116
  const lines = buf.split('\n');
89
117
  buf = lines.pop();
@@ -96,27 +124,85 @@ export function mcpStatus({ bin, args = [], cwd, env, timeoutMs = 30_000 }) {
96
124
  }
97
125
  if (m.type !== 'control_response') continue;
98
126
  const r = m.response ?? {};
99
- if (r.subtype === 'error') return finish(reject, new Error(`Claude Code: ${r.error ?? 'error'}`));
100
- if (r.request_id === 'r1') {
101
- send({ subtype: 'mcp_status' });
102
- continue;
103
- }
104
- const servers = r.response?.mcpServers;
105
- if (!Array.isArray(servers)) continue;
106
- last = servers;
107
- if (servers.some((s) => s.status === 'pending')) poll = setTimeout(() => send({ subtype: 'mcp_status' }), 1000);
108
- else finish(resolve, servers);
127
+ const w = this.waiting.get(r.request_id);
128
+ if (!w) continue;
129
+ this.waiting.delete(r.request_id);
130
+ clearTimeout(w.timer);
131
+ if (r.subtype === 'error') w.reject(err(502, String(r.error ?? 'Claude Code refused the request')));
132
+ else w.resolve(r.response ?? {});
109
133
  }
110
134
  });
111
- child.stderr.on('data', (d) => (err += d));
112
- child.stdin.on('error', () => {});
113
- child.on('error', (e) => finish(reject, e));
114
- child.on('close', (code) => (last ? finish(resolve, last) : finish(reject, new Error(`Claude Code stopped before listing its MCP servers (exit ${code}): ${err.trim().slice(-300)}`))));
115
- send({ subtype: 'initialize' });
116
- });
135
+ this.child.stderr.on('data', (d) => (stderr = `${stderr}${d}`.slice(-2000)));
136
+ this.child.stdin.on('error', () => {});
137
+ const end = (why) => {
138
+ if (this.closed) return;
139
+ this.closed = true;
140
+ for (const w of this.waiting.values()) {
141
+ clearTimeout(w.timer);
142
+ w.reject(err(502, why));
143
+ }
144
+ this.waiting.clear();
145
+ onClose();
146
+ };
147
+ this.child.on('error', (e) => end(`Claude Code could not start: ${e.message}`));
148
+ this.child.on('close', (code) => end(`Claude Code's MCP session stopped (exit ${code})${stderr.trim() ? `: ${stderr.trim().slice(-300)}` : ''}`));
149
+ this.ready = this.request({ subtype: 'initialize' }, 30_000);
150
+ this.ready.catch(() => this.close());
151
+ }
152
+
153
+ request(request, timeoutMs = 30_000) {
154
+ if (this.closed) return Promise.reject(err(502, "Claude Code's MCP session has stopped; refresh the list"));
155
+ this.usedAt = Date.now();
156
+ const id = `r${++this.n}`;
157
+ return new Promise((resolve, reject) => {
158
+ const timer = setTimeout(() => {
159
+ this.waiting.delete(id);
160
+ reject(err(504, `Claude Code did not answer (${request.subtype}) in ${Math.round(timeoutMs / 1000)} s`));
161
+ }, timeoutMs);
162
+ this.waiting.set(id, { resolve, reject, timer });
163
+ this.child.stdin.write(`${JSON.stringify({ type: 'control_request', request_id: id, request })}\n`);
164
+ });
165
+ }
166
+
167
+ /** The servers, asked again while any is still connecting (up to `waitMs`). */
168
+ async status({ waitMs = 20_000 } = {}) {
169
+ await this.ready;
170
+ const until = Date.now() + waitMs;
171
+ for (;;) {
172
+ const servers = (await this.request({ subtype: 'mcp_status' })).mcpServers ?? [];
173
+ if (!servers.some((s) => s.status === 'pending') || Date.now() > until) return servers;
174
+ await new Promise((r) => setTimeout(r, 700));
175
+ }
176
+ }
177
+
178
+ async call(tool, args, timeoutMs = RUN_TIMEOUT_MS) {
179
+ await this.ready;
180
+ return this.request({ subtype: 'mcp_call', tool, arguments: args }, timeoutMs);
181
+ }
182
+
183
+ async reconnect(serverName) {
184
+ await this.ready;
185
+ return this.request({ subtype: 'mcp_reconnect', serverName }, 60_000);
186
+ }
187
+
188
+ /** Start signing in: { authUrl, callbackExpected, callbackPort } (the callback lands on this process). */
189
+ async authenticate(serverName) {
190
+ await this.ready;
191
+ return this.request({ subtype: 'mcp_authenticate', serverName }, 60_000);
192
+ }
193
+
194
+ /** The address the sign-in ended on, when its redirect could not reach this computer. */
195
+ async callback(serverName, callbackUrl) {
196
+ await this.ready;
197
+ return this.request({ subtype: 'mcp_oauth_callback_url', serverName, callbackUrl }, 60_000);
198
+ }
199
+
200
+ close() {
201
+ if (!this.closed) this.child.kill();
202
+ }
117
203
  }
118
204
 
119
- /** The one-off call in a workspace: use the tool for the request, and report what it returned. */
205
+ /** The one-off call through Claude Code: use the tool for the request, and report what it returned. */
120
206
  export function runPrompt(id, input) {
121
207
  return [
122
208
  `Use the MCP tool ${id} for the request below, calling it as few times as needed (once if you can).`,
@@ -133,10 +219,17 @@ export function runPrompt(id, input) {
133
219
  export const sessionMessage = (id, input) => `Use the MCP tool ${id}${input?.trim() ? ` for this: ${input.trim()}` : ''}. Show me what it returned.`;
134
220
 
135
221
  export class Mcp {
136
- constructor({ manager, homeDir = os.homedir() }) {
222
+ constructor({ manager, homeDir = os.homedir(), idleMs = IDLE_MS }) {
137
223
  this.manager = manager;
138
224
  this.homeDir = homeDir;
139
- this.cache = new Map(); // folder -> { at, servers } | { pending }
225
+ this.idleMs = idleMs;
226
+ this.sessions = new Map(); // folder -> McpSession
227
+ this.lists = new Map(); // folder -> { at, servers }
228
+ this.runs = new Map(); // folder -> the last runs, newest first
229
+ this.sweep = setInterval(() => {
230
+ for (const s of this.sessions.values()) if (Date.now() - s.usedAt > this.idleMs && !s.waiting.size) s.close();
231
+ }, 60_000);
232
+ this.sweep.unref?.();
140
233
  }
141
234
 
142
235
  /** Where the tools run: an agent's folder, or the home folder (user servers and connectors). */
@@ -146,63 +239,143 @@ export class Mcp {
146
239
  return { agent, dir: agent.workdir ?? agent.planning?.dir ?? this.homeDir };
147
240
  }
148
241
 
149
- async list(ref, { refresh = false } = {}) {
150
- const { agent, dir } = this.where(ref);
151
- let hit = this.cache.get(dir);
152
- if (refresh || !hit || (hit.at && Date.now() - hit.at > LIST_TTL_MS) || hit.error) {
153
- if (!hit?.pending) {
154
- const engine = ENGINES[DEFAULT_ENGINE];
155
- const pending = mcpStatus({ bin: engine.bin(this.manager.config), args: engine.extraArgs(this.manager.config), cwd: dir, env: this.manager.childEnv(agent) })
156
- .then((servers) => ({ at: Date.now(), servers: servers.map(serverView).sort((a, b) => a.name.localeCompare(b.name)) }))
157
- .catch((e) => ({ at: Date.now(), servers: [], error: e.message }));
158
- hit = { pending };
159
- this.cache.set(dir, hit);
160
- pending.then((r) => this.cache.set(dir, r));
161
- }
162
- hit = await this.cache.get(dir).pending;
242
+ /** The folder's MCP session, started if it has none (or `fresh`: a new one, which reads the configuration again). */
243
+ session(agent, dir, { fresh = false } = {}) {
244
+ let s = this.sessions.get(dir);
245
+ if (s && (fresh || s.closed)) {
246
+ s.close();
247
+ s = null;
248
+ }
249
+ if (!s) {
250
+ const engine = ENGINES[DEFAULT_ENGINE];
251
+ s = new McpSession({
252
+ bin: engine.bin(this.manager.config),
253
+ args: engine.extraArgs(this.manager.config),
254
+ cwd: dir,
255
+ env: this.manager.childEnv(agent),
256
+ onClose: () => this.sessions.get(dir) === s && this.sessions.delete(dir),
257
+ });
258
+ this.sessions.set(dir, s);
163
259
  }
260
+ return s;
261
+ }
262
+
263
+ view(agent, dir, extra = {}) {
264
+ const list = this.lists.get(dir);
265
+ const s = this.sessions.get(dir);
164
266
  return {
165
267
  agent: agent ? { id: agent.id, name: agent.name, engine: agent.engine ?? DEFAULT_ENGINE, running: Boolean(this.manager.runtimes.get(agent.id)?.pty) } : null,
166
268
  dir,
167
- at: new Date(hit.at).toISOString(),
168
- servers: hit.servers,
169
- error: hit.error ?? null,
269
+ at: list ? new Date(list.at).toISOString() : null,
270
+ servers: list?.servers ?? [],
271
+ session: s && !s.closed ? { startedAt: new Date(s.startedAt).toISOString() } : null,
272
+ runs: this.runs.get(dir) ?? [],
273
+ error: null,
274
+ ...extra,
170
275
  };
171
276
  }
172
277
 
278
+ async list(ref, { refresh = false } = {}) {
279
+ const { agent, dir } = this.where(ref);
280
+ try {
281
+ const servers = await this.session(agent, dir, { fresh: refresh }).status();
282
+ this.lists.set(dir, { at: Date.now(), servers: servers.map(serverView).sort((a, b) => a.name.localeCompare(b.name)) });
283
+ return this.view(agent, dir);
284
+ } catch (e) {
285
+ return this.view(agent, dir, { error: e.message });
286
+ }
287
+ }
288
+
289
+ /** The server, from the last list for that folder. */
290
+ server(dir, name) {
291
+ const s = this.lists.get(dir)?.servers.find((x) => x.name === name);
292
+ if (!s) throw err(404, `No MCP server "${name}" here; refresh the list`);
293
+ return s;
294
+ }
295
+
173
296
  /** The tool, checked against the last list for that folder. */
174
297
  tool(dir, server, tool) {
175
- const s = this.cache.get(dir)?.servers?.find((x) => x.name === server);
176
- const t = s?.tools.find((x) => x.name === tool);
177
- if (!t) throw Object.assign(new Error(`No tool "${tool}" on the MCP server "${server}" here; refresh the list`), { status: 404 });
178
- if (s.status !== 'connected') throw Object.assign(new Error(`The MCP server "${server}" is ${s.status}`), { status: 409 });
298
+ const s = this.server(dir, server);
299
+ const t = s.tools.find((x) => x.name === tool);
300
+ if (!t) throw err(404, `No tool "${tool}" on the MCP server "${server}" here; refresh the list`);
301
+ if (s.status !== 'connected') throw err(409, `The MCP server "${server}" is ${s.status}`);
179
302
  return t;
180
303
  }
181
304
 
182
- /** Run a tool: "session" tells the agent to use it; "workspace" runs it once, apart from the session. */
183
- async run(ref, { server, tool, input = '', where = 'workspace' } = {}) {
305
+ /** Connect one server again (after signing in, or when it failed), and list them all. */
306
+ async reconnect(ref, name) {
307
+ const { agent, dir } = this.where(ref);
308
+ if (!this.lists.has(dir)) await this.list(ref);
309
+ this.server(dir, String(name ?? ''));
310
+ await this.session(agent, dir).reconnect(name);
311
+ return this.list(ref);
312
+ }
313
+
314
+ /**
315
+ * Start signing in to a server: the address to open. Claude Code keeps the tokens (the app never
316
+ * sees them); its sign-in page comes back to a port on this computer, which the session listens on.
317
+ */
318
+ async signIn(ref, name) {
319
+ const { agent, dir } = this.where(ref);
320
+ if (!this.lists.has(dir)) await this.list(ref);
321
+ const s = this.server(dir, String(name ?? ''));
322
+ if (!s.canSignIn) throw err(409, `"${s.name}" runs as a command on this computer; it has no sign-in`);
323
+ const r = await this.session(agent, dir).authenticate(s.name);
324
+ if (!r.authUrl) return { server: s.name, url: null, signedIn: true };
325
+ return { server: s.name, url: String(r.authUrl), callback: r.callbackExpected === true, local: r.callbackExpected === true && r.redirectScheme !== 'custom' };
326
+ }
327
+
328
+ /** Finish a sign-in whose redirect could not reach this computer: the address the browser ended on. */
329
+ async signInCallback(ref, name, url) {
184
330
  const { agent, dir } = this.where(ref);
185
- if (!this.cache.get(dir)?.servers) await this.list(ref);
331
+ this.server(dir, String(name ?? ''));
332
+ await this.session(agent, dir).callback(name, String(url ?? '').trim());
333
+ return this.list(ref);
334
+ }
335
+
336
+ record(dir, run) {
337
+ const list = [run, ...(this.runs.get(dir) ?? [])].slice(0, KEEP_RUNS);
338
+ this.runs.set(dir, list);
339
+ return run;
340
+ }
341
+
342
+ /**
343
+ * Run a tool. "direct": called in the folder's MCP session with these arguments (no model call).
344
+ * "workspace": once through Claude Code, which works the arguments out from plain words, with
345
+ * only that tool allowed. "session": the agent is told to use it.
346
+ */
347
+ async run(ref, { server, tool, input = '', where = 'direct' } = {}) {
348
+ const { agent, dir } = this.where(ref);
349
+ if (!this.lists.has(dir)) await this.list(ref);
186
350
  const t = this.tool(dir, String(server ?? ''), String(tool ?? ''));
187
351
  input = String(input ?? '').slice(0, 8000);
188
352
  if (where === 'session') {
189
- if (!agent) throw Object.assign(new Error('Pick an agent to run it in its session'), { status: 400 });
190
- if ((agent.engine ?? DEFAULT_ENGINE) !== DEFAULT_ENGINE) throw Object.assign(new Error('Running MCP tools in the session works for Claude Code agents'), { status: 409 });
353
+ if (!agent) throw err(400, 'Pick an agent to run it in its session');
354
+ if ((agent.engine ?? DEFAULT_ENGINE) !== DEFAULT_ENGINE) throw err(409, 'Running MCP tools in the session works for Claude Code agents');
191
355
  return { where, tool: t.id, agent: this.manager.tell(agent.id, sessionMessage(t.id, input), { source: 'mcp' }) };
192
356
  }
193
- if (where !== 'workspace') throw Object.assign(new Error('where must be "session" or "workspace"'), { status: 400 });
194
- const scope = { agent: agent ? this.manager.auditView(agent) : null, dir, tool: t.id, input };
357
+ if (where !== 'workspace' && where !== 'direct') throw err(400, 'where must be "direct", "workspace" or "session"');
358
+ const args = where === 'direct' ? parseArgs(input) : null;
359
+ if (where === 'direct' && !args) throw err(400, 'To call it directly, give its arguments as a JSON object (or nothing); plain words go through Claude Code');
360
+ const scope = { agent: agent ? this.manager.auditView(agent) : null, dir, tool: t.id, input, where };
195
361
  this.manager.plugins.check('mcp.run', scope);
196
362
  this.manager.plugins.emit('mcp.run', scope);
197
- const engine = ENGINES[DEFAULT_ENGINE];
198
363
  const t0 = Date.now();
199
- const text = await this.manager.oneShot(agent, runPrompt(t.id, input), {
200
- engine,
201
- model: this.manager.config.explainModel,
202
- tools: [t.id],
203
- cwd: dir,
204
- timeoutMs: RUN_TIMEOUT_MS,
205
- });
206
- return { where, tool: t.id, text, ms: Date.now() - t0, at: new Date().toISOString() };
364
+ const base = { where, server: String(server), name: t.name, tool: t.id, input };
365
+ const done = (out) => this.record(dir, { ...base, ...out, ms: Date.now() - t0, at: new Date().toISOString() });
366
+ try {
367
+ if (where === 'direct') return done(resultText(await this.session(agent, dir).call(t.id, args)));
368
+ const engine = ENGINES[DEFAULT_ENGINE];
369
+ const text = await this.manager.oneShot(agent, runPrompt(t.id, input), { engine, model: this.manager.config.explainModel, tools: [t.id], cwd: dir, timeoutMs: RUN_TIMEOUT_MS });
370
+ return done({ text, isError: false });
371
+ } catch (e) {
372
+ done({ text: e.message, isError: true });
373
+ throw e;
374
+ }
375
+ }
376
+
377
+ close() {
378
+ clearInterval(this.sweep);
379
+ for (const s of this.sessions.values()) s.close();
207
380
  }
208
381
  }
package/src/server.js CHANGED
@@ -957,9 +957,14 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
957
957
  // Your action on issues: assign (starts an agent from the proposal), skip, done, remove, or null to clear.
958
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 })));
959
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), and running one.
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.
961
962
  api.get('/mcp', wrap((req) => mcp.list(req.query.agent, { refresh: req.query.refresh === '1' })));
962
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)));
963
968
  api.get('/designs', wrap((req) => {
964
969
  const v = manager.designs();
965
970
  const group = req.query.group ? String(req.query.group) : null;
@@ -1431,6 +1436,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1431
1436
  // ---------------------------------------------------------- listeners
1432
1437
 
1433
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());
1434
1441
  // Outlive clients' idle keep-alive sockets (Node fetch keeps them ~4s+): with the 5s
1435
1442
  // default, a request sent on a socket just as the server closes it fails with ECONNRESET.
1436
1443
  server.keepAliveTimeout = 65_000;
@@ -1488,6 +1495,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1488
1495
  budgets.close();
1489
1496
  playbooks.close();
1490
1497
  updates.close();
1498
+ mcp.close();
1491
1499
  assistant.close();
1492
1500
  console.log(`[agentmgr] shutting down (${reason}); closing agents so their sessions are saved`);
1493
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
  }