mindferry 0.0.0-stage → 0.2.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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -2
  3. package/README.zh-CN.md +165 -0
  4. package/bin/mindferry.mjs +301 -0
  5. package/examples/demo-en/chatgpt-conversations.json +72 -0
  6. package/examples/demo-en/chatgpt-copied.txt +8 -0
  7. package/examples/demo-en/claude-conversations.json +25 -0
  8. package/examples/demo-en/claude-memories.json +6 -0
  9. package/examples/demo-en/deepseek-conversations.json +39 -0
  10. package/examples/demo-en/gemini-MyActivity.json +18 -0
  11. package/examples/demo-en/grok-export.json +27 -0
  12. package/examples/exports/README.md +4 -0
  13. package/examples/exports/chatgpt-conversations.json +21 -0
  14. package/examples/exports/claude-conversations.json +13 -0
  15. package/examples/exports/claude-memories.json +3 -0
  16. package/examples/exports/deepseek-conversations.json +12 -0
  17. package/examples/exports/gemini-MyActivity.json +5 -0
  18. package/examples/exports/grok-export.json +11 -0
  19. package/examples/exports/open-webui-export.json +13 -0
  20. package/examples/scheduler/crontab.txt +2 -0
  21. package/examples/scheduler/io.github.mindferry.sync.plist +18 -0
  22. package/examples/single-chats/chatgpt-copied.txt +8 -0
  23. package/examples/single-chats/chatgpt-saved-page.html +4 -0
  24. package/examples/single-chats/claude-chat.md +7 -0
  25. package/package.json +55 -4
  26. package/src/connect.mjs +204 -0
  27. package/src/core/archive.mjs +144 -0
  28. package/src/core/card.mjs +64 -0
  29. package/src/core/classify.mjs +81 -0
  30. package/src/core/clients.mjs +63 -0
  31. package/src/core/errors.mjs +146 -0
  32. package/src/core/export.mjs +53 -0
  33. package/src/core/extract.mjs +183 -0
  34. package/src/core/generator.mjs +98 -0
  35. package/src/core/hub.mjs +637 -0
  36. package/src/core/llm.mjs +77 -0
  37. package/src/core/merge.mjs +95 -0
  38. package/src/core/profile.mjs +175 -0
  39. package/src/core/rules.mjs +88 -0
  40. package/src/core/store.mjs +109 -0
  41. package/src/core/text.mjs +82 -0
  42. package/src/demo.mjs +30 -0
  43. package/src/importers/index.mjs +366 -0
  44. package/src/importers/zip.mjs +48 -0
  45. package/src/mcp/server.mjs +272 -0
  46. package/src/remote.mjs +180 -0
  47. package/src/ui/server.mjs +281 -0
  48. package/src/ui/static/app.js +1037 -0
  49. package/src/ui/static/index.html +269 -0
  50. package/src/ui/static/logo.svg +16 -0
  51. package/src/ui/static/mascot-busy.svg +35 -0
  52. package/src/ui/static/mascot-happy.svg +27 -0
  53. package/src/ui/static/mascot-idle.svg +26 -0
  54. package/src/ui/static/mascot-oops.svg +26 -0
  55. package/src/ui/static/style.css +382 -0
  56. package/src/version.mjs +1 -0
  57. package/src/watch.mjs +80 -0
