mindmeld-mcp 0.4.2 → 0.6.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/dist/mcp.js CHANGED
@@ -7,9 +7,11 @@ import { answerWithFork } from "./answerer.js";
7
7
  import { DEFAULT_RELAY, defaultName, deleteConfig, homeDir, loadConfig, saveConfig } from "./config.js";
8
8
  import { generateGroupSecret, generateInviteCode } from "./crypto.js";
9
9
  import { Daemon } from "./daemon.js";
10
+ import { setupTeams } from "./mcpteam.js";
10
11
  import { runInviter, runJoiner } from "./pairing.js";
11
12
  import { fenceUntrusted } from "./protocol.js";
12
13
  import { listSessions } from "./sessions.js";
14
+ import { compareVersions, VERSION } from "./version.js";
13
15
  const APPROVAL_TIMEOUT_MS = 10 * 60_000;
14
16
  const NOT_PAIRED = "Not connected to anyone yet. Use invite_peer to get a code to send a teammate, or join_peer with a code they sent you.";
15
17
  const NOT_SHARED_HINT = "This session is private. Run /mindmeld:share in it to let your group ask it questions.";
@@ -36,6 +38,12 @@ const STATE_TEXT = {
36
38
  approved: "approved; their session is writing the answer",
37
39
  drafting: "answer drafted; waiting for them to approve sending it",
38
40
  };
41
+ /** Why the invite-code tools refuse while a team is set (the team channel would be used, not the group). */
42
+ export const teamSetNote = (team) => `this machine is using team "${team}"; legacy groups are inactive while a team is set. ` +
43
+ "Invite teammates to the team with invite_member instead.";
44
+ /** What leaving says when this machine is in a team: only a legacy group can be left for now. */
45
+ export const teamLeaveNote = (team, leftGroup) => `${leftGroup ? "Left the old invite-code group. " : "There's no invite-code group to leave. "}` +
46
+ `This machine is still in team "${team}": leaving a team isn't supported yet. Ask a team admin to remove you.`;
39
47
  const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], isError });
