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,7 @@
1
+ # Weekend plans
2
+
3
+ ## User
4
+ I'm training for a half marathon in March. Keep suggestions short.
5
+
6
+ ## Claude
7
+ Great goal! Here's a light weekend plan…
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "mindferry",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Sync what your AIs know about you — ChatGPT, Claude, Gemini, Grok, DeepSeek, Claude Code, Codex, Cursor — locally. Imports chat exports, per-AI privacy rules, MCP server. Zero dependencies.",
5
+ "mcpName": "io.github.cmy515006420/mindferry",
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "keywords": [
9
+ "mcp",
10
+ "mcp-server",
11
+ "model-context-protocol",
12
+ "ai-memory",
13
+ "memory",
14
+ "personal-context",
15
+ "chatgpt",
16
+ "claude",
17
+ "claude-code",
18
+ "codex",
19
+ "gemini",
20
+ "grok",
21
+ "deepseek",
22
+ "cursor",
23
+ "chatgpt-export",
24
+ "local-first",
25
+ "privacy",
26
+ "llm"
27
+ ],
28
+ "homepage": "https://github.com/cmy515006420/mindferry#readme",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/cmy515006420/mindferry.git"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/cmy515006420/mindferry/issues"
35
+ },
36
+ "engines": {
37
+ "node": ">=22"
38
+ },
39
+ "bin": {
40
+ "mindferry": "bin/mindferry.mjs"
41
+ },
42
+ "files": [
43
+ "bin/",
44
+ "src/",
45
+ "examples/",
46
+ "LICENSE",
47
+ "README.md",
48
+ "README.zh-CN.md"
49
+ ],
50
+ "scripts": {
51
+ "test": "node --test \"test/*.test.mjs\"",
52
+ "scan": "node scripts/privacy-scan.mjs",
53
+ "hooks": "node scripts/install-hooks.mjs",
54
+ "start": "node bin/mindferry.mjs start",
55
+ "smoke": "node scripts/smoke.mjs"
56
+ }
57
+ }
@@ -0,0 +1,204 @@
1
+ // One-click connect/disconnect of local AI apps.
2
+ // Uses each app's own official command when it has one (claude / codex / gemini "mcp add"),
3
+ // otherwise edits its JSON config with a timestamped backup. Every change is reversible
4
+ // with disconnect(). Nothing is touched until the user asks for it.
5
+ import { spawnSync } from 'node:child_process';
6
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, copyFileSync, cpSync, rmSync } from 'node:fs';
7
+ import { homedir, tmpdir } from 'node:os';
8
+ import { join, dirname, resolve } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { FriendlyError } from './core/errors.mjs';
11
+ import { clientInfo, clientName } from './core/clients.mjs';
12
+
13
+ export const SERVER_NAME = 'mindferry';
14
+ export const BIN = resolve(dirname(fileURLToPath(import.meta.url)), '../bin/mindferry.mjs');
15
+
16
+ function dataEnv() {
17
+ return process.env.MINDFERRY_DATA_DIR ? { MINDFERRY_DATA_DIR: process.env.MINDFERRY_DATA_DIR } : null;
18
+ }
19
+
20
+ const ROOT = resolve(dirname(BIN), '..');
21
+
22
+ /** True when we run from a cache that may be cleaned later (npx, a temp folder). */
23
+ export function isTransient(bin = BIN) {
24
+ return /[\\/]_npx[\\/]/.test(bin) || bin.startsWith(tmpdir());
25
+ }
26
+
27
+ /**
28
+ * The path AI apps should start. From a durable install that is this copy; from npx we
29
+ * copy the (dependency-free) app into ~/.mindferry/app so the registration keeps working.
30
+ */
31
+ function stableBin({ install = false } = {}) {
32
+ if (!isTransient()) return BIN;
33
+ const dest = join(homedir(), '.mindferry', 'app');
34
+ const bin = join(dest, 'bin', 'mindferry.mjs');
35
+ if (install) {
36
+ rmSync(dest, { recursive: true, force: true });
37
+ mkdirSync(dest, { recursive: true });
38
+ for (const part of ['bin', 'src', 'package.json', 'LICENSE']) {
39
+ if (existsSync(join(ROOT, part))) cpSync(join(ROOT, part), join(dest, part), { recursive: true });
40
+ }
41
+ }
42
+ return bin;
43
+ }
44
+
45
+ export function serverCommand(clientId, opts) {
46
+ return { command: process.execPath, args: [stableBin(opts), 'mcp', '--client', clientId], env: dataEnv() };
47
+ }
48
+
49
+ function jsonConfigPath(clientId) {
50
+ const home = homedir();
51
+ if (clientId === 'claude-desktop') {
52
+ if (process.platform === 'darwin') return join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
53
+ if (process.platform === 'win32') return join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json');
54
+ return join(home, '.config', 'Claude', 'claude_desktop_config.json');
55
+ }
56
+ if (clientId === 'cursor') return join(home, '.cursor', 'mcp.json');
57
+ if (clientId === 'gemini-cli') return join(home, '.gemini', 'settings.json');
58
+ return null;
59
+ }
60
+
61
+ function codexConfigPath() {
62
+ return join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'config.toml');
63
+ }
64
+
65
+ const tomlStr = (v) => JSON.stringify(v); // TOML basic strings share JSON escaping for our values
66
+ function codexBlock(c) {
67
+ let b = `[mcp_servers.${SERVER_NAME}]\ncommand = ${tomlStr(c.command)}\nargs = [${c.args.map(tomlStr).join(', ')}]\n`;
68
+ if (c.env) b += `env = { MINDFERRY_DATA_DIR = ${tomlStr(c.env.MINDFERRY_DATA_DIR)} }\n`;
69
+ return b;
70
+ }
71
+ // Remove our own [mcp_servers.mindferry] table (and its sub-tables) from a TOML text.
72
+ function stripCodexBlock(text) {
73
+ const lines = text.split('\n');
74
+ const out = [];
75
+ let skipping = false;
76
+ for (const line of lines) {
77
+ const header = line.match(/^\s*\[([^\]]+)\]\s*$/);
78
+ if (header) skipping = header[1].trim() === `mcp_servers.${SERVER_NAME}` || header[1].trim().startsWith(`mcp_servers.${SERVER_NAME}.`);
79
+ if (!skipping) out.push(line);
80
+ }
81
+ return out.join('\n').replace(/\n{3,}/g, '\n\n');
82
+ }
83
+
84
+ const CLI = {
85
+ 'claude-code': {
86
+ cli: 'claude',
87
+ add: (c) => ['mcp', 'add', '--scope', 'user', SERVER_NAME, ...(c.env ? ['-e', `MINDFERRY_DATA_DIR=${c.env.MINDFERRY_DATA_DIR}`] : []), '--', c.command, ...c.args],
88
+ remove: () => ['mcp', 'remove', '--scope', 'user', SERVER_NAME],
89
+ },
90
+ };
91
+
92
+ /** Copy-paste snippets for every MCP app (also shown on the Connect page). */
93
+ export { codexBlock, stripCodexBlock };
94
+
95
+ export function snippets() {
96
+ const q = JSON.stringify;
97
+ const out = {};
98
+ for (const id of ['claude-code']) {
99
+ const c = serverCommand(id);
100
+ out[id] = [CLI[id].cli, ...CLI[id].add(c)].map((a) => (/[\s"']/.test(a) ? q(a) : a)).join(' ');
101
+ }
102
+ const json = (id) => {
103
+ const c = serverCommand(id);
104
+ return JSON.stringify({ mcpServers: { [SERVER_NAME]: { command: c.command, args: c.args, ...(c.env ? { env: c.env } : {}) } } }, null, 2);
105
+ };
106
+ out.codex = codexBlock(serverCommand('codex'));
107
+ out['gemini-cli'] = json('gemini-cli');
108
+ out['claude-desktop'] = json('claude-desktop');
109
+ out.cursor = json('cursor');
110
+ out['grok-bot'] = json('grok-bot');
111
+ out['other-mcp'] = json('other-mcp');
112
+ return out;
113
+ }
114
+
115
+ function run(cli, args) {
116
+ // When MindFerry itself was started from inside Claude Code, the `claude` CLI refuses to run
117
+ // nested unless this marker is removed; it only affects this one child process.
118
+ const env = { ...process.env };
119
+ delete env.CLAUDECODE;
120
+ const r = spawnSync(cli, args, { encoding: 'utf8', timeout: 30000, env });
121
+ if (r.error?.code === 'ENOENT') return { missing: true };
122
+ return { ok: r.status === 0, out: (r.stdout || '') + (r.stderr || '') };
123
+ }
124
+
125
+ function backup(file) {
126
+ if (!existsSync(file)) return null;
127
+ const b = `${file}.bak-mindferry-${new Date().toISOString().replace(/[:.]/g, '-')}`;
128
+ copyFileSync(file, b);
129
+ return b;
130
+ }
131
+
132
+ function editJson(file, fn) {
133
+ let cfg = {};
134
+ if (existsSync(file)) {
135
+ const raw = readFileSync(file, 'utf8');
136
+ try { cfg = raw.trim() ? JSON.parse(raw) : {}; } catch { throw new FriendlyError('CONNECT_FAILED', { name: file, detail: 'its settings file is not valid JSON, so it was left untouched' }); }
137
+ }
138
+ const b = backup(file);
139
+ fn(cfg);
140
+ mkdirSync(dirname(file), { recursive: true });
141
+ writeFileSync(file, JSON.stringify(cfg, null, 2) + '\n');
142
+ return b;
143
+ }
144
+
145
+ /**
146
+ * Connect a local AI app to MindFerry.
147
+ * @returns {{ok: true, how: string, backup?: string, undo: string, restart?: boolean}}
148
+ */
149
+ export function connect(clientId) {
150
+ const info = clientInfo(clientId);
151
+ if (!info || info.kind !== 'mcp') throw new FriendlyError('UNKNOWN_CLIENT', { id: clientId });
152
+ const name = clientName(clientId);
153
+ const c = serverCommand(clientId, { install: true });
154
+ if (CLI[clientId]) {
155
+ const { cli } = CLI[clientId];
156
+ run(cli, CLI[clientId].remove()); // idempotent: replace an older registration
157
+ const r = run(cli, CLI[clientId].add(c));
158
+ if (r.missing) throw new FriendlyError('CONNECT_NO_CLI', { cli, name });
159
+ if (!r.ok) throw new FriendlyError('CONNECT_FAILED', { name, detail: r.out.trim().split('\n').pop()?.slice(0, 160) || 'unknown error' });
160
+ return { ok: true, how: `Claude Code's MCP list (${cli} mcp add --scope user)`, undo: `mindferry disconnect ${clientId}` };
161
+ }
162
+ if (clientId === 'codex') {
163
+ const file = codexConfigPath();
164
+ const before = existsSync(file) ? readFileSync(file, 'utf8') : '';
165
+ const b = backup(file);
166
+ mkdirSync(dirname(file), { recursive: true });
167
+ const kept = stripCodexBlock(before).trimEnd();
168
+ writeFileSync(file, (kept ? kept + '\n\n' : '') + codexBlock(c));
169
+ return { ok: true, how: file, backup: b, undo: `mindferry disconnect ${clientId}`, restart: true };
170
+ }
171
+ const file = jsonConfigPath(clientId);
172
+ if (!file) throw new FriendlyError('CONNECT_NO_CLI', { cli: 'auto-connect', name });
173
+ const b = editJson(file, (cfg) => {
174
+ cfg.mcpServers ||= {};
175
+ cfg.mcpServers[SERVER_NAME] = { command: c.command, args: c.args, ...(c.env ? { env: c.env } : {}) };
176
+ });
177
+ return { ok: true, how: file, backup: b, undo: `mindferry disconnect ${clientId}`, restart: true };
178
+ }
179
+
180
+ export function disconnect(clientId) {
181
+ const info = clientInfo(clientId);
182
+ if (!info || info.kind !== 'mcp') throw new FriendlyError('UNKNOWN_CLIENT', { id: clientId });
183
+ if (CLI[clientId]) {
184
+ const r = run(CLI[clientId].cli, CLI[clientId].remove());
185
+ if (r.missing) throw new FriendlyError('CONNECT_NO_CLI', { cli: CLI[clientId].cli, name: clientName(clientId) });
186
+ return { ok: true };
187
+ }
188
+ if (clientId === 'codex') {
189
+ const file = codexConfigPath();
190
+ if (!existsSync(file)) return { ok: true };
191
+ const b = backup(file);
192
+ writeFileSync(file, stripCodexBlock(readFileSync(file, 'utf8')).trimEnd() + '\n');
193
+ return { ok: true, backup: b };
194
+ }
195
+ const file = jsonConfigPath(clientId);
196
+ if (!file || !existsSync(file)) return { ok: true };
197
+ const b = editJson(file, (cfg) => { if (cfg.mcpServers) delete cfg.mcpServers[SERVER_NAME]; });
198
+ return { ok: true, backup: b };
199
+ }
200
+
201
+ export function canAutoConnect(clientId) {
202
+ if (CLI[clientId]) return !run(CLI[clientId].cli, ['--version']).missing;
203
+ return clientId === 'codex' || !!jsonConfigPath(clientId);
204
+ }
@@ -0,0 +1,144 @@
1
+ // Raw conversation archive: every imported message (user + assistant), secrets masked,
2
+ // stored locally as JSON Lines. Facts in store.json are an index on top of this.
3
+ import { appendFileSync, readFileSync, existsSync, writeFileSync, renameSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { maskSecrets, hash, normalize } from './text.mjs';
6
+
7
+ const MAX_MSG = 20000;
8
+
9
+ export class Archive {
10
+ constructor(dir) {
11
+ this.file = join(dir, 'archive.jsonl');
12
+ }
13
+
14
+ *iter() {
15
+ if (!existsSync(this.file)) return;
16
+ const data = readFileSync(this.file, 'utf8');
17
+ let start = 0;
18
+ while (start < data.length) {
19
+ let end = data.indexOf('\n', start);
20
+ if (end < 0) end = data.length;
21
+ const line = data.slice(start, end);
22
+ start = end + 1;
23
+ if (!line.trim()) continue;
24
+ try { yield JSON.parse(line); } catch { /* skip a torn line */ }
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Append messages; skips ones already archived. Call while holding the store lock.
30
+ * @param {{client, conv?, title?, role, text, at?}[]} msgs
31
+ */
32
+ add(msgs) {
33
+ const seen = new Set();
34
+ for (const m of this.iter()) seen.add(m.h);
35
+ const lines = [];
36
+ let added = 0;
37
+ for (const m of msgs) {
38
+ if (!m.text || !String(m.text).trim()) continue;
39
+ const text = maskSecrets(String(m.text).slice(0, MAX_MSG)).text;
40
+ const role = m.role === 'assistant' ? 'assistant' : 'user';
41
+ const h = hash(`${m.client}|${role}|${m.conv || ''}|${normalize(text)}`);
42
+ if (seen.has(h)) continue;
43
+ seen.add(h);
44
+ lines.push(JSON.stringify({ h, client: m.client, conv: m.conv || null, title: m.title ? String(m.title).slice(0, 200) : null, role, text, at: m.at || null }));
45
+ added++;
46
+ }
47
+ if (lines.length) appendFileSync(this.file, lines.join('\n') + '\n', { mode: 0o600 });
48
+ return added;
49
+ }
50
+
51
+ stats() {
52
+ const byClient = {};
53
+ const convs = new Set();
54
+ let total = 0;
55
+ for (const m of this.iter()) {
56
+ total++;
57
+ byClient[m.client] = (byClient[m.client] || 0) + 1;
58
+ if (m.conv) convs.add(m.client + '|' + m.conv);
59
+ }
60
+ return { messages: total, conversations: convs.size, byClient };
61
+ }
62
+
63
+ /** Simple local full-text search (words + CJK bigrams), newest first among equals. */
64
+ search(query, { limit = 20, clients = null } = {}) {
65
+ const toks = tokens(query);
66
+ if (!toks.length) return [];
67
+ const hits = [];
68
+ for (const m of this.iter()) {
69
+ if (clients && !clients.includes(m.client)) continue;
70
+ const lower = m.text.toLowerCase();
71
+ let matched = 0;
72
+ for (const t of toks) if (lower.includes(t)) matched++;
73
+ const score = matched / toks.length;
74
+ if (score < (toks.length <= 2 ? 1 : 0.6)) continue;
75
+ hits.push({ score, m });
76
+ }
77
+ hits.sort((a, b) => b.score - a.score || String(b.m.at || '').localeCompare(String(a.m.at || '')));
78
+ return hits.slice(0, limit).map(({ score, m }) => ({
79
+ client: m.client, conv: m.conv, title: m.title, role: m.role, at: m.at, score: +score.toFixed(2),
80
+ snippet: snippet(m.text, toks),
81
+ }));
82
+ }
83
+
84
+ conversation(client, conv) {
85
+ const out = [];
86
+ for (const m of this.iter()) if (m.client === client && m.conv === conv) out.push({ role: m.role, text: m.text, at: m.at, title: m.title });
87
+ return out;
88
+ }
89
+
90
+ /** Every archived message (for export). */
91
+ all() { return [...this.iter()].map(({ h, ...m }) => m); }
92
+
93
+ reload() {}
94
+
95
+ /**
96
+ * Blank out sentences the user deleted for good. Each message keeps its id (so importing the
97
+ * same export again doesn't bring the words back); only the text changes. Returns how many
98
+ * messages changed. Call while holding the store lock.
99
+ */
100
+ redact(phrases) {
101
+ const list = phrases.map((p) => String(p).trim()).filter((p) => p.length >= 4)
102
+ .map((p) => p.replace(/[\s.。!!??;;,,]+$/u, ''))
103
+ .flatMap((p) => [p, p.replace(/^(?:我|I(?:'m| am)?\s)/i, '').trim()])
104
+ .filter((p, i, all) => p.length >= 4 && all.indexOf(p) === i)
105
+ .sort((a, b) => b.length - a.length);
106
+ if (!list.length || !existsSync(this.file)) return 0;
107
+ const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
108
+ // Case, spaces and line breaks don't matter: "I TAKE PROZAC EVERY\nMORNING" is the same words.
109
+ const re = new RegExp(list.map((x) => esc(x).replace(/\s+/g, '\\s+')).join('|'), 'gi');
110
+ let changed = 0;
111
+ const out = [];
112
+ for (const m of this.iter()) {
113
+ const text = m.text.replace(re, '[removed]');
114
+ if (text !== m.text) changed++;
115
+ out.push(JSON.stringify({ ...m, text }));
116
+ }
117
+ if (changed) { writeFileSync(this.file + '.tmp', out.join('\n') + '\n', { mode: 0o600 }); renameSync(this.file + '.tmp', this.file); }
118
+ return changed;
119
+ }
120
+
121
+ clear() {
122
+ if (existsSync(this.file)) { writeFileSync(this.file + '.tmp', ''); renameSync(this.file + '.tmp', this.file); }
123
+ }
124
+ }
125
+
126
+ export function tokens(q) {
127
+ const s = String(q).toLowerCase();
128
+ const out = new Set();
129
+ for (const w of s.match(/[a-z0-9][a-z0-9'+#.-]*/g) || []) if (w.length >= 2) out.add(w);
130
+ for (const run of s.match(/[一-鿿]+/g) || []) {
131
+ if (run.length === 1) out.add(run);
132
+ for (let i = 0; i + 1 < run.length; i++) out.add(run.slice(i, i + 2));
133
+ }
134
+ return [...out];
135
+ }
136
+
137
+ function snippet(text, toks) {
138
+ const lower = text.toLowerCase();
139
+ let pos = -1;
140
+ for (const t of toks) { pos = lower.indexOf(t); if (pos >= 0) break; }
141
+ const start = Math.max(0, pos - 80);
142
+ const s = text.slice(start, start + 280).replace(/\s+/g, ' ');
143
+ return (start > 0 ? '…' : '') + s + (start + 280 < text.length ? '…' : '');
144
+ }
@@ -0,0 +1,64 @@
1
+ // Context cards: the text each AI receives (pasted for web AIs, returned by MCP for local ones).
2
+ import { allowed, ruleFor } from './rules.mjs';
3
+
4
+ export const CATEGORY_LABELS = {
5
+ identity: { zh: '基本信息', en: 'About me' },
6
+ work: { zh: '工作职业', en: 'Work' },
7
+ skills: { zh: '技能', en: 'Skills' },
8
+ projects: { zh: '项目', en: 'Projects' },
9
+ goals: { zh: '目标', en: 'Goals' },
10
+ preferences: { zh: '偏好习惯', en: 'Preferences' },
11
+ communication: { zh: '沟通方式', en: 'How to talk to me' },
12
+ location: { zh: '所在地', en: 'Location' },
13
+ contact: { zh: '联系方式', en: 'Contact' },
14
+ health: { zh: '健康', en: 'Health' },
15
+ finance: { zh: '财务', en: 'Finance' },
16
+ ids: { zh: '证件号码', en: 'ID numbers' },
17
+ others: { zh: '他人信息', en: 'Other people' },
18
+ other: { zh: '其他', en: 'Other' },
19
+ };
20
+
21
+ const ORDER = ['communication', 'identity', 'work', 'projects', 'goals', 'skills', 'location', 'preferences', 'other', 'contact', 'health', 'finance', 'others'];
22
+
23
+ const HEADER = {
24
+ zh: (d) => `# 关于我(AI 记忆中介同步于 ${d})\n以下是我在其他 AI 里提过的个人背景,请在回答时参考,不必复述。若与我之后的说法冲突,以我最新的说法为准。`,
25
+ en: (d) => `# About me (synced by MindFerry on ${d})\nBackground I've shared with other AIs. Use it when helpful; no need to repeat it back. If anything conflicts with what I say later, my latest statement wins.`,
26
+ };
27
+
28
+ function pickLang(rule, items, uiLang) {
29
+ if (rule.lang !== 'auto') return rule.lang;
30
+ if (uiLang === 'zh' || uiLang === 'en') return uiLang; // follow the language the user reads the app in
31
+ const zh = items.filter((i) => i.lang === 'zh').length;
32
+ if (!items.length) return uiLang || 'zh';
33
+ return zh * 2 >= items.length ? 'zh' : 'en';
34
+ }
35
+
36
+ /** Build the full context card for a client. */
37
+ export function buildCard(state, clientId, now = new Date().toISOString()) {
38
+ const rule = ruleFor(state.clients[clientId], clientId);
39
+ const items = state.items
40
+ .filter((i) => allowed(i, clientId, rule))
41
+ .sort((a, b) => ORDER.indexOf(a.category) - ORDER.indexOf(b.category) || (b.observedAt > a.observedAt ? 1 : -1));
42
+ const lang = pickLang(rule, items, state.settings?.uiLang);
43
+ let out = HEADER[lang](now.slice(0, 10));
44
+ let used = out.length;
45
+ const included = [];
46
+ let lastCat = null;
47
+ for (const i of items) {
48
+ const head = i.category !== lastCat ? `\n\n## ${CATEGORY_LABELS[i.category][lang]}` : '';
49
+ const line = `\n- ${i.text}`;
50
+ if (used + head.length + line.length > rule.maxChars) break;
51
+ out += head + line;
52
+ used += head.length + line.length;
53
+ lastCat = i.category;
54
+ included.push(i.id);
55
+ }
56
+ return { text: out + '\n', lang, itemIds: included, total: items.length };
57
+ }
58
+
59
+ /** Short delta text for "what's new since your last sync". */
60
+ export function buildDelta(items, lang = 'zh') {
61
+ if (!items.length) return lang === 'zh' ? '(没有新的信息)' : '(nothing new)';
62
+ const head = lang === 'zh' ? '自上次同步以来的新信息:' : 'New since your last sync:';
63
+ return head + '\n' + items.map((i) => `- ${i.text}${i.conflict ? (lang === 'zh' ? '(更新:替代了旧说法)' : ' (updated: replaces an older statement)') : ''}`).join('\n');
64
+ }
@@ -0,0 +1,81 @@
1
+ // Category + sensitivity classifier (rule-based, zh + en). No network, no model.
2
+ import { maskSecrets, findContacts } from './text.mjs';
3
+
4
+ export const SENSITIVITY = ['public', 'personal', 'sensitive', 'secret', 'uncertain'];
5
+ // Rank used for "most sensitive wins". uncertain ranks between sensitive and secret.
6
+ export const SENS_RANK = { public: 0, personal: 1, sensitive: 2, uncertain: 2.5, secret: 3 };
7
+
8
+ export const CATEGORIES = [
9
+ 'identity', 'work', 'skills', 'projects', 'goals', 'preferences', 'communication',
10
+ 'location', 'contact', 'health', 'finance', 'ids', 'others', 'other',
11
+ ];
12
+
13
+ export const CATEGORY_DEFAULT_SENS = {
14
+ identity: 'personal', work: 'personal', skills: 'public', projects: 'personal', goals: 'personal',
15
+ preferences: 'public', communication: 'public', location: 'personal',
16
+ contact: 'sensitive', health: 'sensitive', finance: 'sensitive', ids: 'secret',
17
+ others: 'sensitive', other: 'uncertain',
18
+ };
19
+
20
+ // Order = tie-break priority (sensitive first).
21
+ const KEYWORDS = [
22
+ ['ids', /身份证|护照|驾照|驾驶证|社保号|医保卡号|签证号|\bpassport\b|\bssn\b|social security|driver'?s licen[cs]e|national id/i],
23
+ ['health', /自残|割腕|自伤|试管婴儿|做试管|吸毒|嗑药|大麻|冰毒|海洛因|摇头丸|\bi (?:cut|hurt|burn) myself\b|\bself[- ]?harm|\bsex work|\bi(?:'m| am| work as) an escort\b|\bmethadone\b|\blithium\b(?![- ](?:ion|battery|batteries|cell|polymer))|\btestosterone\b|\bHRT\b|\bestrogen\b|\boestrogen\b|\bozempic\b|\bwegovy\b|\binsulin\b|\bi(?:'m| am) (?:medically )?transitioning\b(?! (?:to|from|into|out of) (?:a |an |the |my )?(?:new |different )?(?:role|job|team|position|career|management|company|field|industry|stack|framework|language|codebase))|\bgender transition|\bNA meetings?\b|\bIVF\b|\bmiscarri|\b(?:do|doing|did|does|on|snort(?:ing|ed)?|bump of|line of|lines of|some|into) coke\b(?! zero|-zero| cola|-cola)|\bcocaine\b|\bmdma\b|\bmolly\b(?=\s*(?:on|at|every|sometimes|when|[,.!]|$))|\bketamine\b|\bLSD\b|\bshrooms\b|\bmagic mushrooms\b|\bmeth\b|\bheroin\b|\bopioid|\bfentanyl|\bxtc\b|\becstasy\b|堕胎|流产|人流|戒酒会|喝酒|酗酒|abortion|miscarriage|\bin recovery\b|\brecovering (?:alcoholic|addict)|alcoholics anonymous|narcotics anonymous|\bi(?:'m| am) in (?:aa|na)\b|\bget(?:ting)? (?:wasted|hammered|blackout drunk)|病|医院|医生说|看医生|吃药|药物|抑郁|焦虑|过敏|怀孕|孕|血压|血糖|糖尿病|手术|诊断|体检|心理咨询|失眠|癌|残疾|therap(y|ist)|diagnos|allerg|medication|prescri|pregnan|depress|anxiety|diabet|surgery|hospital|blood pressure|adhd|insomnia|cancer|disabilit|mental health|酗酒|喝太多|戒酒|戒烟|戒毒|上瘾|成瘾|赌博|赌瘾|吸毒|自残|轻生|进食障碍|暴食|厌食|\bdrink(?:ing)? too much|\bdrunk\b|\balcohol|\bsober\b|\bsobriety|\brehab\b|\baddict|\bgambl|\bweed\b|\bcannabis|\bsmok(?:e|ing) (?:too much|a pack)|\bquit (?:drinking|smoking)|\bself[- ]harm|\bsuicid|\beating disorder|\bbinge|\brelapse|\bhangover|\bhung ?over|prozac|zoloft|lexapro|xanax|adderall|ritalin|\bssris?\b|antidepress|\bmeds\b|\bpills?\b|counsell?or|counsell?ing|psychiatr|psycholog|\bhiv\b|\bstd\b|\bsti\b|chemo|\bpanic attack|bipolar|ptsd|\bocd\b|\bautis|抗抑郁|安眠药|宿醉|心理医生|心理治疗|精神科|艾滋|HIV|化疗|惊恐|双相|强迫症|自闭/i],
24
+ ['finance', /工资|薪水|收入|存款|贷款|房贷|车贷|负债|欠款|股票|基金|理财|投资|年薪|月薪|信用卡|银行卡|银行账户|资产|税|salary|income|\bdebt|\bloan|mortgage|savings|invest|bank account|credit card|net worth|\btax(es)?\b|\bpaycheck/i],
25
+ ['others', /孙子|孙女|外孙|爷爷|奶奶|姥姥|姥爷|外公|外婆|老伴|儿媳|女婿|老婆|妻子|丈夫|老公|爱人|孩子|儿子|女儿|爸爸|妈妈|父亲|母亲|父母|哥哥|姐姐|弟弟|妹妹|朋友|同事|老板|上司|男朋友|女朋友|对象|室友|带娃|\bi have (?:a |an |one |two |three |four |\d+ )?(?:young |little |grown(?:-up)? )?(?:kids?|children|sons?|daughters?|baby|toddler|stepkids?)\b|\bmy (wife|husband|son|daughter|kids?|children|mom|mum|dad|mother|father|parents?|brother|sister|friends?|boss|colleagues?|coworkers?|girlfriend|boyfriend|partner|roommate|grandson|granddaughter|grandkids?|grandchildren|grandma|grandpa|grandmother|grandfather)\b/i],
26
+ ['contact', /手机号|电话号|微信号|邮箱是|住址|家庭地址|门牌|\bphone number|\bemail (address )?is|home address|\bmy address/i],
27
+ ['identity', /我叫|叫我|老家|籍贯|^我(?:不)?是[一-鿿]{1,4}人|^我(?:是)?(?:19|20)?\d{2}年(?:的|生)|性格|内向|外向|\bintrovert|\bextrovert|hometown|grew up in|名字|姓名|我今年|\d+\s*岁|生日|出生|母语|国籍|性别|\bmy name\b|call me|years old|\bborn\b|birthday|native (language|speaker)|nationality/i],
28
+ ['location', /我住在|住在|定居|搬到|搬去|搬回|我在[一-鿿]{1,6}(市|省|区|生活)|所在城市|时区|\blive in\b|\bbased in\b|moved to|time ?zone|\bliving in\b/i],
29
+ ['work', /工作|上班|公司|职业|职位|岗位|工程师|设计师|产品经理|程序员|开发者|研究员|老师|教师|律师|会计|创业|实习|团队|电商|网店|开店|开了(?:一)?家|做生意|生意|淘宝店|辞职|离职|跳槽|转行|\brun (?:an? |my own )?(?:online |small |little )?(?:shop|store|business|bakery|restaurant|cafe|café|agency)|\bown (?:an? |my own )?(?:\w+ ){0,2}(?:business|shop|store|restaurant|cafe|café|agency|company)\b|\bself-employed\b|\bfreelanc|\bquit(?:ting)? my job\b|外企|国企|财务|前端|后端|全栈|学生|博士|研究生|硕士|本科|读研|读博|大学|毕业|专业是|学的是|\bjob\b|\bfor work\b|\b(?:the|our|my) [A-Z]?\w* ?office\b|\btranslat(?:e|or|ion)|\bphd\b|\bstudent\b|\bgrad(?:uate)? school|\buniversity\b|\bcollege\b|\bmajor(?:ed|ing)? in\b|\bdegree in\b|\bpostdoc|\bwork(ing)? (at|for|as)\b|company|engineer|developer|designer|product manager|researcher|teacher|lawyer|startup|founder|career|my role|intern/i],
30
+ ['goals', /目标|梦想|打算|计划(?!生育)|希望将来|想成为|以后想|总有一天|准备考|\bmy (?:goal|dream|plan) (?:is|for)|\bi (?:hope|plan|aim|intend|dream) to|\bi'm (?:planning|hoping|aiming) to|\bi want to (?:become|be a|learn|run|get|move|start|build|travel|finish|pass|write|launch|retire|save)|\bsomeday\b|\bone day\b|\beventually\b/i],
31
+ ['projects', /项目|在做|正在开发|正在写|在搭|副业|开源|side project|working on|\bbuilding\b|my project|open[- ]source/i],
32
+ ['skills', /我(?:平时|一般|主要|常|日常|经常|都)?用\s*(?:[A-Za-z]|飞书|钉钉|企业微信|石墨|语雀|剪映|微信读书|WPS)|飞书|钉钉|语雀|\b(?:VS ?Code|Vim|Neovim|n?vim|tmux|Emacs|Cursor|Notion|Obsidian|Figma|Excel|Sketch|Photoshop|Jira|Linear|Slack|Docker|Kubernetes|Linux|iTerm|zsh|Xcode|IntelliJ|PyCharm|Jupyter)\b|擅长|会说|说[一-鿿]{1,2}话|[一-鿿]{1,2}语(?:是母语|很流利)|\bi speak\b|熟悉|精通|会用|学过|在学|开始学|掌握|雅思|托福|考研|考试|备考|证书|IELTS|TOEFL|exam|certificat|python|javascript|typescript|rust|golang|\bjava\b|swift|kotlin|sql|react|\bskilled\b|proficient|fluent|experience (with|in)|learning|good at/i],
33
+ ['communication', /回答|回复|简洁|详细|啰嗦|语气|用中文|用英文|直接说|别客套|\breply\b|\brespond\b|answers?\b|\btone\b|concise|verbose|bullet points|be direct|in english|in chinese|(?:别|不要|少|不用)用表格|用表格(?:回答|列出|展示|对比)|表情|emoji|术语|列表|markdown|简体|繁体|先给结论|先说结论|先(?:给|说|讲)(?:答案|重点|要点)|先.{1,8}[,,]?再(?:解释|说|讲|展开|给)|回答的时候|回答时|\bprose\b|\bbullet(?:s| points?)?\b|\bgive me (?:the )?[\w -]{2,30} first\b|\btables?\b|\bformatting\b|british english|american english|code comments|^(?:please )?(?:don't|do not|never|no) (?:use )?(?:any )?(?:emojis?|tables|jargon|markdown|headers)\b/i],
34
+ ['preferences', /喜欢|不喜欢|讨厌|偏好|习惯|爱好|最爱|口味|\bprefer|\blike\b|\blove\b|\bhate\b|favou?rite|hobby|hobbies|enjoy|usually|vegetarian|vegan|素食|吃素|不吃肉|周末|每周|每天|平时|练习|健身|跑步|游泳|徒步|爬山|骑行|吉他|钢琴|画画|摄影|看书|阅读|on weekends|every (day|week|morning)|\bpractice\b|times a (day|week|month)|\bplay(s|ing)? (the )?(guitar|piano|violin|tennis|football|soccer|basketball|chess|games)|\b(running|cycling|hiking|swimming|reading|photography)\b|\bblog|\bdiet\b|节食|减肥|\b(?:eat|eating|drink|drinking)\b|^我(?:现在|已经|平时|从来)?(?:不再|不|没|从不)?(?:吃|喝)|养了|宠物|\bmy (?:dog|cat|pet)s?\b/i],
35
+ ];
36
+
37
+ /**
38
+ * Classify one statement.
39
+ * @param {string} text
40
+ * @param {{category?: string, sensitivity?: string}} [hint] e.g. from an AI's memory_push.
41
+ * Hints may raise sensitivity but never lower it below what the rules detect.
42
+ * @returns {{text, category, sensitivity, confidence, secrets}}
43
+ */
44
+ // Topics that are nobody else's business by default, whatever category they land in: religion,
45
+ // politics, sexuality, criminal record, immigration status. They become "sensitive", so the
46
+ // default rule never shares them.
47
+ const SENSITIVE_TOPICS = /斋月|清真|礼拜|封斋|守斋|\bkosher\b|\bhalal\b|\bramadan\b|\blent\b|\bfast(?:ing)? (?:for (?:religious|lent|ramadan|yom kippur)|during (?:ramadan|lent))|\byom kippur\b|\bshabbat\b|\bsabbath\b|离婚|分居|(?<![相确自坚迷])信(?:基督教?|佛教?|教|伊斯兰教?|天主教?|主|耶稣)|耶和华见证人|摩门|\bdivorc|\bseparated from my (?:wife|husband|partner)|jehovah'?s? witness|\bmormon|\b(?:i(?:'m| am)|as a) trans\b|\btrans (?:woman|man|person|guy|girl|kid)\b|宗教|信仰|信教|基督徒|穆斯林|佛教徒|教会|清真|党员|政治立场|投票给|左派|右派|同性恋|双性恋|跨性别|性取向|出柜|LGBT|坐过牢|被捕|犯罪记录|缓刑|前科|签证|绿卡|移民身份|难民|黑户|\b(?:religio|christian\b|muslim\b|jewish\b|hindu\b|buddhist\b|atheist\b|church\b|mosque\b|synagogue\b|pray(?:er|ing)?\b)|\b(?:democrat|republican|liberal|conservative|socialist|communist)s?\b|\bvot(?:e|ed|ing) (?:for|against)\b|\b(?:gay|lesbian|bisexual|queer|transgender|trans woman|trans man|non-?binary|came out|coming out|sexual orientation)\b|\b(?:arrested|convicted|felony|probation|parole|criminal record|jail|prison|dui|dwi)\b|\b(?:visa|green card|undocumented|asylum|refugee|immigration status|deport)/i;
48
+
49
+ // Acronyms that only mean the sensitive thing in capitals ("PrEP" vs "meal prep", "LDS", "AA").
50
+ const SENSITIVE_ACRONYMS = /\bPrEP\b|\bLDS\b|\b(?:in|at|go to|joined) AA\b/;
51
+
52
+ export function classify(text, hint = {}) {
53
+ const masked = maskSecrets(text);
54
+ const contacts = findContacts(masked.text);
55
+ const hits = KEYWORDS.filter(([, re]) => re.test(masked.text)).map(([c]) => c);
56
+ if (/\bPrEP\b|\b(?:in|at|go to|joined) AA\b/.test(masked.text) && !hits.includes('health')) hits.push('health');
57
+ if (contacts.length && !hits.includes('contact')) hits.push('contact');
58
+ if (masked.secrets.length && !hits.includes('ids')) hits.unshift('ids');
59
+
60
+ let category = 'other';
61
+ let sensitivity = 'uncertain';
62
+ let confidence = 0.3;
63
+ if (hits.length) {
64
+ // Most sensitive category wins; ties keep keyword priority order.
65
+ category = hits.reduce((best, c) =>
66
+ SENS_RANK[CATEGORY_DEFAULT_SENS[c]] > SENS_RANK[CATEGORY_DEFAULT_SENS[best]] ? c : best);
67
+ sensitivity = CATEGORY_DEFAULT_SENS[category];
68
+ confidence = hits.length === 1 ? 0.8 : 0.7;
69
+ }
70
+ if (hint.category && CATEGORIES.includes(hint.category) && category === 'other') {
71
+ category = hint.category;
72
+ sensitivity = CATEGORY_DEFAULT_SENS[category];
73
+ confidence = 0.6;
74
+ }
75
+ if (hint.sensitivity && SENSITIVITY.includes(hint.sensitivity) && SENS_RANK[hint.sensitivity] > SENS_RANK[sensitivity]) {
76
+ sensitivity = hint.sensitivity;
77
+ }
78
+ if ((SENSITIVE_TOPICS.test(masked.text) || SENSITIVE_ACRONYMS.test(masked.text)) && sensitivity !== 'sensitive') { sensitivity = 'sensitive'; confidence = Math.min(confidence, 0.7); }
79
+ if (masked.secrets.length) sensitivity = 'secret';
80
+ return { text: masked.text, category, sensitivity, confidence, secrets: masked.secrets };
81
+ }
@@ -0,0 +1,63 @@
1
+ // The AIs MindFerry knows. Adding one is a small PR: see docs/en/ADAPTERS.md.
2
+ // kind 'mcp' — local app that speaks MCP (pulls/pushes automatically)
3
+ // kind 'web' — chat website: import its export / pasted chats, copy a context card back
4
+ // detect — regex used to guess the source of a pasted chat or saved page
5
+ import { FriendlyError } from './errors.mjs';
6
+
7
+ export const CLIENTS = [
8
+ // Local apps (MCP)
9
+ { id: 'claude-code', kind: 'mcp', name: { zh: 'Claude Code', en: 'Claude Code' } },
10
+ { id: 'codex', kind: 'mcp', name: { zh: 'Codex', en: 'Codex' } },
11
+ { id: 'claude-desktop', kind: 'mcp', name: { zh: 'Claude 桌面版', en: 'Claude Desktop' } },
12
+ { id: 'gemini-cli', kind: 'mcp', name: { zh: 'Gemini CLI', en: 'Gemini CLI' } },
13
+ { id: 'cursor', kind: 'mcp', name: { zh: 'Cursor', en: 'Cursor' } },
14
+ { id: 'grok-bot', kind: 'mcp', name: { zh: 'Grok bot', en: 'Grok bot' } },
15
+ { id: 'other-mcp', kind: 'mcp', name: { zh: '其他 MCP 应用', en: 'Other MCP app' }, note: { zh: 'Cline、Continue、Goose、OpenHands、Windsurf…', en: 'Cline, Continue, Goose, OpenHands, Windsurf…' } },
16
+ // Chat websites
17
+ { id: 'chatgpt', kind: 'web', name: { zh: 'ChatGPT', en: 'ChatGPT' }, detect: /chatgpt|openai|chat\.com/i },
18
+ { id: 'claude-web', kind: 'web', name: { zh: 'Claude 网页版', en: 'Claude (web)' }, detect: /claude|anthropic/i },
19
+ { id: 'gemini-web', kind: 'web', name: { zh: 'Gemini', en: 'Gemini' }, detect: /gemini|bard/i },
20
+ { id: 'grok-web', kind: 'web', name: { zh: 'Grok', en: 'Grok' }, detect: /grok|x\.ai/i },
21
+ { id: 'deepseek', kind: 'web', name: { zh: 'DeepSeek', en: 'DeepSeek' }, detect: /deepseek/i },
22
+ { id: 'kimi', kind: 'web', name: { zh: 'Kimi', en: 'Kimi' }, detect: /kimi|moonshot/i },
23
+ { id: 'doubao', kind: 'web', name: { zh: '豆包', en: 'Doubao' }, detect: /豆包|doubao/i },
24
+ { id: 'qwen', kind: 'web', name: { zh: '通义千问', en: 'Qwen' }, detect: /通义|千问|qwen|tongyi/i },
25
+ { id: 'local-llm', kind: 'web', name: { zh: '本地模型', en: 'Local models' }, note: { zh: 'Open WebUI、LM Studio、Ollama', en: 'Open WebUI, LM Studio, Ollama' }, detect: /open ?webui|lm ?studio|ollama/i },
26
+ ];
27
+
28
+ export const CLIENT_IDS = CLIENTS.map((c) => c.id);
29
+ export const clientInfo = (id) => CLIENTS.find((c) => c.id === id);
30
+ export const clientName = (id, lang = 'en') => clientInfo(id)?.name[lang] || id;
31
+
32
+ /** Guess which web AI a pasted chat / saved page came from. Returns an id or null. */
33
+ export function detectVendor(text) {
34
+ const head = String(text).slice(0, 4000);
35
+ // Speaker labels are the strongest signal ("ChatGPT said:", "Claude:" …).
36
+ for (const c of CLIENTS) {
37
+ if (c.kind !== 'web' || !c.detect) continue;
38
+ const label = new RegExp(`^\\s*(?:${c.detect.source})[^\\n::]{0,12}(?:said)?\\s*[::]`, 'im');
39
+ if (label.test(head)) return c.id;
40
+ }
41
+ for (const c of CLIENTS) if (c.kind === 'web' && c.detect?.test(head)) return c.id;
42
+ return null;
43
+ }
44
+
45
+ /** Ensure state.clients[id] exists; returns it. */
46
+ export function ensureClient(state, id) {
47
+ if (!clientInfo(id)) throw new FriendlyError('UNKNOWN_CLIENT', { id });
48
+ if (!state.clients[id]) {
49
+ state.clients[id] = {
50
+ id,
51
+ enabled: false,
52
+ paused: false,
53
+ rule: null, // null = default rule
54
+ lastSyncAt: null,
55
+ lastIn: 0,
56
+ lastOut: 0,
57
+ pendingOut: 0,
58
+ lastSeenAt: null,
59
+ delivered: {}, // itemId -> item.updatedAt delivered
60
+ };
61
+ }
62
+ return state.clients[id];
63
+ }