@@ -0,0 +1,272 @@
1
+ // Minimal stdio MCP server (JSON-RPC 2.0, newline-delimited). Zero dependencies.
2
+ // One process per local AI: `mindferry mcp --client claude-code`. The client id is fixed
3
+ // by the command line, so one AI cannot read or write in another's name.
4
+ import { createInterface } from 'node:readline';
5
+ import { clientInfo, clientName, CLIENTS } from '../core/clients.mjs';
6
+ import { CATEGORIES } from '../core/classify.mjs';
7
+ import { FriendlyError, toFriendly, messageFor } from '../core/errors.mjs';
8
+ import { VERSION } from '../version.mjs';
9
+
10
+ const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
11
+
12
+ const INSTRUCTIONS = `MindFerry keeps the user's own cross-AI memory on their computer: facts they told ChatGPT, Claude, Gemini, Grok, DeepSeek and others, filtered by the privacy rule the user set for you.
13
+ Take only what you need, in three steps:
14
+ 1. At the start of a new conversation, call get_user_profile once (a few hundred tokens: who the user is, how they like answers, what they're working on, plus a short catalog of what else you may read). Use it quietly; don't recite it back.
15
+ 2. When the task needs more about one area, call memory_browse with that category, or memory_search with a few words.
16
+ 3. Only if the user allowed it and you need the exact words, open a past conversation with memory_read_conversation.
17
+ - When the user states a durable fact about themselves (role, projects, preferences, how they like answers, city, skills), call memory_push with short, self-contained statements written as the user would say them.
18
+ - Never push passwords, keys or ID/card numbers. Sensitive details are filtered automatically.`;
19
+
20
+ export const TOOLS = [
21
+ {
22
+ name: 'get_user_profile',
23
+ description: "START HERE: call once at the start of every new conversation. Returns a short 'About me' profile of the user (who they are, how they like answers, what they're working on, goals, tools, dislikes), what changed since you last asked, and a catalog of the other categories you may read with memory_browse. Small (a few hundred tokens) and filtered by the privacy rule the user set for you.",
24
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
25
+ annotations: { title: 'Who is the user? (start here)', readOnlyHint: false, idempotentHint: true },
26
+ },
27
+ {
28
+ name: 'memory_browse',
29
+ description: "List the user's facts in one category, newest first (only what the user lets you see). Use after get_user_profile when the task needs more detail about one area, e.g. 'projects' before planning work, 'preferences' before recommending something.",
30
+ inputSchema: {
31
+ type: 'object',
32
+ properties: {
33
+ category: { type: 'string', enum: ['all', ...CATEGORIES.filter((c) => c !== 'ids')], description: "A category from the profile's catalog, or 'all'" },
34
+ limit: { type: 'number', description: 'Max facts (default 30)' },
35
+ },
36
+ required: ['category'],
37
+ additionalProperties: false,
38
+ },
39
+ annotations: { title: 'Read one category of my memory', readOnlyHint: false },
40
+ },
41
+ {
42
+ name: 'memory_pull',
43
+ description: "The user's full context card (longer than get_user_profile) plus what is new since you last pulled. Prefer get_user_profile at the start of a conversation; use this when you want everything you're allowed to see in one go.",
44
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
45
+ annotations: { title: 'Get my cross-AI profile', readOnlyHint: false, idempotentHint: true },
46
+ },
47
+ {
48
+ name: 'memory_search',
49
+ description: "Search the user's memory: facts always; their past conversations from other AIs too if the user gave you 'Everything' access. Use for questions like 'what did I tell ChatGPT about X'.",
50
+ inputSchema: {
51
+ type: 'object',
52
+ properties: {
53
+ query: { type: 'string', description: 'Words to look for, any language, e.g. "trip Lisbon" or "咖啡"' },
54
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
55
+ },
56
+ required: ['query'],
57
+ additionalProperties: false,
58
+ },
59
+ annotations: { title: 'Search my memory', readOnlyHint: false },
60
+ },
61
+ {
62
+ name: 'memory_read_conversation',
63
+ description: 'Read one past conversation found by memory_search (needs the user\'s "Everything" access).',
64
+ inputSchema: {
65
+ type: 'object',
66
+ properties: {
67
+ source: { type: 'string', description: 'The "client" field of a search result, e.g. "chatgpt"' },
68
+ conversation: { type: 'string', description: 'The "conv" field of a search result' },
69
+ },
70
+ required: ['source', 'conversation'],
71
+ additionalProperties: false,
72
+ },
73
+ annotations: { title: 'Read a past conversation', readOnlyHint: false },
74
+ },
75
+ {
76
+ name: 'memory_push',
77
+ description: "Save durable facts about the user so their other AIs learn them at the next sync. One fact per item, written as the user would say it (e.g. 'I prefer concise answers').",
78
+ inputSchema: {
79
+ type: 'object',
80
+ properties: {
81
+ items: {
82
+ type: 'array',
83
+ minItems: 1,
84
+ maxItems: 50,
85
+ items: {
86
+ type: 'object',
87
+ properties: {
88
+ text: { type: 'string', description: 'One fact, e.g. "I prefer concise answers" / "我在做一个开源笔记应用"' },
89
+ category: { type: 'string', enum: CATEGORIES.filter((c) => c !== 'ids'), description: 'Optional hint' },
90
+ sensitive: { type: 'boolean', description: 'true if this seems private (health, money, other people…)' },
91
+ },
92
+ required: ['text'],
93
+ },
94
+ },
95
+ },
96
+ required: ['items'],
97
+ additionalProperties: false,
98
+ },
99
+ annotations: { title: 'Remember facts about me' },
100
+ },
101
+ {
102
+ name: 'memory_organize',
103
+ description: "Only works if the user picked you to tidy up their memory (otherwise it says so). Returns a batch of messages the user wrote to their AIs. Read them, extract durable facts the user states about themselves (first person, short, one per item; skip requests, hypotheticals, other people's details, secrets), save them with memory_push, then call memory_organize again until it says nothing is left.",
104
+ inputSchema: { type: 'object', properties: { batch: { type: 'number', description: 'Messages per batch (default 20, max 50)' } }, additionalProperties: false },
105
+ annotations: { title: 'Help tidy up my memory', readOnlyHint: false },
106
+ },
107
+ {
108
+ name: 'memory_status',
109
+ description: 'When MindFerry last synced, how much it holds, and what you are allowed to see.',
110
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
111
+ annotations: { title: 'MindFerry status', readOnlyHint: true },
112
+ },
113
+ ];
114
+
115
+ const text = (t) => ({ content: [{ type: 'text', text: t }] });
116
+ const bilingual = (code, params) => `${messageFor(code, params, 'en')}\n${messageFor(code, params, 'zh')}`;
117
+
118
+ /** Lazy auto-sync: if the user enabled scheduled sync and it is overdue, sync now. */
119
+ async function maybeAutoSync(hub) {
120
+ const s = hub.read();
121
+ const mins = s.settings?.autoSyncMinutes || 0;
122
+ if (!mins) return false;
123
+ const last = s.lastSyncAt ? Date.parse(s.lastSyncAt) : 0;
124
+ if (Date.now() - last < mins * 60000) return false;
125
+ await hub.sync();
126
+ return true;
127
+ }
128
+
129
+ /**
130
+ * @param {object} [opts] remote=true: a web AI over the optional web connection (web ids allowed);
131
+ * readOnly=true: memory_push is not offered.
132
+ */
133
+ export function createMcpHandler(hub, clientId, { remote = false, readOnly = false } = {}) {
134
+ if (!clientInfo(clientId) || (!remote && clientInfo(clientId).kind !== 'mcp')) {
135
+ throw new FriendlyError('UNKNOWN_CLIENT', { id: String(clientId) + ' (use one of: ' + CLIENTS.filter((c) => c.kind === 'mcp').map((c) => c.id).join(', ') + ')' });
136
+ }
137
+ const me = clientName(clientId);
138
+
139
+ async function callTool(name, args = {}) {
140
+ if (name === 'get_user_profile') {
141
+ await maybeAutoSync(hub);
142
+ const r = await hub.pull(clientId, { action: 'profile' });
143
+ if (r.paused) return text(bilingual('PAUSED', { client: me }));
144
+ const p = hub.profile(clientId);
145
+ const cat = hub.catalog(clientId);
146
+ const s = hub.status();
147
+ const mine = s.clients.find((c) => c.id === clientId);
148
+ let out = p.text;
149
+ if (r.newItems.length && r.delta && !/First pull|第一次/.test(r.delta)) out += `\n---\n${r.delta}`;
150
+ out += `\n---\nCatalog (call memory_browse with a category for more): ${cat.map((c) => `${c.category} (${c.count})`).join(', ') || 'empty'}`;
151
+ out += `\nYou ${mine.rule.archiveAccess ? 'can' : 'cannot'} search the user's past conversations. Last sync: ${s.lastSyncAt || 'never'}.`;
152
+ if (s.items === 0) out += '\n(MindFerry is empty so far: the user can drop their ChatGPT/Claude/Gemini export into the MindFerry window to fill it.)';
153
+ return text(out);
154
+ }
155
+ if (name === 'memory_browse') {
156
+ const list = await hub.browse(clientId, String(args.category || 'all'), { limit: Math.min(100, Number(args.limit) || 30) });
157
+ if (!list.length) return text(`Nothing in "${args.category}" that you may see.`);
158
+ return text(list.map((x) => `- ${x.text} (${x.category}, ${x.date})`).join('\n'));
159
+ }
160
+ if (name === 'memory_pull') {
161
+ await maybeAutoSync(hub);
162
+ const r = await hub.pull(clientId);
163
+ if (r.paused) return text(bilingual('PAUSED', { client: me }));
164
+ const s = hub.status();
165
+ const empty = s.items === 0
166
+ ? '\n(MindFerry is empty so far: the user can drop their ChatGPT/Claude/Gemini export into the MindFerry window, run `mindferry`, to fill it.)'
167
+ : '';
168
+ return text(`${r.card}\n---\n${r.delta}\n(last sync: ${r.lastSyncAt || s.lastSyncAt || 'never'}; new for you: ${r.newCount}; archived messages: ${s.archive.messages})${empty}`);
169
+ }
170
+ if (name === 'memory_search') {
171
+ const q = String(args.query || '').trim();
172
+ if (!q) return { ...text('Empty query.'), isError: true };
173
+ const r = await hub.search(clientId, q, { limit: Math.min(50, Number(args.limit) || 10) });
174
+ const out = { facts: r.facts };
175
+ if (r.conversations) out.conversations = r.conversations;
176
+ else out.note = messageFor('ACCESS_FACTS_ONLY', { client: me }, 'en');
177
+ return text(JSON.stringify(out, null, 2));
178
+ }
179
+ if (name === 'memory_read_conversation') {
180
+ const msgs = await hub.readConversation(clientId, String(args.source || ''), String(args.conversation || ''));
181
+ if (!msgs.length) return text('No such conversation.');
182
+ return text(msgs.map((m) => `${m.role === 'user' ? 'User' : clientName(args.source)}: ${m.text}`).join('\n\n'));
183
+ }
184
+ if (name === 'memory_push') {
185
+ if (readOnly) return { ...text('Saving is turned off for this connection. The user can allow it in MindFerry.'), isError: true };
186
+ // Be forgiving about shape: models sometimes send `facts`, plain strings, or a single `text`.
187
+ let items = args.items ?? args.facts ?? args.memories ?? (args.text ? [args.text] : []);
188
+ if (!Array.isArray(items)) items = [items];
189
+ const entries = items.slice(0, 50)
190
+ .map((i) => (typeof i === 'string' ? { text: i } : i))
191
+ .filter((i) => i && typeof i.text === 'string' && i.text.trim())
192
+ .map((i) => ({ text: i.text, category: i.category, sensitivity: i.sensitive ? 'sensitive' : undefined }));
193
+ if (!entries.length) return { ...text('Nothing to save. Send {"items": [{"text": "I prefer concise answers"}]} — one fact per item.'), isError: true };
194
+ const r = await hub.submit(clientId, entries);
195
+ await hub.sync(); // a pushed fact is visible right away (to this AI and to the user's other AIs)
196
+ return text(`Saved ${r.accepted} new fact(s) (${r.duplicates} already known). Synced: the user's other AIs get them the next time they pull.`);
197
+ }
198
+ if (name === 'memory_organize') {
199
+ const r = await hub.organizeBatch(clientId, Math.max(1, Math.min(50, Number(args.batch) || 20)));
200
+ if (!r.messages.length) return text('Nothing left to tidy. Thank you!');
201
+ return text(`${r.messages.length} message(s) the user wrote (${r.remaining} more after these). Extract facts about the user, save them with memory_push, then call memory_organize again.\n\n` +
202
+ r.messages.map((m, i) => `[${i + 1}] (${m.from}${m.chat ? ' · ' + m.chat : ''}${m.at ? ' · ' + String(m.at).slice(0, 10) : ''})\n${m.text}`).join('\n\n'));
203
+ }
204
+ if (name === 'memory_status') {
205
+ const s = hub.status();
206
+ const mine = s.clients.find((c) => c.id === clientId);
207
+ return text(JSON.stringify({
208
+ lastSync: s.lastSyncAt, facts: s.items, archivedMessages: s.archive.messages, waitingForSync: s.inbox,
209
+ you: { id: clientId, access: mine.rule.preset, canSearchConversations: mine.rule.archiveAccess, paused: mine.paused, newForYou: mine.pendingOut },
210
+ }, null, 2));
211
+ }
212
+ const err = new Error(`Unknown tool: ${name}`);
213
+ err.rpc = -32602;
214
+ throw err;
215
+ }
216
+
217
+ /** Handle one parsed JSON-RPC message; returns a response object or null (notifications). */
218
+ return async function handle(msg) {
219
+ const { id, method, params } = msg || {};
220
+ const isNotification = id === undefined || id === null;
221
+ const ok = (result) => (isNotification ? null : { jsonrpc: '2.0', id, result });
222
+ const fail = (code, message) => (isNotification ? null : { jsonrpc: '2.0', id, error: { code, message } });
223
+ try {
224
+ switch (method) {
225
+ case 'initialize': {
226
+ const asked = params?.protocolVersion;
227
+ return ok({
228
+ protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
229
+ capabilities: { tools: { listChanged: false } },
230
+ serverInfo: { name: 'mindferry', title: 'MindFerry', version: VERSION },
231
+ instructions: INSTRUCTIONS,
232
+ });
233
+ }
234
+ case 'ping': return ok({});
235
+ case 'tools/list': return ok({ tools: readOnly ? TOOLS.filter((t) => t.name !== 'memory_push') : TOOLS });
236
+ case 'tools/call': {
237
+ try {
238
+ return ok(await callTool(params?.name, params?.arguments));
239
+ } catch (e) {
240
+ if (e.rpc === -32602) return fail(-32602, e.message);
241
+ const f = toFriendly(e);
242
+ return ok({ ...text(`${f.text('en')}\n${f.text('zh')}`), isError: true });
243
+ }
244
+ }
245
+ default:
246
+ if (method?.startsWith('notifications/')) return null;
247
+ return fail(-32601, `Method not found: ${method}`);
248
+ }
249
+ } catch (e) {
250
+ return fail(-32603, toFriendly(e).text('en'));
251
+ }
252
+ };
253
+ }
254
+
255
+ export async function runMcp(hub, clientId) {
256
+ let handle;
257
+ try { handle = createMcpHandler(hub, clientId); } catch (e) { console.error(toFriendly(e).text('en')); process.exit(2); }
258
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
259
+ const write = (o) => process.stdout.write(JSON.stringify(o) + '\n');
260
+ let chain = Promise.resolve();
261
+ rl.on('line', (line) => {
262
+ if (!line.trim()) return;
263
+ let msg;
264
+ try { msg = JSON.parse(line); } catch { write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); return; }
265
+ chain = chain.then(async () => {
266
+ const msgs = Array.isArray(msg) ? msg : [msg];
267
+ for (const m of msgs) { const r = await handle(m); if (r) write(r); }
268
+ });
269
+ });
270
+ await new Promise((r) => rl.on('close', r));
271
+ await chain;
272
+ }
package/src/remote.mjs ADDED
@@ -0,0 +1,180 @@
1
+ // Optional "web connection": lets web AIs that support custom MCP connectors (ChatGPT,
2
+ // Claude.ai, Grok, Le Chat, Perplexity…) fetch the user's memory themselves.
3
+ //
4
+ // Off by default. When the user turns it on:
5
+ // - a separate small HTTP server listens on 127.0.0.1 and serves ONLY the MCP endpoint
6
+ // (never the management UI), Streamable HTTP with plain JSON responses (no SSE);
7
+ // - each web AI gets its own long random token (in the URL path, because some connector
8
+ // UIs cannot send headers; `Authorization: Bearer` works too), read-only by default;
9
+ // - requests are rate-limited, every read is in the "who took what" log;
10
+ // - if `cloudflared` is installed, a Cloudflare quick tunnel gives a public HTTPS address
11
+ // with no account; it stops when MindFerry stops, when the user clicks Stop, or when the
12
+ // chosen time runs out.
13
+ import { createServer } from 'node:http';
14
+ import { spawn, execFileSync } from 'node:child_process';
15
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
16
+ import { clientInfo, CLIENTS } from './core/clients.mjs';
17
+ import { createMcpHandler } from './mcp/server.mjs';
18
+ import { FriendlyError } from './core/errors.mjs';
19
+
20
+ export const REMOTE_CLIENTS = ['chatgpt', 'claude-web', 'gemini-web', 'grok-web', 'other-mcp'];
21
+ const RATE = { windowMs: 60000, max: 60 };
22
+ const MAX_BODY = 1 << 20;
23
+
24
+ const newToken = () => randomBytes(24).toString('base64url');
25
+ const same = (a, b) => { const x = Buffer.from(String(a)); const y = Buffer.from(String(b)); return x.length === y.length && timingSafeEqual(x, y); };
26
+
27
+ export function findCloudflared() {
28
+ for (const cmd of ['cloudflared', '/opt/homebrew/bin/cloudflared', '/usr/local/bin/cloudflared', 'C:\\Program Files (x86)\\cloudflared\\cloudflared.exe', 'C:\\Program Files\\cloudflared\\cloudflared.exe']) {
29
+ try { execFileSync(cmd, ['--version'], { stdio: 'ignore', timeout: 4000 }); return cmd; } catch {}
30
+ }
31
+ return null;
32
+ }
33
+
34
+ export class Remote {
35
+ constructor(hub, { port = 7799 } = {}) {
36
+ this.hub = hub;
37
+ this.port = port;
38
+ this.server = null;
39
+ this.tunnel = null;
40
+ this.publicUrl = null;
41
+ this.until = null;
42
+ this.timer = null;
43
+ this.hits = new Map();
44
+ this.error = null;
45
+ }
46
+
47
+ /** Tokens live in the store so a restart keeps the same addresses (until rotated). */
48
+ async tokens() {
49
+ return this.hub.store.update((s) => {
50
+ s.remote ||= { tokens: {} };
51
+ for (const id of REMOTE_CLIENTS) s.remote.tokens[id] ||= { token: newToken(), write: false, createdAt: new Date().toISOString() };
52
+ return s.remote.tokens;
53
+ });
54
+ }
55
+
56
+ async rotate(clientId) {
57
+ if (!REMOTE_CLIENTS.includes(clientId)) throw new FriendlyError('UNKNOWN_CLIENT', { id: clientId }, 404);
58
+ return this.hub.store.update((s) => {
59
+ s.remote ||= { tokens: {} };
60
+ s.remote.tokens[clientId] = { token: newToken(), write: !!s.remote.tokens[clientId]?.write, createdAt: new Date().toISOString() };
61
+ });
62
+ }
63
+
64
+ async setWrite(clientId, write) {
65
+ if (!REMOTE_CLIENTS.includes(clientId)) throw new FriendlyError('UNKNOWN_CLIENT', { id: clientId }, 404);
66
+ await this.tokens();
67
+ return this.hub.store.update((s) => { s.remote.tokens[clientId].write = !!write; });
68
+ }
69
+
70
+ async status() {
71
+ const toks = await this.tokens();
72
+ const base = this.publicUrl || (this.server ? `http://127.0.0.1:${this.port}` : null);
73
+ return {
74
+ on: !!this.server,
75
+ tunnel: !!this.publicUrl,
76
+ cloudflared: this.cloudflared ?? (this.cloudflared = !!findCloudflared()),
77
+ until: this.until,
78
+ error: this.error,
79
+ clients: REMOTE_CLIENTS.map((id) => ({
80
+ id, write: !!toks[id].write,
81
+ url: base ? `${base}/mcp/${toks[id].token}` : null,
82
+ })),
83
+ };
84
+ }
85
+
86
+ #limited(key) {
87
+ const now = Date.now();
88
+ const list = (this.hits.get(key) || []).filter((t) => now - t < RATE.windowMs);
89
+ list.push(now);
90
+ this.hits.set(key, list);
91
+ return list.length > RATE.max;
92
+ }
93
+
94
+ async #handle(req, res) {
95
+ const send = (status, body, headers = {}) => {
96
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', ...headers });
97
+ res.end(body === undefined ? '' : JSON.stringify(body));
98
+ };
99
+ const url = new URL(req.url, 'http://x');
100
+ const m = url.pathname.match(/^\/mcp(?:\/([\w-]{20,64}))?\/?$/);
101
+ if (!m) return send(404, { error: 'not found' });
102
+ const bearer = (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
103
+ const given = m[1] || bearer;
104
+ const toks = await this.tokens();
105
+ const clientId = given ? REMOTE_CLIENTS.find((id) => same(toks[id].token, given)) : null;
106
+ if (!clientId) { await new Promise((r) => setTimeout(r, 300)); return send(401, { error: 'unauthorized' }); }
107
+ if (this.#limited(clientId)) return send(429, { error: 'too many requests' }, { 'Retry-After': '30' });
108
+ if (req.method === 'GET') return send(405, { error: 'this server does not stream; POST JSON-RPC' }, { Allow: 'POST' });
109
+ if (req.method === 'DELETE') return send(200, {});
110
+ if (req.method !== 'POST') return send(405, { error: 'method not allowed' }, { Allow: 'POST' });
111
+ let size = 0;
112
+ const chunks = [];
113
+ for await (const c of req) { size += c.length; if (size > MAX_BODY) return send(413, { error: 'too large' }); chunks.push(c); }
114
+ let msg;
115
+ try { msg = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return send(400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
116
+ const handle = createMcpHandler(this.hub, clientId, { remote: true, readOnly: !toks[clientId].write });
117
+ const msgs = Array.isArray(msg) ? msg : [msg];
118
+ // Every call in a batch counts against the limit (not just the HTTP request), and batches are small.
119
+ if (msgs.length > 20) return send(413, { error: 'batch too large (max 20)' });
120
+ for (let k = 1; k < msgs.length; k++) if (this.#limited(clientId)) return send(429, { error: 'too many requests' }, { 'Retry-After': '30' });
121
+ const out = [];
122
+ for (const one of msgs) { const r = await handle(one); if (r) out.push(r); }
123
+ if (!out.length) return send(202);
124
+ const sid = req.headers['mcp-session-id'] || randomBytes(12).toString('hex');
125
+ return send(200, Array.isArray(msg) ? out : out[0], { 'Mcp-Session-Id': sid });
126
+ }
127
+
128
+ /** Turn the web connection on for `hours` (0 = until MindFerry closes). */
129
+ async start({ hours = 1, tunnel = true } = {}) {
130
+ await this.tokens();
131
+ this.error = null;
132
+ if (!this.server) {
133
+ this.server = createServer((req, res) => this.#handle(req, res).catch(() => { try { res.writeHead(500); res.end(); } catch {} }));
134
+ await new Promise((resolve, reject) => {
135
+ this.server.once('error', reject);
136
+ this.server.listen(this.port, '127.0.0.1', () => { this.port = this.server.address().port; resolve(); });
137
+ }).catch((e) => { this.server = null; throw e; });
138
+ }
139
+ if (tunnel && !this.tunnel) {
140
+ const bin = findCloudflared();
141
+ this.cloudflared = !!bin;
142
+ if (bin) await this.#openTunnel(bin);
143
+ }
144
+ clearTimeout(this.timer);
145
+ this.until = hours > 0 ? new Date(Date.now() + hours * 3600000).toISOString() : null;
146
+ if (hours > 0) this.timer = setTimeout(() => this.stop(), hours * 3600000).unref?.() ?? null;
147
+ return this.status();
148
+ }
149
+
150
+ #openTunnel(bin) {
151
+ return new Promise((resolve) => {
152
+ const p = spawn(bin, ['tunnel', '--no-autoupdate', '--url', `http://127.0.0.1:${this.port}`], { stdio: ['ignore', 'pipe', 'pipe'] });
153
+ this.tunnel = p;
154
+ process.once('exit', () => { try { p.kill(); } catch {} });
155
+ let done = false;
156
+ const finish = () => { if (!done) { done = true; resolve(); } };
157
+ const onData = (d) => {
158
+ const hit = String(d).match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);
159
+ if (hit) { this.publicUrl = hit[0]; finish(); }
160
+ };
161
+ p.stdout.on('data', onData);
162
+ p.stderr.on('data', onData);
163
+ p.on('exit', () => { this.tunnel = null; this.publicUrl = null; finish(); });
164
+ p.on('error', (e) => { this.error = String(e.message || e); this.tunnel = null; finish(); });
165
+ setTimeout(() => { if (!this.publicUrl) this.error = 'tunnel did not start in 30 s'; finish(); }, 30000).unref?.();
166
+ });
167
+ }
168
+
169
+ async stop() {
170
+ clearTimeout(this.timer);
171
+ this.until = null;
172
+ if (this.tunnel) { try { this.tunnel.kill(); } catch {} this.tunnel = null; }
173
+ this.publicUrl = null;
174
+ if (this.server) { const srv = this.server; this.server = null; await new Promise((r) => { srv.close(() => r()); srv.closeAllConnections?.(); }); }
175
+ return this.status();
176
+ }
177
+ }
178
+
179
+ export const remoteClientName = (id, lang = 'en') => clientInfo(id)?.name[lang] || id;
180
+ export { CLIENTS };