40
48
  function loadConfigOrNull() {
41
49
  try {
@@ -61,7 +69,7 @@ function ago(ms) {
61
69
  * dialogs in that session and answered by a read-only fork of it.
62
70
  */
63
71
  export async function runMcpServer() {
64
- const server = new McpServer({ name: "mindmeld", version: "0.4.2" });
72
+ const server = new McpServer({ name: "mindmeld", version: VERSION });
65
73
  const cwd = process.env.CLAUDE_PROJECT_DIR ?? process.cwd();
66
74
  const mySessionId = process.env.CLAUDE_CODE_SESSION_ID;
67
75
  let daemon = null;
@@ -132,10 +140,19 @@ export async function runMcpServer() {
132
140
  });
133
141
  return r.action === "accept" ? { action: "send", text: draft } : { action: "decline", reason: "declined to send the answer" };
134
142
  }
143
+ const teams = setupTeams({ server, elicit, loadConfig: loadConfigOrNull, reconnect });
135
144
  function connect(config) {
136
145
  void daemon?.stop();
146
+ daemon = null;
147
+ if (!config.secret && !config.team)
148
+ return; // e.g. only a team relay chosen: nobody to connect to
149
+ const how = teams.channelFor(config);
150
+ if (!how)
151
+ return; // in a team but not signed in: status and the tools say so
137
152
  daemon = new Daemon({
138
153
  ...config,
154
+ name: how.name,
155
+ channel: how.channel,
139
156
  project: basename(cwd),
140
157
  share,
141
158
  decide,
@@ -152,35 +169,72 @@ export async function runMcpServer() {
152
169
  daemon = null;
153
170
  share = null;
154
171
  }
172
+ const UPDATE = "claude plugin update mindmeld@mindmeld, then restart Claude Code";
173
+ /** Things the user should know about versions: shown in status, and once per session elsewhere. */
174
+ function notices() {
175
+ const info = daemon?.server;
176
+ if (!info)
177
+ return [];
178
+ if (info.blocked)
179
+ return [`mindmeld ${VERSION} is no longer supported by the relay (minimum ${info.minimum}). Update: ${UPDATE}.`];
180
+ const out = [];
181
+ if (compareVersions(VERSION, info.latest) < 0)
182
+ out.push(`mindmeld ${info.latest} is available (you have ${VERSION}). Update: ${UPDATE}.`);
183
+ if (info.legacy) {
184
+ out.push(`${info.legacy} teammate session${info.legacy === 1 ? " is" : "s are"} on an old mindmeld and can't see or ask this one. They need to update: ${UPDATE}.`);
185
+ }
186
+ return out;
187
+ }
188
+ let noticeShown = false;
189
+ /** Append version notices to a tool result the first time they apply in this session. */
190
+ const withNotices = (r) => {
191
+ const n = notices();
192
+ if (noticeShown || n.length === 0)
193
+ return r;
194
+ noticeShown = true;
195
+ return { ...r, content: [...r.content, { type: "text", text: n.join("\n") }] };
196
+ };
155
197
  const existing = loadConfigOrNull();
156
198
  if (existing)
157
199
  connect(existing);
158
- // Every open session holds its own connection. If the group changes elsewhere (left, or
159
- // re-paired from another session or the CLI), follow it here within a few seconds.
160
- let knownSecret = existing?.secret ?? null;
200
+ // Every open session holds its own connection. If the group or team changes elsewhere (left,
201
+ // re-paired, a team created or joined, signed in), follow it here within a few seconds.
202
+ let knownKey = teams.watchKey(existing);
161
203
  const watch = setInterval(() => {
162
204
  const c = loadConfigOrNull();
163
- const secret = c?.secret ?? null;
164
- if (secret === knownSecret)
205
+ const key = teams.watchKey(c);
206
+ if (key === knownKey)
165
207
  return;
166
- knownSecret = secret;
208
+ knownKey = key;
167
209
  if (c)
168
210
  connect(c);
169
211
  else
170
212
  disconnect();
171
213
  }, 3000);
172
214
  watch.unref();
215
+ /** Reconnect from the saved config now (after a sign-in or a team change in this session). */
216
+ function reconnect() {
217
+ const c = loadConfigOrNull();
218
+ knownKey = teams.watchKey(c);
219
+ if (c)
220
+ connect(c);
221
+ else
222
+ disconnect();
223
+ }
224
+ /** Why the peer tools can't work right now: team sign-in or connection trouble, or not paired. */
225
+ const notReady = () => teams.blocker() ?? (daemon ? null : NOT_PAIRED);
173
226
  server.registerTool("list_peers", {
174
227
  title: "List peers",
175
228
  description: "List the sessions teammates are sharing through mindmeld right now (only shared sessions are visible).",
176
229
  inputSchema: {},
177
230
  }, async () => {
178
- if (!daemon)
179
- return text(NOT_PAIRED);
231
+ const why = notReady();
232
+ if (why || !daemon)
233
+ return text(why ?? NOT_PAIRED);
180
234
  const peers = daemon.onlinePeers();
181
235
  if (peers.length === 0)
182
- return text("Nobody is sharing a session right now. Teammates appear here after they run /mindmeld:share.");
183
- return text(peers.map((p) => `- ${p.name}: "${p.project}"${p.activeAt ? ` · active ${ago(p.activeAt)}` : ""}`).join("\n"));
236
+ return withNotices(text("Nobody is sharing a session right now. Teammates appear here after they run /mindmeld:share."));
237
+ return withNotices(text(peers.map((p) => `- ${p.name}: "${p.project}"${p.activeAt ? ` · active ${ago(p.activeAt)}` : ""}`).join("\n")));
184
238
  });
185
239
  server.registerTool("ask_peer", {
186
240
  title: "Ask a teammate's Claude",
@@ -194,8 +248,9 @@ export async function runMcpServer() {
194
248
  timeout_sec: z.number().int().min(10).max(3600).optional().describe("Default 600"),
195
249
  },
196
250
  }, async ({ question, peer, context, timeout_sec }, extra) => {
197
- if (!daemon)
198
- return text(NOT_PAIRED, true);
251
+ const why = notReady();
252
+ if (why || !daemon)
253
+ return text(why ?? NOT_PAIRED, true);
199
254
  const token = extra._meta?.progressToken;
200
255
  let step = 0;
201
256
  const progress = (message) => {
@@ -208,8 +263,8 @@ export async function runMcpServer() {
208
263
  const r = await daemon.ask(question, { peer, context, timeoutSec: timeout_sec, onStatus: (s) => progress(STATE_TEXT[s]) });
209
264
  logActivity({ at: Date.now(), dir: "out", peer: "error" in r ? (peer ?? "?") : r.from, question: question.slice(0, 200), outcome: "error" in r ? r.error : "answered" });
210
265
  if ("error" in r)
211
- return text(`No answer: ${r.error}`, true);
212
- return text(fenceUntrusted(r.from, r.text));
266
+ return withNotices(text(`No answer: ${r.error}`, true));
267
+ return withNotices(text(fenceUntrusted(r.from, r.text)));
213
268
  });
214
269
  server.registerTool("share_snippet", {
215
270
  title: "Share a snippet",
@@ -220,8 +275,9 @@ export async function runMcpServer() {
220
275
  peer: z.string().optional().describe("Who to send it to. Optional if only one person is online"),
221
276
  },
222
277
  }, async ({ title, text: body, peer }) => {
223
- if (!daemon)
224
- return text(NOT_PAIRED, true);
278
+ const why = notReady();
279
+ if (why || !daemon)
280
+ return text(why ?? NOT_PAIRED, true);
225
281
  const r = daemon.snippet(title, body, peer);
226
282
  return "error" in r ? text(r.error, true) : text(`Shared with ${r.to}.`);
227
283
  });
@@ -231,7 +287,7 @@ export async function runMcpServer() {
231
287
  inputSchema: {},
232
288
  }, async () => {
233
289
  if (!daemon)
234
- return text(NOT_PAIRED);
290
+ return text(notReady() ?? NOT_PAIRED);
235
291
  const items = daemon.drainInbox();
236
292
  if (items.length === 0)
237
293
  return text("Inbox is empty.");
@@ -246,12 +302,12 @@ export async function runMcpServer() {
246
302
  },
247
303
  }, async ({ label }) => {
248
304
  if (!daemon)
249
- return text(NOT_PAIRED, true);
305
+ return text(notReady() ?? NOT_PAIRED, true);
250
306
  share = { label: (label ?? basename(cwd)).trim() || basename(cwd) };
251
307
  daemon.setShare(share);
252
308
  return text([
253
309
  `This session is now shared with your mindmeld group as "${share.label}".`,
254
- `They can see: your name ("${loadConfigOrNull()?.name}"), the label "${share.label}", and when the session was last active. Nothing else: not your prompts, files or transcript.`,
310
+ `They can see: your name ("${daemon.name}"), the label "${share.label}", and when the session was last active. Nothing else: not your prompts, files or transcript.`,
255
311
  "Each question shows an Accept/Decline dialog here, and answers come from a read-only copy of this session that can only read files inside this project (never .env or key files).",
256
312
  "Run /mindmeld:stop to stop sharing. Closing this session stops it too.",
257
313
  ].join("\n"));
@@ -273,12 +329,16 @@ export async function runMcpServer() {
273
329
  inputSchema: {},
274
330
  }, async () => {
275
331
  const c = loadConfigOrNull();
332
+ const teamLines = await teams.statusLines(c);
276
333
  if (!c || !daemon)
277
- return text(NOT_PAIRED);
334
+ return text([...(c?.team ? [] : [NOT_PAIRED]), ...teamLines].join("\n"));
278
335
  const peers = daemon.onlinePeers();
279
336
  const lines = [
280
- `Connection: ${daemon.connected ? "connected" : "NOT connected (reconnecting to the relay)"}`,
281
- `You appear as: ${c.name}`,
337
+ `Connection: ${daemon.server?.blocked ? "blocked: this version is too old" : daemon.connected ? "connected" : `NOT connected (${c.team ? "see below" : "reconnecting to the relay"})`}`,
338
+ `Version: ${VERSION}`,
339
+ ...notices(),
340
+ ...teamLines,
341
+ `You appear as: ${c.team ? `@${daemon.name}` : c.name}`,
282
342
  `This session: ${share ? `shared as "${share.label}"` : "private (not visible to anyone). Run /mindmeld:share to share it."}`,
283
343
  `Sharing now: ${peers.length ? peers.map((p) => `${p.name} ("${p.project}")`).join(", ") : "nobody"}`,
284
344
  `Always allowed (answered without dialogs): ${c.trusted?.length ? c.trusted.join(", ") : "nobody"}`,
@@ -295,15 +355,24 @@ export async function runMcpServer() {
295
355
  description: "Disconnect this machine from the user's mindmeld group and forget the pairing, in every open session. " +
296
356
  "Only when the user asks to leave or disconnect. Reconnecting needs a new invite.",
297
357
  inputSchema: {
298
- confirmed: z.boolean().optional().describe("Set true only if the user has explicitly confirmed in chat; otherwise a dialog asks them"),
358
+ confirmed: z
359
+ .boolean()
360
+ .optional()
361
+ .describe("Only used when this client can't show dialogs: set true after the user has explicitly confirmed in chat. Otherwise a dialog always asks them"),
299
362
  },
300
363
  }, async ({ confirmed }) => {
301
- if (!loadConfigOrNull())
364
+ const current = loadConfigOrNull();
365
+ if (!current || (!current.secret && !current.team))
302
366
  return text("You're not in a mindmeld group.");
303
- if (!confirmed) {
304
- if (!server.server.getClientCapabilities()?.elicitation) {
367
+ if (current.team && !current.secret)
368
+ return text(teamLeaveNote(current.team.name, false));
369
+ // The user confirms in a dialog whenever the client can show one; `confirmed` can't skip it.
370
+ if (!server.server.getClientCapabilities()?.elicitation) {
371
+ if (!confirmed) {
305
372
  return text("Ask the user to confirm leaving the group, then call leave_group again with confirmed: true.", true);
306
373
  }
374
+ }
375
+ else {
307
376
  const r = await elicit([
308
377
  "Leave your mindmeld group?",
309
378
  "",
@@ -313,9 +382,16 @@ export async function runMcpServer() {
313
382
  if (r.action !== "accept")
314
383
  return text("Okay, staying in the group.");
315
384
  }
385
+ if (current.team) {
386
+ // Only the legacy group goes; the team stays (leaving a team isn't supported yet).
387
+ const { secret: _gone, trusted: _t, ...rest } = current;
388
+ saveConfig(rest);
389
+ reconnect();
390
+ return text(teamLeaveNote(current.team.name, true));
391
+ }
316
392
  disconnect();
317
393
  deleteConfig();
318
- knownSecret = null;
394
+ knownKey = teams.watchKey(null);
319
395
  return text("Left the group. Every session on this machine is now disconnected and the pairing is deleted. Use /mindmeld:invite or /mindmeld:join to connect again.");
320
396
  });
321
397
  server.registerTool("trust_peer", {
@@ -345,17 +421,22 @@ export async function runMcpServer() {
345
421
  },
346
422
  }, async ({ my_name }) => {
347
423
  const prev = loadConfigOrNull();
424
+ if (prev?.team)
425
+ return text(teamSetNote(prev.team.name), true);
426
+ const secret = prev?.secret ?? generateGroupSecret();
348
427
  const config = {
349
- secret: prev?.secret ?? generateGroupSecret(),
428
+ ...prev,
429
+ secret,
350
430
  relay: prev?.relay ?? DEFAULT_RELAY,
351
431
  name: my_name ?? prev?.name ?? defaultName(),
352
432
  trusted: prev?.trusted,
353
433
  };
354
434
  saveConfig(config);
355
- if (!daemon || !prev || my_name)
435
+ knownKey = teams.watchKey(config);
436
+ if (!daemon || !prev?.secret || my_name)
356
437
  connect(config);
357
438
  const code = generateInviteCode();
358
- runInviter({ relay: config.relay, code, secret: config.secret, name: config.name }).then(({ peerName }) => console.error(`mindmeld: ${peerName} joined`), (e) => console.error(`mindmeld: invite ${code} ended: ${e.message}`));
439
+ runInviter({ relay: config.relay, code, secret, name: config.name }).then(({ peerName }) => console.error(`mindmeld: ${peerName} joined`), (e) => console.error(`mindmeld: invite ${code} ended: ${e.message}`));
359
440
  return text([
360
441
  `Invite code: ${code}`,
361
442
  "",
@@ -377,12 +458,15 @@ export async function runMcpServer() {
377
458
  },
378
459
  }, async ({ code, my_name }) => {
379
460
  const prev = loadConfigOrNull();
461
+ if (prev?.team)
462
+ return text(teamSetNote(prev.team.name), true);
380
463
  const relay = prev?.relay ?? DEFAULT_RELAY;
381
464
  const name = my_name ?? prev?.name ?? defaultName();
382
465
  try {
383
466
  const { secret, inviterName } = await runJoiner({ relay, code, name });
384
- const config = { secret, relay, name, trusted: prev?.secret === secret ? prev.trusted : [] };
467
+ const config = { ...prev, secret, relay, name, trusted: prev?.secret === secret ? prev.trusted : [] };
385
468
  saveConfig(config);
469
+ knownKey = teams.watchKey(config);
386
470
  connect(config);
387
471
  return text(`Connected to ${inviterName}'s group as "${name}". ` +
388
472
  `You can ask any session they share, e.g. "ask ${inviterName.split(/\s+/)[0]} how they built X". ` +
@@ -0,0 +1,304 @@
1
+ import { z } from "zod";
2
+ import { loadSession } from "./auth/session.js";
3
+ import { DEFAULT_RELAY, relayWarning, saveConfig, teamRelay, withTeam } from "./config.js";
4
+ import { loadOrCreateIdentity } from "./identity.js";
5
+ import { acceptInvite, addDevice, createTeam, deleteMember, formatTeam, getRoster, inviteMember, inviteMessage, listTeams, normLogin, removeAndRotate, setRole, signIn, signInLine, signInState, SIGNED_IN_EXPIRED, teamLine, } from "./teamapi.js";
6
+ import { SIGN_IN_EXPIRED, TeamChannel } from "./teamchannel.js";
7
+ import { rotate } from "./teamkeys.js";
8
+ const NO_TEAM = "You're not in a team yet. Create one with create_team, or accept an invite with accept_invite.";
9
+ /** "invite to "core"" or "team "core" (member)". */
10
+ const describeEntry = (t) => (t.role === "invited" ? `invite to "${t.name}"` : `team "${t.name}" (${t.role})`);
11
+ const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], isError });
12
+ /**
13
+ * GitHub sign-in and teams for the MCP server: registers login, create_team, invite_member,
14
+ * accept_invite, team, remove_member and set_role, and builds the TeamChannel when config.json has a
15
+ * team. Every tool answers with sign-in guidance when the session is missing or expired.
16
+ */
17
+ export function setupTeams(host) {
18
+ const { server } = host;
19
+ /** The current connection's TeamChannel, if this machine is in a team and signed in. */
20
+ let channel = null;
21
+ /** The relay refused this channel's session token. */
22
+ let channelExpired = false;
23
+ let login = { gen: 0, pending: false, error: null };
24
+ function ready(needTeam) {
25
+ const config = host.loadConfig();
26
+ const relay = teamRelay(config);
27
+ const s = signInState(relay);
28
+ if (!("session" in s))
29
+ return signInLine(s);
30
+ if (!needTeam)
31
+ return { session: s.session, config, relay };
32
+ if (!config?.team)
33
+ return NO_TEAM;
34
+ return { session: s.session, config, relay, team: config.team };
35
+ }
36
+ /** Run a relay call for a tool, turning a thrown error into an error result. */
37
+ const attempt = async (f) => {
38
+ try {
39
+ return await f();
40
+ }
41
+ catch (e) {
42
+ return text(e.message, true);
43
+ }
44
+ };
45
+ /**
46
+ * How to connect for `config`: the team channel (and the login as the name) when it has a team,
47
+ * `{ name }` for the legacy group, or null when it has a team but nobody is signed in.
48
+ */
49
+ function channelFor(config) {
50
+ channel = null;
51
+ channelExpired = false;
52
+ if (!config.team)
53
+ return { name: config.name };
54
+ const relay = teamRelay(config);
55
+ const session = loadSession(relay);
56
+ if (!session)
57
+ return null;
58
+ const ch = new TeamChannel({ relayHttp: relay, teamId: config.team.teamId, session, id: loadOrCreateIdentity() });
59
+ ch.on("auth-expired", () => {
60
+ if (channel === ch)
61
+ channelExpired = true;
62
+ });
63
+ channel = ch;
64
+ // A second machine for the same login: add this device (a no-op when the team already has it).
65
+ addDevice(relay, session, config.team.teamId).catch(() => { });
66
+ return { channel: ch, name: session.login };
67
+ }
68
+ /** Why the team connection can't be used right now (sign-in or channel trouble); null if fine or not in a team. */
69
+ function blocker() {
70
+ const config = host.loadConfig();
71
+ if (!config?.team)
72
+ return null;
73
+ const s = signInState(teamRelay(config));
74
+ if (!("session" in s))
75
+ return signInLine(s);
76
+ if (channelExpired)
77
+ return SIGNED_IN_EXPIRED;
78
+ if (channel && !channel.connected && channel.status)
79
+ return `Not connected to team "${config.team.name}": ${channel.status}`;
80
+ return null;
81
+ }
82
+ /** Lines for the status tool: sign-in, team and role, and the team connection's problem if any. */
83
+ async function statusLines(config) {
84
+ const relayUrl = teamRelay(config);
85
+ const s = signInState(relayUrl);
86
+ let signedIn = signInLine(s);
87
+ const lines = [];
88
+ let teamText = null;
89
+ if (config?.team) {
90
+ let roster = null;
91
+ let failed = "";
92
+ if ("session" in s && !channelExpired) {
93
+ try {
94
+ roster = await getRoster(relayUrl, s.session, config.team.teamId, 3000);
95
+ }
96
+ catch (e) {
97
+ if (e.status === 401)
98
+ channelExpired = true;
99
+ else
100
+ failed = ` (couldn't load the roster: ${e.message})`;
101
+ }
102
+ }
103
+ if (channelExpired)
104
+ signedIn = SIGNED_IN_EXPIRED;
105
+ teamText = teamLine(config.team.name, roster, "session" in s ? s.session.uid : null) + failed;
106
+ }
107
+ // The relay in use: the legacy group's when only a group is set, else the team relay.
108
+ const relay = relayWarning(config?.secret && !config.team ? config.relay : relayUrl);
109
+ if (relay)
110
+ lines.push(relay);
111
+ lines.push(signedIn);
112
+ if (login.pending && !("session" in s))
113
+ lines.push("Sign-in in progress: waiting for the code to be entered on GitHub");
114
+ if (login.error)
115
+ lines.push(`Last sign-in attempt failed: ${login.error}`);
116
+ if (teamText)
117
+ lines.push(teamText);
118
+ const why = config?.team ? channel?.status : null;
119
+ if (why && why !== SIGN_IN_EXPIRED)
120
+ lines.push(`Team connection: ${why}`);
121
+ return lines;
122
+ }
123
+ /** What the config watcher compares: a change means reconnect. Includes the session for a team. */
124
+ const watchKey = (c) => [c?.secret ?? "", c?.team?.teamId ?? "", teamRelay(c), c?.team ? (loadSession(teamRelay(c))?.token ?? "") : ""].join("|");
125
+ /**
126
+ * Point config.json at `team`, keeping everything else except the always-allow list when the team
127
+ * changes: names trusted in a legacy group (or another team) must not match a GitHub login here.
128
+ */
129
+ function useTeam(r, team) {
130
+ const prev = r.config;
131
+ saveConfig(withTeam(prev, { relay: prev?.relay ?? DEFAULT_RELAY, name: prev?.name ?? r.session.login }, team));
132
+ host.reconnect();
133
+ return prev?.team && prev.team.teamId !== team.teamId ? ` (This replaced team "${prev.team.name}" on this machine.)` : "";
134
+ }
135
+ server.registerTool("login", {
136
+ title: "Sign in with GitHub",
137
+ description: "Sign this machine in to mindmeld with GitHub (needed for teams). Returns a code and a URL for the user to open; " +
138
+ "sign-in finishes in the background once they approve, and status then shows who is signed in.",
139
+ inputSchema: {},
140
+ }, async () => {
141
+ const config = host.loadConfig();
142
+ const relay = teamRelay(config);
143
+ const gen = login.gen + 1;
144
+ login = { gen, pending: true, error: null };
145
+ return new Promise((resolve) => {
146
+ let shown = false;
147
+ signIn(relay, config, (code, uri) => {
148
+ shown = true;
149
+ resolve(text([
150
+ `Open ${uri} and enter ${code}`,
151
+ "",
152
+ "Show the user this code and link. Sign-in finishes on its own once they approve it on GitHub; then /mindmeld:status shows who is signed in.",
153
+ "The code expires in 15 minutes.",
154
+ ].join("\n")));
155
+ }).then(() => {
156
+ if (login.gen !== gen)
157
+ return;
158
+ login = { gen, pending: false, error: null };
159
+ host.reconnect();
160
+ }, (e) => {
161
+ if (login.gen === gen)
162
+ login = { gen, pending: false, error: e.message };
163
+ if (!shown)
164
+ resolve(text(`Sign-in failed: ${e.message}`, true));
165
+ });
166
+ });
167
+ });
168
+ server.registerTool("create_team", {
169
+ title: "Create a team",
170
+ description: "Create a mindmeld team with the signed-in user as its admin, and connect this machine to it. Only when the user asks.",
171
+ inputSchema: { name: z.string().min(1).max(60).describe("The team's name") },
172
+ }, async ({ name }) => {
173
+ const r = ready(false);
174
+ if (typeof r === "string")
175
+ return text(r, true);
176
+ return attempt(async () => {
177
+ const teamName = name.trim();
178
+ const { teamId } = await createTeam(r.relay, r.session, teamName);
179
+ const replaced = useTeam(r, { teamId, name: teamName });
180
+ return text(`Created team "${teamName}" with you (@${r.session.login}) as admin.${replaced}\n` +
181
+ "Invite teammates by their GitHub login with invite_member. Your sessions stay private until you run /mindmeld:share in one.");
182
+ });
183
+ });
184
+ server.registerTool("invite_member", {
185
+ title: "Invite someone to the team",
186
+ description: "Invite a GitHub user to the team (admins only). Gives the user a message to send them, with install and sign-in steps.",
187
+ inputSchema: { login: z.string().min(1).describe("Their GitHub login") },
188
+ }, async ({ login: who }) => {
189
+ const r = ready(true);
190
+ if (typeof r === "string")
191
+ return text(r, true);
192
+ return attempt(async () => {
193
+ await inviteMember(r.relay, r.session, r.team.teamId, who);
194
+ return text(inviteMessage(who, r.team.name));
195
+ });
196
+ });
197
+ server.registerTool("accept_invite", {
198
+ title: "Accept a team invite (or use a team you're in)",
199
+ description: "Accept an invite to a mindmeld team and connect this machine to it. Also connects this machine to a team the user already belongs to. " +
200
+ "Optional team name or id when there are several.",
201
+ inputSchema: { team: z.string().optional().describe("Team name or id, if there is more than one") },
202
+ }, async ({ team }) => {
203
+ const r = ready(false);
204
+ if (typeof r === "string")
205
+ return text(r, true);
206
+ return attempt(async () => {
207
+ const teams = await listTeams(r.relay, r.session);
208
+ const q = team?.trim().toLowerCase();
209
+ const match = q ? teams.filter((t) => t.teamId === q || t.name.toLowerCase() === q) : teams;
210
+ if (match.length === 0) {
211
+ return text(q && teams.length
212
+ ? `No invite to or team called "${team}". Yours: ${teams.map(describeEntry).join(", ")}.`
213
+ : `No pending invites for @${r.session.login}. Ask a team admin to invite your GitHub login (@${r.session.login}).`, true);
214
+ }
215
+ if (match.length > 1) {
216
+ return text(`You have ${match.map((t) => `${describeEntry(t)} (${t.teamId})`).join(", ")}. Which one? Call accept_invite with team set.`, true);
217
+ }
218
+ const t = match[0];
219
+ if (t.role !== "invited") {
220
+ const replaced = useTeam(r, { teamId: t.teamId, name: t.name });
221
+ return text(`This machine now uses team "${t.name}", where you're ${t.role}.${replaced}`);
222
+ }
223
+ await acceptInvite(r.relay, r.session, t.teamId);
224
+ const replaced = useTeam(r, { teamId: t.teamId, name: t.name });
225
+ return text(`Joined team "${t.name}" as @${r.session.login}.${replaced}\n` +
226
+ "A teammate's mindmeld gives this device the team key the next time one of them is online; /mindmeld:status shows progress. " +
227
+ "Your sessions stay private until you run /mindmeld:share in one.");
228
+ });
229
+ });
230
+ server.registerTool("team", {
231
+ title: "Show the team",
232
+ description: "Show the user's mindmeld team: members and roles, each device's key fingerprint and whether it has the team key, pending invites, and recent activity.",
233
+ inputSchema: {},
234
+ }, async () => {
235
+ const r = ready(false);
236
+ if (typeof r === "string")
237
+ return text(r, true);
238
+ return attempt(async () => {
239
+ if (!r.config?.team) {
240
+ const teams = await listTeams(r.relay, r.session);
241
+ if (teams.length === 0)
242
+ return text(NO_TEAM);
243
+ return text(`This machine isn't using a team. Yours: ${teams.map(describeEntry).join(", ")}. Use accept_invite with the team's name to use one here.`);
244
+ }
245
+ const roster = await getRoster(r.relay, r.session, r.config.team.teamId);
246
+ return text(formatTeam(roster, { uid: r.session.uid, deviceId: loadOrCreateIdentity().deviceId }));
247
+ });
248
+ });
249
+ server.registerTool("remove_member", {
250
+ title: "Remove someone from the team",
251
+ description: "Remove a member from the team (admins only), with all their devices, then rotate the team key so they can't read anything sent afterwards. " +
252
+ "Only when the user asks. A dialog asks them to confirm.",
253
+ inputSchema: {
254
+ login: z.string().min(1).describe("Their GitHub login"),
255
+ confirmed: z
256
+ .boolean()
257
+ .optional()
258
+ .describe("Only used when this client can't show dialogs: set true after the user has explicitly confirmed in chat. Otherwise a dialog always asks them"),
259
+ },
260
+ }, async ({ login: who, confirmed }) => {
261
+ const r = ready(true);
262
+ if (typeof r === "string")
263
+ return text(r, true);
264
+ const target = normLogin(who);
265
+ // The user confirms in a dialog whenever the client can show one; `confirmed` can't skip it.
266
+ if (!server.server.getClientCapabilities()?.elicitation) {
267
+ if (!confirmed) {
268
+ return text(`Ask the user to confirm removing @${target} from team "${r.team.name}", then call remove_member again with confirmed: true.`, true);
269
+ }
270
+ }
271
+ else {
272
+ const a = await host.elicit([
273
+ `Remove @${target} from team "${r.team.name}"?`,
274
+ "",
275
+ "Their devices lose access right away, and the team key is rotated so they can't read anything the team sends after this.",
276
+ ].join("\n"), { type: "object", properties: {} });
277
+ if (a.action !== "accept")
278
+ return text(`Okay, @${target} stays in the team.`);
279
+ }
280
+ const o = { relayHttp: r.relay, teamId: r.team.teamId, session: r.session, id: loadOrCreateIdentity() };
281
+ const res = await removeAndRotate(target, {
282
+ remove: () => deleteMember(r.relay, r.session, r.team.teamId, target),
283
+ rotate: () => rotate({ ...o, reason: "removed" }),
284
+ });
285
+ return text(res.text, res.isError);
286
+ });
287
+ server.registerTool("set_role", {
288
+ title: "Change a member's role",
289
+ description: "Make a team member an admin or a regular member (admins only).",
290
+ inputSchema: {
291
+ login: z.string().min(1).describe("Their GitHub login"),
292
+ role: z.enum(["admin", "member"]),
293
+ },
294
+ }, async ({ login: who, role }) => {
295
+ const r = ready(true);
296
+ if (typeof r === "string")
297
+ return text(r, true);
298
+ return attempt(async () => {
299
+ await setRole(r.relay, r.session, r.team.teamId, who, role);
300
+ return text(`@${normLogin(who)} is now ${role} in team "${r.team.name}".`);
301
+ });
302
+ });
303
+ return { channelFor, blocker, statusLines, watchKey };
304
+ }
package/dist/protocol.js CHANGED
@@ -41,11 +41,32 @@ export const Payload = z.discriminatedUnion("type", [
41
41
  text: z.string(),
42
42
  }),
43
43
  ]);
44
- /** Relay envelope: opaque sealed data. */
45
- export const Frame = z.object({ t: z.literal("msg"), d: z.string() });
46
- export const PROTOCOL_VERSION = 2;
47
- export const HELLO_INTERVAL_MS = 20_000;
48
- export const PEER_TIMEOUT_MS = 60_000;
44
+ /** Relay envelope: opaque sealed data. From v3 the relay adds `c`, the sender's connection id. */
45
+ export const Frame = z.object({ t: z.literal("msg"), d: z.string(), c: z.string().optional() });
46
+ /**
47
+ * Plaintext control frames from the relay (v3+ clients only, i.e. those that send `?v=`):
48
+ * - server: versions, sent on connect (and when the count of old clients in the room changes).
49
+ * `blocked` means this client is below the minimum and is about to be disconnected.
50
+ * - joined / left: a connection opened or closed. Presence is driven by these instead of timers.
51
+ */
52
+ export const Control = z.discriminatedUnion("t", [
53
+ z.object({
54
+ t: z.literal("server"),
55
+ latest: z.string(),
56
+ minimum: z.string(),
57
+ legacy: z.number().optional(),
58
+ blocked: z.boolean().optional(),
59
+ }),
60
+ z.object({ t: z.literal("joined"), c: z.string() }),
61
+ z.object({ t: z.literal("left"), c: z.string() }),
62
+ ]);
63
+ export const PROTOCOL_VERSION = 3;
64
+ /** How often a client checks whether its "last active" time moved enough to re-announce. */
65
+ export const ACTIVITY_CHECK_MS = 60_000;
66
+ /** Re-announce "last active" only when it moved by at least this much. */
67
+ export const ACTIVITY_RESOLUTION_MS = 5 * 60_000;
68
+ /** WebSocket protocol pings (not billed by Cloudflare) to detect dead connections. */
69
+ export const PING_INTERVAL_MS = 60_000;
49
70
  /** Fence peer-originated text so the asking Claude treats it as data, not instructions. */
50
71
  export function fenceUntrusted(from, text) {
51
72
  const safeFrom = from.replace(/[^\w .-]/g, "");