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/cli.js CHANGED
@@ -734,18 +734,21 @@ export async function main(argv) {
734
734
  const actionsCmd = program.command('actions').description("Your action items from Slack and meeting notes (the assistant finds them): decide on each one");
735
735
  actionsCmd
736
736
  .command('ls', { isDefault: true })
737
- .description('The open ones (--all for the decided ones too)')
737
+ .description('The open ones (--all for the decided ones too, --due for the dues)')
738
738
  .option('--all', 'also assigned, skipped, done and removed')
739
+ .option('--due', 'the ones with a due date not done yet, soonest first (overdue at the top)')
739
740
  .option('--json', 'print JSON')
740
741
  .action(async (opts) => {
741
742
  await daemon();
742
743
  const v = await api('GET', '/actions');
743
- const rows = opts.all ? v.rows : v.rows.filter((r) => r.group === 'open');
744
+ const rows = opts.due
745
+ ? v.rows.filter((r) => r.due && ['open', 'assigned', 'skipped', 'snoozed'].includes(r.group)).sort((x, y) => (x.dueAt ? 0 : 1) - (y.dueAt ? 0 : 1) || String(x.dueAt ?? '').localeCompare(String(y.dueAt ?? '')))
746
+ : opts.all ? v.rows : v.rows.filter((r) => r.group === 'open');
744
747
  if (opts.json) return console.log(JSON.stringify({ ...v, rows }, null, 2));
745
- if (!rows.length) return console.log(dim(opts.all ? 'No action items yet.' : 'Nothing open. --all shows the decided ones.'));
748
+ if (!rows.length) return console.log(dim(opts.due ? 'Nothing with a due date is waiting on you.' : opts.all ? 'No action items yet.' : 'Nothing open. --all shows the decided ones.'));
746
749
  for (const r of rows) {
747
750
  console.log(`${bold(r.id)} ${r.group === 'open' ? yellow(r.text) : r.text}${r.group === 'open' ? '' : dim(` [${r.status}]`)}`);
748
- console.log(dim(` ${[r.sourceLabel, r.from && `from ${r.from}`, r.due && `due ${r.due}`, r.link].filter(Boolean).join(' · ')}`));
751
+ console.log(dim(` ${[r.sourceLabel, r.from && `from ${r.from}`, r.due && (/^overdue/.test(r.dueWords ?? '') ? red(r.dueWords) : (r.dueWords ?? `due ${r.due}`)), r.link].filter(Boolean).join(' · ')}`));
749
752
  }
750
753
  });
751
754
  actionsCmd
@@ -826,7 +829,7 @@ export async function main(argv) {
826
829
  .command('list', { isDefault: true })
827
830
  .description('List the MCP servers, their status and tools')
828
831
  .argument('[agent]', "an agent: its folder's servers too (default: your home folder)")
829
- .option('-r, --refresh', 'ask Claude Code again instead of the list from the last 5 minutes')
832
+ .option('-r, --refresh', "start the folder's MCP session again (reads the configuration again)")
830
833
  .option('--json', 'print JSON')
831
834
  .action(async (ref, opts) => {
832
835
  await daemon();
@@ -843,19 +846,46 @@ export async function main(argv) {
843
846
  });
844
847
  mcp
845
848
  .command('run')
846
- .description("Run a tool once in the agent's folder (a separate call allowed only that tool), or in its session with --session")
849
+ .description("Run a tool in the folder's MCP session: JSON arguments (or none) call it directly; plain words go through a one-off Claude Code call allowed only that tool. --session tells the agent to use it")
847
850
  .argument('<agent>', 'the agent, or "home" for your home folder')
848
851
  .argument('<server>')
849
852
  .argument('<tool>')
850
- .argument('[request...]', 'what it should do, or its arguments in plain words')
853
+ .argument('[request...]', `its arguments as JSON ('{"query":"x"}'), or what it should do in plain words`)
851
854
  .option('-s, --session', 'tell the agent to use it in its session instead')
852
855
  .action(async (ref, server, tool, request, opts) => {
853
856
  await daemon();
854
857
  const agent = ref === 'home' ? 'home' : (await resolveAgent(ref)).id;
855
- const r = await api('POST', '/mcp/run', { agent, server, tool, input: request.join(' '), where: opts.session ? 'session' : 'workspace' });
858
+ const input = request.join(' ');
859
+ const { parseArgs } = await import('./mcp.js');
860
+ const r = await api('POST', '/mcp/run', { agent, server, tool, input, where: opts.session ? 'session' : parseArgs(input) ? 'direct' : 'workspace' });
856
861
  if (r.where === 'session') return console.log(`${green('✓')} asked ${r.agent.name} to use ${r.tool}; its answer is in the session`);
857
862
  console.log(r.text);
858
- console.log(dim(`(${r.tool}, ${(r.ms / 1000).toFixed(1)} s)`));
863
+ console.log(dim(`(${r.tool}, ${(r.ms / 1000).toFixed(1)} s, ${r.where === 'direct' ? 'called directly' : 'through Claude Code'})`));
864
+ if (r.isError) process.exitCode = 1;
865
+ });
866
+ mcp
867
+ .command('signin')
868
+ .description("Sign in to a server that needs it: prints the address to open. Claude Code keeps the sign-in")
869
+ .argument('<agent>', 'the agent, or "home" for your home folder')
870
+ .argument('<server>')
871
+ .action(async (ref, server) => {
872
+ await daemon();
873
+ const agent = ref === 'home' ? 'home' : (await resolveAgent(ref)).id;
874
+ const r = await api('POST', '/mcp/signin', { agent, server });
875
+ if (!r.url) return console.log(`${green('✓')} ${server} is already signed in`);
876
+ console.log(`Open this to sign in to ${bold(server)}:\n${r.url}`);
877
+ console.log(dim(r.callback ? `When you finish there it connects by itself; check with: agentmgr mcp reconnect ${ref} ${server}` : `Then connect it again: agentmgr mcp reconnect ${ref} ${server}`));
878
+ });
879
+ mcp
880
+ .command('reconnect')
881
+ .description('Connect one server again (after signing in, or when it failed) and show its status')
882
+ .argument('<agent>', 'the agent, or "home" for your home folder')
883
+ .argument('<server>')
884
+ .action(async (ref, server) => {
885
+ await daemon();
886
+ const agent = ref === 'home' ? 'home' : (await resolveAgent(ref)).id;
887
+ const s = (await api('POST', '/mcp/reconnect', { agent, server })).servers.find((x) => x.name === server);
888
+ console.log(`${bold(server)} ${s?.status === 'connected' ? green(s.status) : yellow(s?.status ?? 'not listed')}${s ? dim(` ${s.tools.length} tools`) : ''}`);
859
889
  });
860
890
 
861
891
  program
@@ -2734,7 +2764,10 @@ export async function main(argv) {
2734
2764
  if (!info.newer) return console.log(`${green('✓')} ${info.current} is the newest release`);
2735
2765
  if (info.blocker) throw new Error(`${info.latest} is available, but: ${info.blocker}`);
2736
2766
  if (opts.check) return console.log(`${yellow(info.latest)} is available (you have ${info.current}); install it: agentmgr update`);
2737
- const r = await up.installUpdate({ log: (m) => console.log(dim(m)) });
2767
+ // A line per package npm fetches, as a count that moves while a long install runs.
2768
+ let fetched = 0;
2769
+ const onLine = (line) => /^npm http /.test(line) && process.stdout.isTTY && process.stdout.write(`\r${dim(` ${++fetched} packages fetched`)}`);
2770
+ const r = await up.installUpdate({ info, log: (m) => console.log(dim(m)), onLine }).finally(() => fetched && process.stdout.write('\n'));
2738
2771
  console.log(`${green('✓')} installed ${r.to} (was ${r.from})`);
2739
2772
  if (!(await health())) return console.log(dim('The daemon is not running; it starts on the new version next time'));
2740
2773
  outliveTerminal();
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/today.js CHANGED
@@ -32,6 +32,15 @@ export function dueAt(due, now = new Date()) {
32
32
  return null;
33
33
  }
34
34
 
35
+ /**
36
+ * When an action is due: its words read from when it was asked, so "by Friday" said last week is
37
+ * that Friday (overdue now), not the next one. From `now` when it isn't known when it was asked.
38
+ */
39
+ export function actionDue(a, now = new Date()) {
40
+ const asked = a?.when ? new Date(a.when) : null;
41
+ return dueAt(a?.due, asked && Number.isFinite(asked.getTime()) ? asked : now);
42
+ }
43
+
35
44
  /** "overdue 2 days", "due today", "due tomorrow", "due Friday", or null. */
36
45
  export function dueWords(at, now = new Date()) {
37
46
  if (!at) return null;
@@ -87,12 +96,12 @@ export function todayItems({ inbox = [], issues = [], actions = [], reviews = []
87
96
  if (a.group !== 'open') continue;
88
97
  // A question put to you: asked directly is pressing; copied or mentioned can wait a little.
89
98
  if (a.kind === 'question') {
90
- const at = dueAt(a.due, now);
99
+ const at = actionDue(a, now);
91
100
  const why = [a.cc ? `you're copied${a.from ? `; ${a.from} asked` : ''}` : a.from ? `${a.from} asked you` : 'asked of you', a.sourceLabel && `in ${a.sourceLabel}`, dueWords(at, now), a.answer ? 'answer drafted' : 'no answer drafted yet'].filter(Boolean).join(' · ');
92
101
  items.push({ id: `action:${a.id}`, kind: 'ask', label: a.cc ? "CC'd" : 'Asked you', title: a.question || a.text, why, score: a.cc ? 44 : at && at.getTime() < now.getTime() + DAY ? 16 : 22, at: a.when ?? null, url: a.link ?? null, actionId: a.id, draft: a.answer ?? null });
93
102
  continue;
94
103
  }
95
- const at = dueAt(a.due, now);
104
+ const at = actionDue(a, now);
96
105
  const words = dueWords(at, now);
97
106
  const late = at && at.getTime() < now.getTime();
98
107
  const soon = at && !late && at.getTime() - now.getTime() < DAY;