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,77 @@
1
+ // Optional smarter extraction with a model that runs on this computer (Ollama or LM Studio).
2
+ // MindFerry never calls an online model. Requests go only to 127.0.0.1, only when the user
3
+ // clicks "Tidy up with my local model". The built-in rules keep working without it.
4
+
5
+ const ENDPOINTS = [
6
+ { kind: 'ollama', base: 'http://127.0.0.1:11434', list: '/api/tags', chat: '/api/chat' },
7
+ { kind: 'lmstudio', base: 'http://127.0.0.1:1234', list: '/v1/models', chat: '/v1/chat/completions' },
8
+ ];
9
+
10
+ const EMBEDDING = /embed|bge|e5-|minilm|nomic/i;
11
+
12
+ async function getJson(url, opts = {}, timeoutMs = 2500) {
13
+ const ctl = new AbortController();
14
+ const t = setTimeout(() => ctl.abort(), timeoutMs);
15
+ try {
16
+ const r = await fetch(url, { ...opts, signal: ctl.signal });
17
+ if (!r.ok) return null;
18
+ return await r.json();
19
+ } catch { return null; } finally { clearTimeout(t); }
20
+ }
21
+
22
+ /** Find a local model server and a chat model on it. */
23
+ export async function detectLocalModel({ endpoints = ENDPOINTS } = {}) {
24
+ for (const e of endpoints) {
25
+ const j = await getJson(e.base + e.list);
26
+ if (!j) continue;
27
+ const names = (j.models || j.data || []).map((m) => m.name || m.id).filter(Boolean);
28
+ const chat = names.filter((n) => !EMBEDDING.test(n));
29
+ return { kind: e.kind, base: e.base, models: chat, model: chat[0] || null, endpoint: e, onlyEmbedding: !chat.length && names.length > 0 };
30
+ }
31
+ return null;
32
+ }
33
+
34
+ const PROMPT = `You read messages a person wrote to an AI assistant. List durable facts the person states about THEMSELVES (who they are, work, skills, projects, goals, preferences, how they like answers, tools they use, what they dislike, where they live).
35
+ Rules: only what they clearly said about themselves; write each fact in first person, short, in the language they used; skip questions, requests, hypotheticals, role-play, and facts about other people; never include passwords, keys or ID/card numbers.
36
+ Answer with JSON only: {"facts": ["...", "..."]}`;
37
+
38
+ /** Ask the local model for facts in a batch of the user's messages. */
39
+ export async function extractWithModel(found, messages, { timeoutMs = 120000 } = {}) {
40
+ const text = messages.map((m, i) => `[${i + 1}] ${String(m.text).slice(0, 1500)}`).join('\n\n');
41
+ const body = found.kind === 'ollama'
42
+ ? { model: found.model, stream: false, format: 'json', options: { temperature: 0 }, messages: [{ role: 'system', content: PROMPT }, { role: 'user', content: text }] }
43
+ : { model: found.model, temperature: 0, messages: [{ role: 'system', content: PROMPT }, { role: 'user', content: text }] };
44
+ const j = await getJson(found.base + found.endpoint.chat, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }, timeoutMs);
45
+ const content = j?.message?.content ?? j?.choices?.[0]?.message?.content ?? '';
46
+ let facts = [];
47
+ try { facts = JSON.parse(content.replace(/^```(?:json)?|```$/g, '').trim()).facts || []; } catch {}
48
+ return facts.filter((f) => typeof f === 'string' && f.trim().length >= 4 && f.length <= 300).slice(0, 40);
49
+ }
50
+
51
+ /**
52
+ * Tidy up: send not-yet-tidied user messages to the local model in batches and submit the
53
+ * facts it finds (as coming from the AI the messages belong to). Returns counts.
54
+ */
55
+ export async function tidyWithLocalModel(hub, { found = null, maxMessages = 200, batch = 12, onProgress = () => {} } = {}) {
56
+ found ||= await detectLocalModel();
57
+ if (!found?.model) return { ok: false, reason: found?.onlyEmbedding ? 'NO_CHAT_MODEL' : 'NO_LOCAL_MODEL' };
58
+ const done = new Set(hub.read().tidied || []);
59
+ const todo = [];
60
+ for (const m of hub.archive.iter()) {
61
+ if (m.role !== 'user' || done.has(m.h) || String(m.text).trim().length < 12) continue;
62
+ todo.push(m);
63
+ if (todo.length >= maxMessages) break;
64
+ }
65
+ let facts = 0;
66
+ for (let i = 0; i < todo.length; i += batch) {
67
+ const part = todo.slice(i, i + batch);
68
+ const found2 = await extractWithModel(found, part);
69
+ const byClient = {};
70
+ for (const f of found2) (byClient[part[0].client] ||= []).push({ text: f });
71
+ for (const [client, entries] of Object.entries(byClient)) facts += (await hub.submit(client, entries)).accepted;
72
+ await hub.store.update((s) => { s.tidied = [...(s.tidied || []), ...part.map((m) => m.h)].slice(-50000); });
73
+ onProgress(Math.min(todo.length, i + batch), todo.length);
74
+ }
75
+ const sync = facts ? await hub.sync() : null;
76
+ return { ok: true, model: found.model, messages: todo.length, facts, sync };
77
+ }
@@ -0,0 +1,95 @@
1
+ // Merge incoming classified statements into the item list.
2
+ // - same fingerprint → same item (add source)
3
+ // - same slot, different value → newer wins; older becomes "superseded"; conflict flagged
4
+ import { fingerprint, newId, detectLang } from './text.mjs';
5
+
6
+ /**
7
+ * @param {object[]} items mutable item list (state.items)
8
+ * @param {{text, slot, value, category, sensitivity, confidence, client, observedAt}} st
9
+ * @param {string} now ISO time of this sync
10
+ * @returns {{action: 'added'|'touched'|'updated'|'stale', item}}
11
+ */
12
+ export function mergeStatement(items, st, now) {
13
+ const fp = fingerprint(st.text);
14
+ const at = st.observedAt || now;
15
+ const live = items.filter((i) => i.status === 'active');
16
+
17
+ const same = items.find((i) => i.fingerprint === fp && i.status !== 'deleted');
18
+ if (same) {
19
+ addSource(same, st.client, at);
20
+ // A re-stated superseded fact that is newer than its replacement revives it.
21
+ if (same.status === 'superseded' && same.slot) {
22
+ const cur = live.find((i) => i.slot === same.slot);
23
+ if (cur && at > cur.observedAt) {
24
+ supersede(cur, same, now);
25
+ same.status = 'active';
26
+ same.supersededBy = null;
27
+ same.observedAt = at;
28
+ same.updatedAt = now;
29
+ return { action: 'updated', item: same };
30
+ }
31
+ }
32
+ return { action: 'touched', item: same };
33
+ }
34
+
35
+ const item = {
36
+ id: newId('m'),
37
+ text: st.text,
38
+ lang: detectLang(st.text),
39
+ slot: st.slot || null,
40
+ value: st.value ?? null,
41
+ category: st.category,
42
+ sensitivity: st.sensitivity,
43
+ confidence: st.confidence ?? 0.5,
44
+ fingerprint: fp,
45
+ sources: [],
46
+ observedAt: at,
47
+ createdAt: now,
48
+ updatedAt: now,
49
+ status: 'active',
50
+ supersededBy: null,
51
+ conflict: null,
52
+ locked: false,
53
+ userEdited: false,
54
+ };
55
+ addSource(item, st.client, at);
56
+
57
+ if (item.slot) {
58
+ const cur = live.find((i) => i.slot === item.slot);
59
+ if (cur && cur.value !== item.value) {
60
+ if (at >= cur.observedAt) {
61
+ supersede(cur, item, now);
62
+ items.push(item);
63
+ return { action: 'updated', item };
64
+ }
65
+ // Incoming is older than what we know: keep it only as history.
66
+ item.status = 'superseded';
67
+ item.supersededBy = cur.id;
68
+ items.push(item);
69
+ return { action: 'stale', item };
70
+ }
71
+ }
72
+ items.push(item);
73
+ return { action: 'added', item };
74
+ }
75
+
76
+ function supersede(oldItem, newItem, now) {
77
+ oldItem.status = 'superseded';
78
+ oldItem.supersededBy = newItem.id;
79
+ oldItem.updatedAt = now;
80
+ newItem.conflict = {
81
+ previousId: oldItem.id,
82
+ previousText: oldItem.text,
83
+ previousSources: oldItem.sources.map((s) => s.client),
84
+ at: now,
85
+ acknowledged: false,
86
+ };
87
+ // Keep the user's protection on the new value if they had locked the old one.
88
+ if (oldItem.locked) newItem.locked = true;
89
+ }
90
+
91
+ function addSource(item, client, at) {
92
+ if (!client) return;
93
+ const s = item.sources.find((x) => x.client === client);
94
+ if (s) { if (at > s.at) s.at = at; } else item.sources.push({ client, at });
95
+ }
@@ -0,0 +1,175 @@
1
+ // The "About me" profile: one short page (a few hundred tokens) that lets any AI, even a
2
+ // brand-new one, understand who the user is at a glance. Built only from things the user
3
+ // actually said; no inferred personality judgements. Private categories never go in.
4
+ import { allowed, ruleFor } from './rules.mjs';
5
+
6
+ export const PROFILE_SECTIONS = ['who', 'how', 'now', 'goals', 'tools', 'dislikes'];
7
+
8
+ export const SECTION_TITLES = {
9
+ who: { en: 'Who I am', zh: '我是谁' },
10
+ how: { en: 'How I work and like answers', zh: '我怎么工作、喜欢怎样的回答' },
11
+ now: { en: "What I'm working on", zh: '现在在做什么' },
12
+ goals: { en: 'Longer-term goals', zh: '长期目标' },
13
+ tools: { en: 'Tools and skills', zh: '常用工具和技能' },
14
+ dislikes: { en: "What I don't like", zh: '不喜欢什么' },
15
+ };
16
+
17
+ // Never in the profile, whatever the rule says (they can still be shared through the
18
+ // full card / search if the user explicitly allows them for a given AI).
19
+ export const PROFILE_EXCLUDED = ['health', 'finance', 'ids', 'others', 'contact'];
20
+
21
+ const RE = {
22
+ dislikes: /不喜欢|讨厌|受不了|别给我|不要给我|不想要|反感|\bdon'?t (?:like|want|enjoy)|\bdislike|\bhate\b|\bcan'?t stand|\bplease don'?t|\bavoid\b|\bnot a fan/i,
23
+ how: /回答|回复|解释|语气|中文|英文|英语|简洁|简短|详细|直接|举例|代码示例|\banswers?\b|\brespon[sd]|\breply|\bexplain|\btone\b|\bconcise|\bdetailed|\bbullet|\bformat|\bexamples?\b|\bin (?:english|chinese)|\bstep[- ]by[- ]step/i,
24
+ goals: /目标|梦想|打算|计划|希望|想要|想成为|准备考|备考|考研|雅思|托福|\bgoals?\b|\bplan(?:ning)? to\b|\bwant to\b|\bhope to\b|\baim(?:ing)? to\b|\bdream\b|\bsomeday\b|\bpreparing for\b/i,
25
+ now: /正在|最近在|这段时间|目前在|开始学|在做|在写|在开发|在准备|\bcurrently\b|\bworking on\b|\bbuilding\b|\bright now\b|\bthese days\b|\bjust started\b|\blearning\b/i,
26
+ tools: /我用|常用|工具|编辑器|软件|\bI use\b|\busing\b|\beditor\b|\bIDE\b|\bapp\b|\btools?\b|VS ?Code|Vim|Neovim|Cursor|Notion|Obsidian|Figma|Excel|Python|TypeScript|JavaScript|React|Rust|Swift|Kotlin|SQL|Docker|Linux|iPad/i,
27
+ // Case-sensitive: "Go", "Java", "Mac" are also everyday words ("go to the hills").
28
+ toolsExact: /\b(?:Go|Java|Mac|Windows)\b/,
29
+ };
30
+ const BY_CATEGORY = { identity: 'who', location: 'who', work: 'who', communication: 'how', projects: 'now', goals: 'goals', skills: 'tools', preferences: 'who', other: 'who' };
31
+ const ORDER_IN = { who: ['identity', 'work', 'location', 'preferences', 'other'] };
32
+
33
+ export function sectionOf(item) {
34
+ const t = item.text;
35
+ if (RE.dislikes.test(t)) return 'dislikes';
36
+ if (item.category === 'communication' || RE.how.test(t)) return 'how';
37
+ if (item.category === 'goals' || RE.goals.test(t)) return 'goals';
38
+ if (item.category === 'projects' || RE.now.test(t)) return 'now';
39
+ if (item.category === 'skills' || (item.category !== 'identity' && (RE.tools.test(t) || RE.toolsExact.test(t)))) return 'tools';
40
+ return BY_CATEGORY[item.category] || 'who';
41
+ }
42
+
43
+ /** Can this item ever be in the profile (before any per-AI rule)? */
44
+ /** Memory lines some AIs keep in the third person ("The user prefers X") read as first person. */
45
+ export function firstPerson(text) {
46
+ let t = String(text).trim();
47
+ const third = (v) => v === 'is' ? "'m" : v === 'has' ? ' have' : v === 'does' ? ' do' : v === 'was' ? ' was'
48
+ : ' ' + (/(?:ss|sh|ch|x|o)es$/.test(v) ? v.slice(0, -2) : /[^aeiou]ies$/.test(v) ? v.slice(0, -3) + 'y' : v.replace(/s$/, ''));
49
+ t = t.replace(/^(?:the )?user's\b/i, 'My');
50
+ t = t.replace(/^(?:the )?user (is|has|does|was|[a-z]+s)\b/i, (_, v) => 'I' + third(v.toLowerCase()));
51
+ t = t.replace(/^(?:the )?user (?=(?:also |often |usually |really |never |always )?[a-z])/i, 'I ');
52
+ t = t.replace(/^(?:该)?用户(?!名|协议|数据|界面|体验|量|群)/, '我');
53
+ return t;
54
+ }
55
+
56
+ const WORD_STOP = new Set('i im am a an the and or to of in on for with my me is are was at by it this that called just very also really so over than some more most much like'.split(' '));
57
+ const words = (t) => new Set(String(t).toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g, ' ').split(' ')
58
+ .flatMap((w) => /[\u4e00-\u9fff]/.test(w) ? [...w].slice(0, -1).map((c, k) => c + w[k + 1]) : [w.replace(/(?:ing|es|s)$/, '')])
59
+ .filter((w) => w.length > 1 && !WORD_STOP.has(w)));
60
+
61
+ /** Two lines say much the same thing (word overlap). */
62
+ export function nearDuplicate(a, b, threshold = 0.5) {
63
+ const x = words(a), y = words(b);
64
+ if (!x.size || !y.size) return false;
65
+ let both = 0;
66
+ for (const w of x) if (y.has(w)) both++;
67
+ if (both / (x.size + y.size - both) >= threshold) return true;
68
+ // One line is mostly inside the other ("I prefer TypeScript over JavaScript" vs "I prefer TypeScript and small PRs").
69
+ const small = Math.min(x.size, y.size);
70
+ return small >= 3 && both / small >= 0.66;
71
+ }
72
+
73
+ const RELATIVE = /\b(?:last|this|next) (?:week|month|year|summer|winter|spring|autumn|fall)\b|\b(?:yesterday|recently|just now|a few (?:days|weeks|months) ago)\b|上个?月|上周|去年|今年|明年|下个?月|最近|刚刚|前几天/i;
74
+
75
+ /** Lines like "I moved here last month" get the date they were said, so they stay meaningful later. */
76
+ export function dated(text, at) {
77
+ if (!at || !RELATIVE.test(text)) return text;
78
+ const ym = String(at).slice(0, 7);
79
+ return /[\u4e00-\u9fff]/.test(text) ? `${text.replace(/[。.]$/, '')}(${ym} 说的)` : `${text.replace(/\.$/, '')} (said ${ym}).`;
80
+ }
81
+
82
+ /** Drop near-duplicates, keeping the longer (more informative) line. Input order is kept. */
83
+ export function dedupeLines(list, textOf = (x) => x.text) {
84
+ const keep = [];
85
+ for (const x of list) {
86
+ const k = keep.findIndex((y) => nearDuplicate(textOf(x), textOf(y)));
87
+ if (k < 0) keep.push(x);
88
+ else if (textOf(x).length > textOf(keep[k]).length) keep[k] = x;
89
+ }
90
+ return keep;
91
+ }
92
+
93
+ export function profileEligible(item) {
94
+ return item.status === 'active' && !item.locked && !item.profileHidden &&
95
+ !PROFILE_EXCLUDED.includes(item.category) &&
96
+ (item.sensitivity === 'public' || item.sensitivity === 'personal');
97
+ }
98
+
99
+ const OPENER = {
100
+ en: "Here is a short profile of me, the person you're talking to. Read it before you answer and use it quietly; no need to repeat it back. If something here conflicts with what I say later, what I say later wins. If you need more context, ask me.",
101
+ zh: '下面是关于我(和你对话的人)的一份简短档案。请先读一遍再回答,自然地用上就好,不必复述。如果和我之后说的有冲突,以我之后说的为准。需要更多背景就直接问我。',
102
+ };
103
+
104
+ export function pickProfileLang(state, items) {
105
+ const ui = state.settings?.uiLang;
106
+ if (ui === 'zh' || ui === 'en') return ui;
107
+ if (!items.length) return 'en';
108
+ return items.filter((i) => i.lang === 'zh').length * 2 >= items.length ? 'zh' : 'en';
109
+ }
110
+
111
+ // Within "who", food and diet lines come before hobbies: they matter more for everyday answers.
112
+ const FOOD = /素食|吃素|不吃|不喝|忌口|饮食|过敏|吃辣|vegetarian|vegan|pescatarian|\bdiet\b|\b(?:don't |do not |never )?(?:eat|drink)\b|gluten|lactose|dairy|allerg/i;
113
+ const MORE = { en: (n) => `- (+${n} more)\n`, zh: (n) => `- (另有 ${n} 条)\n` };
114
+
115
+ /** Share `total` lines across sections: each gets up to `per`, and room a short section leaves goes to longer ones. */
116
+ function shareBudget(counts, per, total) {
117
+ const alloc = counts.map((n) => Math.min(n, per));
118
+ let left = total - alloc.reduce((a, b) => a + b, 0);
119
+ while (left > 0) {
120
+ let gave = false;
121
+ for (let k = 0; k < counts.length && left > 0; k++) if (alloc[k] < counts[k]) { alloc[k]++; left--; gave = true; }
122
+ if (!gave) break;
123
+ }
124
+ return alloc;
125
+ }
126
+
127
+ /**
128
+ * Build the profile. With clientId, only items that AI is allowed to see are used.
129
+ * Sections share one line budget (perSection × number of sections); a section that still has
130
+ * lines left out ends with "(+N more)", so nothing is dropped silently.
131
+ * @returns {{sections: {key, title, items: {id, text}[], more: number}[], text: string, lang: string, itemIds: string[]}}
132
+ */
133
+ export function buildProfile(state, { clientId = null, lang = null, perSection = 6, maxChars = 2200, opener = true } = {}) {
134
+ const rule = clientId ? ruleFor(state.clients[clientId], clientId) : null;
135
+ const items = dedupeLines(state.items
136
+ .filter((i) => profileEligible(i) && (!clientId || allowed(i, clientId, rule)))
137
+ .sort((a, b) => (b.observedAt > a.observedAt ? 1 : -1))); // newest first, near-duplicates merged
138
+ const L = lang || pickProfileLang(state, items);
139
+ const buckets = Object.fromEntries(PROFILE_SECTIONS.map((k) => [k, []]));
140
+ for (const i of items) buckets[sectionOf(i)].push(i);
141
+ for (const k of Object.keys(ORDER_IN)) {
142
+ const o = ORDER_IN[k];
143
+ const rank = (i) => o.indexOf(i.category) * 2 + (i.category === 'preferences' && !FOOD.test(i.text) ? 1 : 0);
144
+ buckets[k].sort((a, b) => rank(a) - rank(b)); // stable: newest first within a rank
145
+ }
146
+ const alloc = shareBudget(PROFILE_SECTIONS.map((k) => buckets[k].length), perSection, perSection * PROFILE_SECTIONS.length);
147
+ const sections = [];
148
+ const itemIds = [];
149
+ let text = `# ${L === 'zh' ? '关于我' : 'About me'}\n${opener ? OPENER[L] + '\n' : ''}`;
150
+ PROFILE_SECTIONS.forEach((key, k) => {
151
+ const all = buckets[key];
152
+ if (!all.length) return;
153
+ const head = `\n## ${SECTION_TITLES[key][L]}\n`;
154
+ let block = '';
155
+ const kept = [];
156
+ for (const i of all.slice(0, alloc[k])) {
157
+ const line = `- ${dated(firstPerson(i.text.replace(/\s+/g, ' ')), i.observedAt)}\n`;
158
+ // Keep room for the "(+N more)" line in case later lines do not fit.
159
+ const reserve = kept.length + 1 < all.length ? MORE[L](all.length).length : 0;
160
+ if (text.length + head.length + block.length + line.length + reserve > maxChars) break;
161
+ block += line;
162
+ kept.push({ id: i.id, text: i.text });
163
+ }
164
+ if (!kept.length) return;
165
+ const more = all.length - kept.length;
166
+ if (more > 0) block += MORE[L](more);
167
+ text += head + block;
168
+ sections.push({ key, title: SECTION_TITLES[key][L], items: kept, more });
169
+ itemIds.push(...kept.map((x) => x.id));
170
+ });
171
+ if (!itemIds.length) text += L === 'zh' ? '\n(还没有内容:先在 MindFerry 里导入聊天记录。)\n' : "\n(Nothing yet: import some chats into MindFerry first.)\n";
172
+ return { sections, text, lang: L, itemIds };
173
+ }
174
+
175
+ export { OPENER as PROFILE_OPENER };
@@ -0,0 +1,88 @@
1
+ // Per-AI sharing rules with safe defaults.
2
+ // preset 'summary' — the default: safe facts only (no health/finance/IDs/other people/contact/uncertain)
3
+ // preset 'custom' — the user picked categories / max sensitivity by hand
4
+ // preset 'everything' — all facts up to "sensitive" + full-text search of raw conversations
5
+ // "secret" items (ID / card numbers, keys) are never shared, whatever the rule says.
6
+ import { CATEGORIES, SENS_RANK } from './classify.mjs';
7
+
8
+ export const DEFAULT_BLOCKED_CATEGORIES = ['health', 'finance', 'ids', 'others', 'contact'];
9
+ export const PRESETS = ['summary', 'custom', 'everything'];
10
+
11
+ // "Just what it needs": coding agents get how-you-work facts; chat AIs also get where you live.
12
+ export const CODING_AGENTS = ['claude-code', 'codex', 'cursor', 'gemini-cli'];
13
+ export const FOCUS_CATEGORIES = {
14
+ coding: ['communication', 'identity', 'work', 'skills', 'projects', 'goals', 'preferences'],
15
+ chat: CATEGORIES.filter((c) => !DEFAULT_BLOCKED_CATEGORIES.includes(c) && c !== 'other'),
16
+ };
17
+ export const focusOf = (clientId) => (CODING_AGENTS.includes(clientId) ? 'coding' : 'chat');
18
+
19
+ export function defaultRule(clientId = null) {
20
+ return {
21
+ preset: 'summary',
22
+ categories: [...FOCUS_CATEGORIES[focusOf(clientId)]],
23
+ maxSensitivity: 'personal', // public | personal | sensitive
24
+ includeUncertain: false,
25
+ acceptFromOthers: true,
26
+ archiveAccess: false, // may search/read raw conversations
27
+ maxChars: 1500,
28
+ lang: 'auto', // auto | zh | en
29
+ };
30
+ }
31
+
32
+ export function everythingRule(base = {}) {
33
+ return {
34
+ ...defaultRule(),
35
+ ...base,
36
+ preset: 'everything',
37
+ categories: CATEGORIES.filter((c) => c !== 'ids'),
38
+ maxSensitivity: 'sensitive',
39
+ includeUncertain: true,
40
+ archiveAccess: true,
41
+ maxChars: Math.max(base.maxChars || 0, 6000),
42
+ };
43
+ }
44
+
45
+ export function normalizeRule(rule, clientId = null) {
46
+ const d = defaultRule(clientId);
47
+ if (rule?.preset === 'everything') return { ...everythingRule(rule), lang: ['auto', 'zh', 'en'].includes(rule.lang) ? rule.lang : 'auto' };
48
+ if (rule?.preset === 'summary') return { ...d, lang: ['auto', 'zh', 'en'].includes(rule.lang) ? rule.lang : 'auto' };
49
+ const r = { ...d, ...(rule || {}) };
50
+ r.preset = rule ? 'custom' : 'summary';
51
+ r.categories = (r.categories || []).filter((c) => CATEGORIES.includes(c) && c !== 'ids');
52
+ if (!['public', 'personal', 'sensitive'].includes(r.maxSensitivity)) r.maxSensitivity = d.maxSensitivity;
53
+ r.maxChars = Math.max(200, Math.min(20000, Number(r.maxChars) || d.maxChars));
54
+ if (!['auto', 'zh', 'en'].includes(r.lang)) r.lang = 'auto';
55
+ r.includeUncertain = !!r.includeUncertain;
56
+ r.acceptFromOthers = r.acceptFromOthers !== false;
57
+ r.archiveAccess = !!r.archiveAccess;
58
+ return r;
59
+ }
60
+
61
+ export function ruleFor(clientState, clientId = clientState?.id) {
62
+ return normalizeRule(clientState?.rule, clientId);
63
+ }
64
+
65
+ /** Is this item shareable with this client under its rule? */
66
+ export function allowed(item, clientId, rule) {
67
+ if (item.status !== 'active' || item.locked) return false;
68
+ if (item.sensitivity === 'secret' || item.category === 'ids') return false;
69
+ if (item.sensitivity === 'uncertain') {
70
+ if (!rule.includeUncertain) return false;
71
+ } else if (SENS_RANK[item.sensitivity] > SENS_RANK[rule.maxSensitivity]) return false;
72
+ if (!rule.categories.includes(item.category)) return false;
73
+ const fromSelf = item.sources.some((s) => s.client === clientId);
74
+ if (!rule.acceptFromOthers && !fromSelf) return false;
75
+ return true;
76
+ }
77
+
78
+ /** Items this client should be told about but hasn't received yet (excludes items only it provided). */
79
+ export function outbox(state, clientId) {
80
+ const c = state.clients[clientId];
81
+ if (c?.paused) return [];
82
+ const rule = ruleFor(c, clientId);
83
+ const delivered = c?.delivered || {};
84
+ return state.items.filter((i) =>
85
+ allowed(i, clientId, rule) &&
86
+ delivered[i.id] !== i.updatedAt &&
87
+ !(i.sources.length && i.sources.every((s) => s.client === clientId)));
88
+ }
@@ -0,0 +1,109 @@
1
+ // Local JSON store with a cross-process lock and atomic writes.
2
+ // Multiple MCP server processes and the UI may touch the store at once.
3
+ import { mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, statSync, existsSync, copyFileSync, readdirSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { homedir } from 'node:os';
6
+ import { FriendlyError } from './errors.mjs';
7
+
8
+ export const STORE_VERSION = 1;
9
+
10
+ export function defaultDataDir() {
11
+ return process.env.MINDFERRY_DATA_DIR || join(homedir(), '.mindferry');
12
+ }
13
+
14
+ export function emptyState() {
15
+ return {
16
+ version: STORE_VERSION,
17
+ createdAt: new Date().toISOString(),
18
+ items: [],
19
+ inbox: [],
20
+ seen: {},
21
+ clients: {},
22
+ settings: { autoSyncMinutes: 0, uiLang: null }, // uiLang: set when the window is opened
23
+ syncLog: [],
24
+ accessLog: [],
25
+ };
26
+ }
27
+
28
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
29
+
30
+ export class Store {
31
+ constructor(dir = defaultDataDir()) {
32
+ this.dir = dir;
33
+ this.file = join(dir, 'store.json');
34
+ this.lockDir = join(dir, '.lock');
35
+ // The folder is made on the first write, so reading (or "mindferry --help") leaves no trace.
36
+ }
37
+
38
+ ensureDir() { mkdirSync(this.dir, { recursive: true, mode: 0o700 }); }
39
+
40
+ read() {
41
+ if (!existsSync(this.file)) return emptyState();
42
+ try {
43
+ const s = JSON.parse(readFileSync(this.file, 'utf8'));
44
+ return { ...emptyState(), ...s };
45
+ } catch {
46
+ // Never crash on a damaged file: set it aside, then use the last good copy if there is one.
47
+ const backup = this.file + '.broken-' + Date.now();
48
+ try { renameSync(this.file, backup); } catch {}
49
+ this.lastRecovery = backup;
50
+ try {
51
+ const prev = JSON.parse(readFileSync(this.file + '.prev', 'utf8'));
52
+ this.recoveredFromPrev = true;
53
+ return { ...emptyState(), ...prev };
54
+ } catch {}
55
+ return emptyState();
56
+ }
57
+ }
58
+
59
+ write(state) {
60
+ this.ensureDir();
61
+ const tmp = this.file + '.' + process.pid + '.tmp';
62
+ writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 });
63
+ // Keep the previous good version so a damaged file (disk fault) loses at most one change.
64
+ try { if (existsSync(this.file)) { JSON.parse(readFileSync(this.file, 'utf8')); copyFileSync(this.file, this.file + '.prev'); } } catch {}
65
+ renameSync(tmp, this.file);
66
+ }
67
+
68
+ async lock(timeoutMs = 10000) {
69
+ this.ensureDir();
70
+ const start = Date.now();
71
+ for (;;) {
72
+ try {
73
+ mkdirSync(this.lockDir);
74
+ return;
75
+ } catch (e) {
76
+ if (e.code !== 'EEXIST') throw e;
77
+ try {
78
+ // Stale lock (crashed process): break after 15s.
79
+ if (Date.now() - statSync(this.lockDir).mtimeMs > 15000) rmSync(this.lockDir, { recursive: true, force: true });
80
+ } catch {}
81
+ if (Date.now() - start > timeoutMs) throw new FriendlyError('STORE_BUSY', {}, 503);
82
+ await sleep(20 + Math.random() * 30);
83
+ }
84
+ }
85
+ }
86
+
87
+ /** Forget the last-good copy (after "delete everything", nothing old may stay behind). */
88
+ dropPrev() {
89
+ rmSync(this.file + '.prev', { force: true });
90
+ try { for (const f of readdirSync(this.dir)) if (f.startsWith('store.json.broken-')) rmSync(join(this.dir, f), { force: true }); } catch {}
91
+ }
92
+
93
+ unlock() {
94
+ rmSync(this.lockDir, { recursive: true, force: true });
95
+ }
96
+
97
+ /** Run fn(state) under the lock; persist the (mutated) state; return fn's result. */
98
+ async update(fn) {
99
+ await this.lock();
100
+ try {
101
+ const state = this.read();
102
+ const result = await fn(state);
103
+ this.write(state);
104
+ return result;
105
+ } finally {
106
+ this.unlock();
107
+ }
108
+ }
109
+ }
@@ -0,0 +1,82 @@
1
+ // Text utilities: normalization, fingerprints, sentence splitting, secret masking.
2
+ import { createHash } from 'node:crypto';
3
+
4
+ export function normalize(s) {
5
+ return String(s)
6
+ .toLowerCase()
7
+ .replace(/[\s\p{P}\p{S}]+/gu, '')
8
+ .trim();
9
+ }
10
+
11
+ export function fingerprint(s) {
12
+ return createHash('sha256').update(normalize(s)).digest('hex').slice(0, 20);
13
+ }
14
+
15
+ export function hash(s) {
16
+ return createHash('sha256').update(String(s)).digest('hex').slice(0, 20);
17
+ }
18
+
19
+ export function newId(prefix = 'm') {
20
+ return prefix + '_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
21
+ }
22
+
23
+ export function detectLang(s) {
24
+ const cjk = (s.match(/[一-鿿]/g) || []).length;
25
+ const latin = (s.match(/[A-Za-z]/g) || []).length;
26
+ return cjk * 2 >= latin ? 'zh' : 'en';
27
+ }
28
+
29
+ // Split into sentences, keeping CJK and Latin punctuation; drops code blocks.
30
+ export function sentences(text) {
31
+ const noCode = String(text).replace(/```[\s\S]*?```/g, ' ').replace(/`[^`]*`/g, ' ');
32
+ return noCode
33
+ .split(/(?<=[。!?!?;;\n])|(?<=\.)\s+/)
34
+ .map((s) => s.replace(/\s+/g, ' ').trim())
35
+ .filter((s) => s.length >= 3 && s.length <= 240);
36
+ }
37
+
38
+ // ---- Secret detection & masking ------------------------------------------
39
+ function luhn(d) {
40
+ let s = 0;
41
+ for (let i = 0; i < d.length; i++) {
42
+ let n = +d[d.length - 1 - i];
43
+ if (i % 2) { n *= 2; if (n > 9) n -= 9; }
44
+ s += n;
45
+ }
46
+ return s % 10 === 0;
47
+ }
48
+
49
+ const SECRET_RULES = [
50
+ { kind: 'cn-id', re: /(?<![\dA-Za-z])\d{17}[\dXx](?![\dA-Za-z])/g },
51
+ { kind: 'card', re: /(?<!\d)(?:\d[ -]?){12,18}\d(?!\d)/g, ok: (m) => luhn(m.replace(/\D/g, '')) },
52
+ { kind: 'ssn', re: /(?<!\d)\d{3}-\d{2}-\d{4}(?!\d)/g },
53
+ { kind: 'passport', re: /(?<=(?:passport|护照)[^A-Za-z0-9]{0,12})[A-Z]{1,2}\d{6,9}/gi },
54
+ { kind: 'api-key', re: /\b(?:sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35}|xox[abprs]-[A-Za-z0-9-]{10,})/g },
55
+ { kind: 'password', re: /(?<=(?:password|passwd|密码|口令)\s*(?:is|是|为|:|:|=)\s*)\S{4,}/gi },
56
+ ];
57
+
58
+ const CONTACT_RULES = [
59
+ { kind: 'phone', re: /(?<!\d)(?:\+?86[- ]?)?1[3-9]\d{9}(?!\d)|(?<!\d)\+?\d{1,3}[- (]{0,2}\d{3}[- )]{1,2}\d{3}[- ]\d{4}(?!\d)/g },
60
+ { kind: 'email', re: /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g },
61
+ ];
62
+
63
+ /** Mask secrets. Returns { text, secrets: [kinds] }. Original values are never kept. */
64
+ export function maskSecrets(text) {
65
+ const secrets = [];
66
+ let out = String(text);
67
+ for (const { kind, re, ok } of SECRET_RULES) {
68
+ out = out.replace(re, (m) => {
69
+ if (ok && !ok(m)) return m;
70
+ secrets.push(kind);
71
+ const tail = m.replace(/[^A-Za-z0-9]/g, '').slice(-2);
72
+ return `[${kind}:••••${kind === 'password' || kind === 'api-key' ? '' : tail}]`;
73
+ });
74
+ }
75
+ return { text: out, secrets };
76
+ }
77
+
78
+ export function findContacts(text) {
79
+ const found = [];
80
+ for (const { kind, re } of CONTACT_RULES) if (String(text).match(re)) found.push(kind);
81
+ return found;
82
+ }
package/src/demo.mjs ADDED
@@ -0,0 +1,30 @@
1
+ // Demo data: made-up people ("Lin Xiaoyu" / 林小雨, and "Alex Moreno" in English). Used by `mindferry demo`,
2
+ // the "Try with sample data" button, screenshots and tests. No real person's data.
3
+ import { readFileSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { importFile, importText } from './importers/index.mjs';
6
+
7
+ const ex = (f) => fileURLToPath(new URL('../examples/' + f, import.meta.url));
8
+
9
+ /** lang 'en' loads an English-speaking made-up person ("Alex Moreno"), otherwise 林小雨. */
10
+ export async function loadDemo(hub, { lang = 'zh' } = {}) {
11
+ const dir = lang === 'en' ? 'demo-en/' : 'exports/';
12
+ await importFile(hub, ex(dir + 'chatgpt-conversations.json'));
13
+ await importFile(hub, ex(dir + 'gemini-MyActivity.json'));
14
+ await importFile(hub, ex(dir + 'grok-export.json'));
15
+ await importFile(hub, ex(dir + 'deepseek-conversations.json'));
16
+ await hub.sync({ now: '2026-01-15T09:00:00.000Z' });
17
+ await importFile(hub, ex(dir + 'claude-conversations.json'));
18
+ await importFile(hub, ex(dir + 'claude-memories.json'));
19
+ await importText(hub, readFileSync(ex(lang === 'en' ? 'demo-en/chatgpt-copied.txt' : 'single-chats/chatgpt-copied.txt'), 'utf8'));
20
+ await hub.submit('claude-code', lang === 'en' ? [
21
+ { text: 'I prefer TypeScript and small, well-tested pull requests.', category: 'preferences' },
22
+ { text: 'Working on Pebble, an open-source notes app (React + SQLite).', category: 'projects' },
23
+ ] : [
24
+ { text: '我喜欢小而有测试的 PR。', category: 'preferences' },
25
+ { text: 'Pebble 用 React + SQLite 写。', category: 'projects' },
26
+ ]);
27
+ await hub.setEnabled('codex', true);
28
+ await hub.setEnabled('claude-web', true);
29
+ return hub.sync();
30
+ }