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.
- package/LICENSE +21 -0
- package/README.md +182 -2
- package/README.zh-CN.md +165 -0
- package/bin/mindferry.mjs +301 -0
- package/examples/demo-en/chatgpt-conversations.json +72 -0
- package/examples/demo-en/chatgpt-copied.txt +8 -0
- package/examples/demo-en/claude-conversations.json +25 -0
- package/examples/demo-en/claude-memories.json +6 -0
- package/examples/demo-en/deepseek-conversations.json +39 -0
- package/examples/demo-en/gemini-MyActivity.json +18 -0
- package/examples/demo-en/grok-export.json +27 -0
- package/examples/exports/README.md +4 -0
- package/examples/exports/chatgpt-conversations.json +21 -0
- package/examples/exports/claude-conversations.json +13 -0
- package/examples/exports/claude-memories.json +3 -0
- package/examples/exports/deepseek-conversations.json +12 -0
- package/examples/exports/gemini-MyActivity.json +5 -0
- package/examples/exports/grok-export.json +11 -0
- package/examples/exports/open-webui-export.json +13 -0
- package/examples/scheduler/crontab.txt +2 -0
- package/examples/scheduler/io.github.mindferry.sync.plist +18 -0
- package/examples/single-chats/chatgpt-copied.txt +8 -0
- package/examples/single-chats/chatgpt-saved-page.html +4 -0
- package/examples/single-chats/claude-chat.md +7 -0
- package/package.json +55 -4
- package/src/connect.mjs +204 -0
- package/src/core/archive.mjs +144 -0
- package/src/core/card.mjs +64 -0
- package/src/core/classify.mjs +81 -0
- package/src/core/clients.mjs +63 -0
- package/src/core/errors.mjs +146 -0
- package/src/core/export.mjs +53 -0
- package/src/core/extract.mjs +183 -0
- package/src/core/generator.mjs +98 -0
- package/src/core/hub.mjs +637 -0
- package/src/core/llm.mjs +77 -0
- package/src/core/merge.mjs +95 -0
- package/src/core/profile.mjs +175 -0
- package/src/core/rules.mjs +88 -0
- package/src/core/store.mjs +109 -0
- package/src/core/text.mjs +82 -0
- package/src/demo.mjs +30 -0
- package/src/importers/index.mjs +366 -0
- package/src/importers/zip.mjs +48 -0
- package/src/mcp/server.mjs +272 -0
- package/src/remote.mjs +180 -0
- package/src/ui/server.mjs +281 -0
- package/src/ui/static/app.js +1037 -0
- package/src/ui/static/index.html +269 -0
- package/src/ui/static/logo.svg +16 -0
- package/src/ui/static/mascot-busy.svg +35 -0
- package/src/ui/static/mascot-happy.svg +27 -0
- package/src/ui/static/mascot-idle.svg +26 -0
- package/src/ui/static/mascot-oops.svg +26 -0
- package/src/ui/static/style.css +382 -0
- package/src/version.mjs +1 -0
- package/src/watch.mjs +80 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// Human-readable errors. Every error a person can see has a code, a plain-language
|
|
2
|
+
// explanation and a next step, in Chinese and English. No stack traces in the UI.
|
|
3
|
+
|
|
4
|
+
const CATALOG = {
|
|
5
|
+
NODE_TOO_OLD: {
|
|
6
|
+
zh: (p) => `需要 Node.js 22 或更新版本,你现在是 ${p.version}。下一步:到 https://nodejs.org 下载安装「LTS」版本,再重新运行。`,
|
|
7
|
+
en: (p) => `MindFerry needs Node.js 22 or newer; you have ${p.version}. Next step: install the "LTS" version from https://nodejs.org and run it again.`,
|
|
8
|
+
},
|
|
9
|
+
PORT_IN_USE: {
|
|
10
|
+
zh: (p) => `端口 ${p.port} 已被别的程序占用。下一步:如果 MindFerry 已经开着,直接打开 http://127.0.0.1:${p.port}/ ;否则换个端口:mindferry start --port ${p.port + 2}`,
|
|
11
|
+
en: (p) => `Port ${p.port} is already in use. Next step: if MindFerry is already running, just open http://127.0.0.1:${p.port}/ ; otherwise pick another port: mindferry start --port ${p.port + 2}`,
|
|
12
|
+
},
|
|
13
|
+
STORE_BUSY: {
|
|
14
|
+
zh: () => '另一个 MindFerry 进程正在写入数据,等了 10 秒还没写完。下一步:稍等几秒再试一次。',
|
|
15
|
+
en: () => 'Another MindFerry process is writing data and did not finish within 10 seconds. Next step: wait a few seconds and try again.',
|
|
16
|
+
},
|
|
17
|
+
STORE_CORRUPT: {
|
|
18
|
+
zh: (p) => `数据文件读不出来(可能被手动改坏了)。已把它备份为 ${p.backup},并从空白重新开始。下一步:如需找回,可用文本编辑器打开备份修复后放回。`,
|
|
19
|
+
en: (p) => `The data file could not be read (it may have been edited by hand). It was backed up to ${p.backup} and MindFerry started fresh. Next step: to recover, fix the backup in a text editor and put it back.`,
|
|
20
|
+
},
|
|
21
|
+
UNKNOWN_CLIENT: {
|
|
22
|
+
zh: (p) => `不认识「${p.id}」这个 AI。下一步:运行 mindferry 不带参数查看支持的名字。`,
|
|
23
|
+
en: (p) => `"${p.id}" is not a known AI. Next step: run mindferry with no arguments to see the supported names.`,
|
|
24
|
+
},
|
|
25
|
+
FILE_UNRECOGNIZED: {
|
|
26
|
+
zh: () => '认不出这个文件来自哪个 AI。下一步:在页面上选择它来自哪个 AI,或者直接把对话文字粘贴进「粘贴对话」框。',
|
|
27
|
+
en: () => "Couldn't tell which AI this file came from. Next step: choose the AI on the page, or paste the conversation text into the \"Paste a conversation\" box.",
|
|
28
|
+
},
|
|
29
|
+
FILE_BLANK: {
|
|
30
|
+
zh: () => '这个文件是空的,里面什么都没有。下一步:重新导出一次,或者直接复制对话文字,点「粘贴一段对话」。',
|
|
31
|
+
en: () => 'This file is empty. Next step: export again, or copy the conversation text and click "Paste a conversation".',
|
|
32
|
+
},
|
|
33
|
+
FILE_NOT_CHAT: {
|
|
34
|
+
zh: (p) => `这是${p.kind === 'image' ? '一张图片' : p.kind === 'pdf' ? '一个 PDF 文件' : p.kind === 'doc' ? '一个文档' : '一个其他类型的文件'},不是聊天记录。下一步:拖入 AI 官方导出的压缩包(.zip);或者打开 AI 网页里的对话,全选、复制,再点「粘贴一段对话」。`,
|
|
35
|
+
en: (p) => `This is ${p.kind === 'image' ? 'an image' : p.kind === 'pdf' ? 'a PDF' : p.kind === 'doc' ? 'a document' : 'another kind of file'}, not a chat. Next step: drop the AI's official export (.zip), or open the chat on the AI's website, select all, copy, and click "Paste a conversation".`,
|
|
36
|
+
},
|
|
37
|
+
FILE_EMPTY: {
|
|
38
|
+
zh: () => '这个文件里没找到对话。下一步:拖入 AI 官方导出的压缩包(.zip)本身;单个对话可以直接复制文字,点「粘贴一段对话」。',
|
|
39
|
+
en: () => 'No conversations were found in this file. Next step: drop the official export .zip (or the conversations.json / MyActivity.json inside it); for a single chat, paste its text instead.',
|
|
40
|
+
},
|
|
41
|
+
FILE_NOT_FOUND: {
|
|
42
|
+
zh: (p) => `找不到文件:${p.path}。下一步:检查路径,或者直接把文件拖进 MindFerry 窗口。`,
|
|
43
|
+
en: (p) => `File not found: ${p.path}. Next step: check the path, or just drag the file into the MindFerry window.`,
|
|
44
|
+
},
|
|
45
|
+
FILE_TOO_LARGE: {
|
|
46
|
+
zh: () => '文件超过 512 MB。下一步:解压导出包,只拖入里面的 conversations.json。',
|
|
47
|
+
en: () => 'The file is larger than 512 MB. Next step: unzip the export and drop only the conversations.json inside it.',
|
|
48
|
+
},
|
|
49
|
+
ZIP64: {
|
|
50
|
+
zh: () => '这个压缩包太大(ZIP64 格式),暂时读不了。下一步:先解压,再把里面的 conversations.json 拖进来。',
|
|
51
|
+
en: () => 'This archive uses the large ZIP64 format, which is not supported yet. Next step: unzip it and drop the conversations.json inside.',
|
|
52
|
+
},
|
|
53
|
+
ZIP_BAD: {
|
|
54
|
+
zh: () => '压缩包损坏或不完整(可能没下载完)。下一步:重新下载导出文件再试。',
|
|
55
|
+
en: () => 'The zip file is damaged or incomplete (maybe the download did not finish). Next step: download the export again.',
|
|
56
|
+
},
|
|
57
|
+
PASTE_EMPTY: {
|
|
58
|
+
zh: () => '没有粘贴任何内容。下一步:在 AI 网页里全选对话(⌘A / Ctrl+A),复制,再粘贴到这里。',
|
|
59
|
+
en: () => 'Nothing was pasted. Next step: in the AI\'s web page select the conversation (⌘A / Ctrl+A), copy, and paste it here.',
|
|
60
|
+
},
|
|
61
|
+
ITEM_NOT_FOUND: {
|
|
62
|
+
zh: () => '这条记忆已经不存在了(可能刚被删掉)。下一步:刷新页面。',
|
|
63
|
+
en: () => 'This memory no longer exists (it may have just been deleted). Next step: refresh the page.',
|
|
64
|
+
},
|
|
65
|
+
BAD_REQUEST: {
|
|
66
|
+
zh: () => '请求格式不对。下一步:刷新页面再试。',
|
|
67
|
+
en: () => 'The request was malformed. Next step: refresh the page and try again.',
|
|
68
|
+
},
|
|
69
|
+
BAD_TOKEN: {
|
|
70
|
+
zh: () => '页面已过期(MindFerry 重启过)。下一步:刷新页面。',
|
|
71
|
+
en: () => 'This page is out of date (MindFerry was restarted). Next step: refresh the page.',
|
|
72
|
+
},
|
|
73
|
+
ACCESS_FACTS_ONLY: {
|
|
74
|
+
zh: (p) => `用户只允许 ${p.client} 读取整理好的摘要,不能搜索原始对话。如需更多,请用户在 MindFerry 的「规则」页把这个 AI 设为「全部」。`,
|
|
75
|
+
en: (p) => `The user lets ${p.client} read the summarized profile only, not raw conversations. To allow more, the user can set this AI to "Everything" on MindFerry's Rules page.`,
|
|
76
|
+
},
|
|
77
|
+
PAUSED: {
|
|
78
|
+
zh: (p) => `用户已暂停向 ${p.client} 分享信息。需要时请用户在 MindFerry 里点「恢复分享」。`,
|
|
79
|
+
en: (p) => `The user has paused sharing with ${p.client}. They can click "Resume sharing" in MindFerry.`,
|
|
80
|
+
},
|
|
81
|
+
DEMO_NO_CONNECT: {
|
|
82
|
+
zh: () => '演示模式下不能接入 AI(演示数据关掉就没了)。下一步:关掉演示,直接运行 mindferry,再来接入。',
|
|
83
|
+
en: () => 'Connecting is off in demo mode (the demo data disappears when it closes). Next step: close the demo, run mindferry normally, then connect.',
|
|
84
|
+
},
|
|
85
|
+
SAMPLE_LOADED: {
|
|
86
|
+
zh: () => '现在里面是示例数据。下一步:点页面顶部的「清除示例,开始用我自己的」,或直接拖入你自己的聊天记录(示例会自动清除),然后再接入。',
|
|
87
|
+
en: () => 'Sample data is loaded right now. Next step: click "Clear samples and start" at the top, or drop in your own chats (samples are cleared automatically), then connect.',
|
|
88
|
+
},
|
|
89
|
+
ORGANIZE_OFF: {
|
|
90
|
+
zh: (p) => `用户没有让 ${p.client} 帮忙整理记忆。需要时请用户在 MindFerry 的「设置 → 更聪明的整理」里选择这个 AI。`,
|
|
91
|
+
en: (p) => `The user has not asked ${p.client} to tidy up their memory. They can choose this AI in MindFerry under Settings → Smarter tidying.`,
|
|
92
|
+
},
|
|
93
|
+
NO_LOCAL_MODEL: {
|
|
94
|
+
zh: () => '没找到本机模型。下一步:安装 Ollama(ollama.com)或 LM Studio,下载一个聊天模型后再试;不装也没关系,内置规则一直在工作。',
|
|
95
|
+
en: () => 'No local model found. Next step: install Ollama (ollama.com) or LM Studio and download a chat model, then try again. You don\'t need one: the built-in rules always work.',
|
|
96
|
+
},
|
|
97
|
+
NO_CHAT_MODEL: {
|
|
98
|
+
zh: () => '本机模型服务里只有嵌入模型,没有聊天模型。下一步:例如运行 ollama pull qwen2.5:3b,再试一次。',
|
|
99
|
+
en: () => 'Your local model server only has embedding models. Next step: download a chat model (for example `ollama pull qwen2.5:3b`) and try again.',
|
|
100
|
+
},
|
|
101
|
+
NOTHING_TO_UNDO: {
|
|
102
|
+
zh: () => '没有可以撤回的内容了。',
|
|
103
|
+
en: () => 'There is nothing to undo.',
|
|
104
|
+
},
|
|
105
|
+
CONNECT_NO_CLI: {
|
|
106
|
+
zh: (p) => `没找到 ${p.cli} 命令,所以没法自动接入。下一步:把「接入」页里的配置片段复制到 ${p.name} 的设置里。`,
|
|
107
|
+
en: (p) => `The ${p.cli} command was not found, so MindFerry can't connect automatically. Next step: copy the snippet from the Connect page into ${p.name}'s settings.`,
|
|
108
|
+
},
|
|
109
|
+
CONNECT_FAILED: {
|
|
110
|
+
zh: (p) => `接入 ${p.name} 没成功:${p.detail}。下一步:把「接入」页里的配置片段手动复制过去。`,
|
|
111
|
+
en: (p) => `Connecting ${p.name} failed: ${p.detail}. Next step: copy the snippet from the Connect page by hand.`,
|
|
112
|
+
},
|
|
113
|
+
INTERNAL: {
|
|
114
|
+
zh: (p) => `出了点意外问题(${p.detail || '未知'})。你的数据没有丢。下一步:刷新页面重试;还不行就到 GitHub 提 issue,附上这句话。`,
|
|
115
|
+
en: (p) => `Something unexpected went wrong (${p.detail || 'unknown'}). Your data is safe. Next step: refresh and retry; if it persists, open a GitHub issue with this message.`,
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export class FriendlyError extends Error {
|
|
120
|
+
constructor(code, params = {}, status = 400) {
|
|
121
|
+
super(code);
|
|
122
|
+
this.code = code;
|
|
123
|
+
this.params = params;
|
|
124
|
+
this.status = status;
|
|
125
|
+
}
|
|
126
|
+
text(lang = 'en') {
|
|
127
|
+
return messageFor(this.code, this.params, lang);
|
|
128
|
+
}
|
|
129
|
+
toJSON() {
|
|
130
|
+
return { error: this.code, message: { zh: this.text('zh'), en: this.text('en') } };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function messageFor(code, params = {}, lang = 'en') {
|
|
135
|
+
const c = CATALOG[code] || CATALOG.INTERNAL;
|
|
136
|
+
return (c[lang] || c.en)(params);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Normalize anything thrown into a FriendlyError (never leaks a stack). */
|
|
140
|
+
export function toFriendly(e) {
|
|
141
|
+
if (e instanceof FriendlyError) return e;
|
|
142
|
+
if (e?.code === 'EADDRINUSE') return new FriendlyError('PORT_IN_USE', { port: e.port }, 409);
|
|
143
|
+
return new FriendlyError('INTERNAL', { detail: String(e?.message || e).slice(0, 120) }, 500);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export const SYSTEM_LANG = (process.env.LANG || process.env.LC_ALL || '').toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Export everything MindFerry holds, so leaving is easy: one Markdown file, a JSON file,
|
|
2
|
+
// or a folder of Markdown notes that Obsidian / Logseq open as a vault.
|
|
3
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { CATEGORY_LABELS } from './card.mjs';
|
|
6
|
+
|
|
7
|
+
const safe = (s) => String(s || 'untitled').replace(/[\\/:*?"<>|#^[\]\n\r]+/g, ' ').trim().slice(0, 80) || 'untitled';
|
|
8
|
+
|
|
9
|
+
function factsByCategory(facts) {
|
|
10
|
+
const by = {};
|
|
11
|
+
for (const f of facts) if (f.status === 'active') (by[f.category] ||= []).push(f);
|
|
12
|
+
return by;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** One Markdown document: the profile, then every fact by category. */
|
|
16
|
+
export function toMarkdown(data, profileText = '') {
|
|
17
|
+
let out = `# MindFerry export\n\nExported ${data.exportedAt}. Everything below stayed on your computer.\n\n`;
|
|
18
|
+
if (profileText) out += profileText.replace(/^# /, '## ').replace(/\n## /g, '\n### ') + '\n';
|
|
19
|
+
out += '\n## All facts\n';
|
|
20
|
+
for (const [cat, list] of Object.entries(factsByCategory(data.facts))) {
|
|
21
|
+
out += `\n### ${CATEGORY_LABELS[cat]?.en || cat}\n`;
|
|
22
|
+
for (const f of list) out += `- ${f.text} _(${f.sensitivity}; from ${f.sources.map((s) => s.client).join(', ')}; ${String(f.observedAt).slice(0, 10)})_\n`;
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A folder of notes: About me.md, Facts/<category>.md, Conversations/<ai>/<title>.md */
|
|
28
|
+
export function toFolder(data, dir, profileText = '') {
|
|
29
|
+
mkdirSync(join(dir, 'Facts'), { recursive: true });
|
|
30
|
+
writeFileSync(join(dir, 'About me.md'), profileText || '# About me\n');
|
|
31
|
+
for (const [cat, list] of Object.entries(factsByCategory(data.facts))) {
|
|
32
|
+
const body = list.map((f) => `- ${f.text}\n - sensitivity:: ${f.sensitivity}\n - from:: ${f.sources.map((s) => `[[${s.client}]]`).join(' ')}\n - date:: ${String(f.observedAt).slice(0, 10)}`).join('\n');
|
|
33
|
+
writeFileSync(join(dir, 'Facts', `${CATEGORY_LABELS[cat]?.en || cat}.md`), `# ${CATEGORY_LABELS[cat]?.en || cat}\n\n${body}\n`);
|
|
34
|
+
}
|
|
35
|
+
const convs = new Map();
|
|
36
|
+
for (const m of data.conversations || []) {
|
|
37
|
+
const k = m.client + '\u0000' + (m.conv || 'loose');
|
|
38
|
+
if (!convs.has(k)) convs.set(k, { client: m.client, title: m.title || m.conv || 'chat', msgs: [] });
|
|
39
|
+
convs.get(k).msgs.push(m);
|
|
40
|
+
}
|
|
41
|
+
const used = new Set();
|
|
42
|
+
for (const c of convs.values()) {
|
|
43
|
+
const folder = join(dir, 'Conversations', safe(c.client));
|
|
44
|
+
mkdirSync(folder, { recursive: true });
|
|
45
|
+
let name = safe(c.title);
|
|
46
|
+
for (let n = 2; used.has(c.client + '/' + name); n++) name = `${safe(c.title)} (${n})`;
|
|
47
|
+
used.add(c.client + '/' + name);
|
|
48
|
+
const body = c.msgs.map((m) => `**${m.role === 'user' ? 'Me' : c.client}**${m.at ? ` · ${String(m.at).slice(0, 16).replace('T', ' ')}` : ''}\n\n${m.text}`).join('\n\n---\n\n');
|
|
49
|
+
writeFileSync(join(folder, name + '.md'), `# ${c.title}\n\n${body}\n`);
|
|
50
|
+
}
|
|
51
|
+
writeFileSync(join(dir, 'mindferry-export.json'), JSON.stringify(data, null, 2));
|
|
52
|
+
return { facts: data.facts.length, conversations: convs.size, dir };
|
|
53
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Extract statements *about the user* from free text, plus attribute slots
|
|
2
|
+
// used for conflict detection ("newer wins").
|
|
3
|
+
import { sentences } from './text.mjs';
|
|
4
|
+
|
|
5
|
+
// A sentence must match one of these to count as self-disclosure.
|
|
6
|
+
const SELF_ZH = /(?<![帮给让替跟对叫请诉和与教问])我(?:现在|目前|一直|也|还|平时|已经|最近|刚|刚刚|上个月|上周|去年|前不久|每天|每周|每晚|周末|经常|常常|很少|从不)?(?:早上|晚上|中午|下午|上午)?(?:开始|在)?(?:搬|不(?:吃|喝|抽|再)|学|练|养|做|写|读|跑|玩|打|退休|准备|打算|计划|吃|喝|住|是|叫|在|住|喜欢|不喜欢|讨厌|习惯|平时|一般|通常|正在|最近在|会|不会|用|今年|有|没有|偏好|更喜欢|希望你|想让你|擅长|熟悉|学过|做过|从事|负责|对.{1,8}过敏)|我(?:的)?(?:老婆|老公|妻子|丈夫|爱人|孩子|儿子|女儿|爸爸|妈妈|父母|朋友|同事|老板|男朋友|女朋友|孙子|孙女|外孙|外孙女|爷爷|奶奶|姥姥|姥爷|外公|外婆|老伴|儿媳|女婿)|我的[\u4e00-\u9fff]{1,4}(?:是|叫|在|有|很|比较)|我的(?:名字|职业|工作|专业|母语|爱好|生日|老婆|妻子|丈夫|老公|孩子|儿子|女儿|父母|手机|电话|邮箱|身份证|护照|工资|收入|公司|团队|项目|城市|家)|^叫我[一-鿿A-Za-z]{1,6}(?:就行|就好|就可以|吧|[,,。.!!]|$)|^(?:请)?(?:不要|别)(?:用|加|使用|放)(?:任何)?(?:表情|emoji)|请(?:用|以).{0,4}(?:中文|英文|英语)|(?:回答|回复).{0,6}(?:简洁|简短|详细)/;
|
|
7
|
+
const SELF_EN = /\b(?:my (?:goal|dream|plan) (?:is|for)|i (?:hope|plan|aim|intend|dream) to|i'm (?:planning|hoping|aiming) to|i want to (?:become|be a|learn|run|get (?:a|into|better)|move|start|build|travel|finish|pass|write|launch|retire|save)\b|i am|i'm|i've been|i've|i (?:(?:\w+ly|just|also|really|still|now|currently) )*(?:work|live|like|love|prefer|hate|dislike|usually|always|never|often|use|have|don't|do not|speak|was born|moved|study|studied|drink|eat|run|play|read|write|train|own|code|teach|travel|plan|cook|wake|go|enjoy|grew up|started|learned|practice|switched|joined|quit|got|take|suffer|struggle|feel|believe|support|vote|earn|make|owe|rent|commute|drive|ride|bike|swim|hike|sleep|meditate|volunteer|graduated|majored))\b|\bmy (?:name|job|role|wife|husband|son|daughter|kids?|grandson|granddaughter|grandkids?|grandchildren|partner|mom|dad|mother|father|company|team|project|city|hometown|native|salary|income|phone|email|passport|birthday|hobby|hobbies|favorite|favourite)\b|\bcall me\b|^(?:please )?(?:don't|do not|never) (?:use|add|include|put|give me|write)(?: any| me)? (?:emojis?|emoticons|bullet(?: points|s)?|lists|tables|headers|headings|markdown|jargon|code comments)\b|^no emojis?\b|^(?:please )?(?:always )?give me (?:the )?[\w -]{2,30} first\b|\bi (?:(?:\w+ly|just|also|finally) )*(?:gave up|stopped|cut out|quit|kicked) (?:drinking|smoking|eating|alcohol|coffee|caffeine|sugar|meat|vaping|cigarettes)\b|\bplease (?:always )?(?:reply|respond|answer|write|keep (?:your |the |all )?(?:answers|replies|responses)|use (?:simple|plain|british|american)|be (?:brief|concise|direct))\b/i;
|
|
8
|
+
const QUESTION = /[??]\s*$|吗[。!!]?$|^(?:what|how|why|can|could|would|is|are|do|does|did)\b|^(?:怎么|为什么|如何|能不能|可以帮)/i;
|
|
9
|
+
// Hypotheticals and role-play are not facts about the user.
|
|
10
|
+
const NOT_FACT = /(?:我是|我只是|作为)(?:一个|一款)?(?:AI|人工智能|语言模型|助手|聊天机器人)|\bas an ai\b|\bi(?:'m| am) (?:an? )?(?:ai|language model|assistant|chatbot)\b|假设|假如|如果我是|扮演|举个例子|比如说|例如|写一个.*(?:故事|小说)|\bimagine\b|\bpretend\b|\bsuppose\b|\bif i were\b|\bhypothetical(?:ly)?\b|\bwhat if\b|\bfor example\b|\brole-?play\b|\bwrite a (story|poem)\b|(?:帮我|请|把这段|下面)(?:翻译|润色|改写|校对|改一下)|翻译(?:成|为)?[::]|\btranslate (?:this|the following|into|to)\b|\bproofread\b|\b(?:rewrite|polish) (?:this|the following)\b/i;
|
|
11
|
+
|
|
12
|
+
// Slot patterns: [slot, regex, valueGroup | fn]. Order matters (first match wins per slot).
|
|
13
|
+
const SLOTS = [
|
|
14
|
+
['identity.name', /我(?:叫|的名字是|的名字叫)\s*([一-鿿A-Za-z·]{1,12})/],
|
|
15
|
+
['identity.name', /^叫我\s*([一-鿿A-Za-z·]{1,6}?)(?:就行|就好|就可以|吧|[,,。.!!]|$)/],
|
|
16
|
+
['identity.name', /\b(?:my name is|call me)\s+([A-Z][\w'-]{1,20}(?: [A-Z][\w'-]{1,20})?)/i],
|
|
17
|
+
['identity.age', /我今年\s*(\d{1,3})\s*岁/],
|
|
18
|
+
['identity.age', /\bi(?:'m| am)\s+(\d{1,3})\s+years? old\b/i],
|
|
19
|
+
['location.home', /(?:我|^|[,,])(?:现在|目前|已经|最近|刚|刚刚|上个月|上周|去年|前不久)?(?:住在|定居在|生活在|搬到了?|搬去了?|搬回了?(?:老家)?)\s*([一-鿿A-Za-z ]{1,16}?)(?:[,,。.!!;;]|$|,|的|了|工作|住)/],
|
|
20
|
+
['location.home', /\bi(?: live|(?:'m| am) (?:now )?(?:based|living|located)|(?:'ve| have)? (?:just |recently )?moved) (?:in|to)\s+([A-Z][\w .'-]{1,30}?)(?:[,.;!(]|$| and | with | now| last | this | recently| a few | in \d| since | for | about | from )/i],
|
|
21
|
+
['work.employer', /我在\s*([一-鿿A-Za-z0-9 ]{1,16}?)\s*(?:工作|上班|任职)/],
|
|
22
|
+
['work.employer', /\bi work (?:at|for)\s+([A-Za-z0-9][\w&.'-]*(?: [\w&.'-]+){0,3}?)(?=\s+(?:as|on|in|at|since|for|and|but|with|now|remotely|from)\b|\s*[,.;!(]|\s*$)/i],
|
|
23
|
+
['work.role', /我(?:是一名|是一位|是个|是一个|的职业是|的工作是|从事)\s*([一-鿿A-Za-z ]{0,12}?(?:工程师|设计师|经理|程序员|开发者|研究员|老师|教师|医生|律师|会计|学生|作家|分析师|顾问|创始人|主管|编辑|记者|产品|运营|销售|工作))/],
|
|
24
|
+
['work.role', /\bi(?:'m| am) an? ((?:senior |junior |lead |staff |principal )?[\w -]{0,20}?(?:engineer|developer|designer|manager|researcher|teacher|student|writer|analyst|consultant|founder|scientist|lawyer|doctor|nurse|editor|journalist|marketer|accountant|architect))\b/i],
|
|
25
|
+
['work.role', /\bi work as an? ([\w -]{2,40}?)(?:[,.;!]|$| at | for )/i],
|
|
26
|
+
['communication.language', /请(?:用|以)\s*(中文|英文|英语|简体中文|繁体中文)/, (m) => (/英/.test(m[1]) ? 'en' : 'zh')],
|
|
27
|
+
['communication.language', /\b(?:reply|respond|answer|write)(?: to me)? in (english|chinese|mandarin)\b/i, (m) => (/english/i.test(m[1]) ? 'en' : 'zh')],
|
|
28
|
+
['communication.length', /(?:回答|回复).{0,6}(简洁|简短|详细)/, (m) => (/详细/.test(m[1]) ? 'detailed' : 'concise')],
|
|
29
|
+
['communication.length', /\b(?:be|keep (?:it|answers|replies)) (concise|brief|short|detailed)\b/i, (m) => (/detailed/i.test(m[1]) ? 'detailed' : 'concise')],
|
|
30
|
+
['communication.emoji', /^(?:please )?(?:don't|do not|never) (?:use|add|include|put)(?: any)? (?:emojis?|emoticons)\b|^no emojis?\b/i, () => 'no'],
|
|
31
|
+
['communication.emoji', /^(?:请)?(?:不要|别)(?:用|加|使用|放)(?:任何)?(?:表情|emoji)/i, () => 'no'],
|
|
32
|
+
// "I'm vegetarian" / "I'm not vegetarian anymore": the newer one replaces the older.
|
|
33
|
+
['is', /^i(?:'m| am)\s+(not\s+|no longer\s+)?(?:an?\s+)?([a-z][a-z-]{2,20}(?:\s(?!any ?more\b)[a-z][a-z-]{2,20})?)(?:\s+any ?more)?\s*[.!]?$/i, (m) => ({ slot: 'is:' + m[2].toLowerCase(), value: m[1] ? 'no' : 'yes' })],
|
|
34
|
+
['is', /^我(?:已经|现在|目前)?(不再是|不是|不再|不|是)?(素食者?|吃素|单身|学生|上班族|自由职业者?|全职妈妈|全职爸爸)(?:了)?[。.!!]?$/, (m) => ({ slot: 'is:' + (/^素食/.test(m[2]) ? '吃素' : m[2].replace(/者$/, '')), value: /不/.test(m[1] || '') ? 'no' : 'yes' })],
|
|
35
|
+
// "I don't drink coffee" / "我不喝咖啡": a habit, so a later "I drink coffee again" replaces it.
|
|
36
|
+
['habit', /^i (don't |do not |no longer |never )?(drink|eat|smoke)\s+([a-z][a-z -]{1,20}?)(?:\s+(?:any ?more|again|now|every \w+|daily))?\s*[,.;!]?$/i, (m) => ({ slot: `habit:${m[2].toLowerCase()}:${m[3].toLowerCase()}`, value: m[1] ? 'no' : 'yes' })],
|
|
37
|
+
['habit', /^i (?:(?:\w+ly|just|also|finally) )*(?:gave up|stopped|quit|kicked|cut out) (drinking|eating|smoking) ([a-z][a-z -]{1,20}?)(?:\s+(?:in|last|this|a|since|for|about|when)\b.*)?\s*[,.;!]?$/i, (m) => ({ slot: `habit:${m[1].slice(0, -3).replace(/k$/, 'k').replace(/smok$/, 'smoke').replace(/^eat$/, 'eat')}:${m[2].toLowerCase()}`, value: 'no' })],
|
|
38
|
+
['habit', /^我(?:已经|去年|今年|上个月|最近)?(?:戒了|戒掉了?)([一-鿿]{1,4}?)(?:了)?[,,。.!!]?$/, (m) => ({ slot: `habit:${/烟/.test(m[1]) ? '抽' : /酒|咖啡|茶|奶|可乐|饮料/.test(m[1]) ? '喝' : '吃'}:${m[1]}`, value: 'no' })],
|
|
39
|
+
['habit', /^我(?:现在|已经|平时|从来)?(不再|不|没|从不)?(喝|吃|抽)([一-鿿]{1,6}?)(?:了)?[。.!!]?$/, (m) => ({ slot: `habit:${m[2]}:${m[3]}`, value: m[1] ? 'no' : 'yes' })],
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
// Preferences: slot keyed by the object so "like X" vs "dislike X" conflict.
|
|
43
|
+
const PREF_ZH = /我(不喜欢|讨厌|喜欢|更喜欢|最喜欢|爱)\s*([一-鿿A-Za-z0-9 ]{1,12}?)(?:[,,。.!!;;]|$|和|,)/;
|
|
44
|
+
const PREF_EN = /\bi (don't like|do not like|dislike|hate|like|love|prefer|enjoy)\s+([\w -]{2,30}?)(?:[,.;!]|$| and | but | because )/i;
|
|
45
|
+
|
|
46
|
+
function cleanVal(v) {
|
|
47
|
+
return String(v).trim().replace(/^(?:a|an|the)\s+/i, '').replace(/[。.,,!!;;]+$/, '').trim();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Conversational lead-ins that carry no meaning: "Update: I'm …", "Actually I'm …", "其实我…".
|
|
51
|
+
const LEAD_IN = /^(?:(?:update|correction|edit|note|fyi|btw|by the way|actually|just so you know|just fyi|for the record|oh|well|ok(?:ay)?|so|also|anyway|heads up|(?:some |quick |a bit of |for )?(?:context|background)|about me)\b[:,!.—-]?\s*)+|^(?:(?:更新一下|更新|其实|对了|顺便说一下|顺便说|另外|说一下|先说一下|补充一下|纠正一下|背景|关于我|先介绍一下|简单介绍一下)[::,,]?\s*)+|^现在[,,]?\s*(?=我)/i;
|
|
52
|
+
export function stripLeadIn(s) {
|
|
53
|
+
return String(s).trim().replace(LEAD_IN, '').replace(/^[a-z]/, (c) => (c === 'i' ? 'I' : c));
|
|
54
|
+
}
|
|
55
|
+
// The bare claim without what follows it: "I'm vegetarian, so no meat please" → "I'm vegetarian".
|
|
56
|
+
const TRAILING = /\s*(?:[,,;;((]|\s(?:so|but|because|since|which|though)\s|所以|但是?|不过|因为).*$/i;
|
|
57
|
+
|
|
58
|
+
/** Extract attribute slot for a single statement, or null. */
|
|
59
|
+
export function slotOf(sentence) {
|
|
60
|
+
const core = stripLeadIn(sentence);
|
|
61
|
+
const bare = core.replace(TRAILING, '');
|
|
62
|
+
for (const [slot, re, fn] of SLOTS) {
|
|
63
|
+
const m = (slot === 'is' ? bare : core).match(re);
|
|
64
|
+
if (m) {
|
|
65
|
+
const value = fn ? fn(m) : cleanVal(m[1]);
|
|
66
|
+
if (value && typeof value === 'object') return value;
|
|
67
|
+
if (value) return { slot, value: slot === 'identity.age' ? value : value };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
let m = core.match(PREF_ZH);
|
|
71
|
+
if (m) {
|
|
72
|
+
const neg = /不喜欢|讨厌/.test(m[1]);
|
|
73
|
+
return { slot: 'pref:' + cleanVal(m[2]).toLowerCase(), value: neg ? 'dislike' : 'like' };
|
|
74
|
+
}
|
|
75
|
+
m = core.match(PREF_EN);
|
|
76
|
+
if (m) {
|
|
77
|
+
const neg = /don't|do not|dislike|hate/i.test(m[1]);
|
|
78
|
+
return { slot: 'pref:' + cleanVal(m[2]).toLowerCase(), value: neg ? 'dislike' : 'like' };
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Passing states and chat filler ("I'm tired", "I'm sorry", "I'm pretty sure it's…") are not facts.
|
|
84
|
+
const TRANSIENT = /^(?:i(?:'m| am) (?:so |really |very |just |a bit |kind of |pretty )?(?:tired|sleepy|exhausted|sorry|confused|back|here|done|ready|bored|hungry|busy today|going to (?:bed|sleep)|off to|about to|heading|sure|not sure|pretty sure|fine|ok(?:ay)?|good now|glad|excited|curious|wondering|stuck|lost)\b|i (?:meant|mean|guess|forgot|just realized|think|thought|was wondering)\b|我(?:好|很|有点|太)?(?:累|困|饿|无聊|烦)了?[。.!!]?$|我(?:去|要去)睡(?:觉)?了|我(?:刚才|刚刚)(?:说错|打错|搞错)|我(?:觉得|认为)(?!我)|我猜|我想问)/i;
|
|
85
|
+
|
|
86
|
+
// Pleasantries, where-am-I-right-now and troubleshooting reports are not lasting facts.
|
|
87
|
+
const SMALL_TALK = /^i(?:'m| am) (?:doing )?(?:good|fine|ok(?:ay)?|great|well|alright|all right|not bad)(?:\s*[,.!-]*\s*(?:thanks|thank you|thx|ty)\b.*)?[.!]*$/i;
|
|
88
|
+
const RIGHT_NOW = /^i(?:'m| am) (?:currently |just |now )?(?:at|in) (?:the|a|my|work|home)\b.*\b(?:right now|at the moment|today|tonight)\b|^i(?:'m| am) (?:currently |just )?at (?:the|work|home)\b|^我(?:现在|正在)?在(?:机场|车站|路上|地铁上|公司|外面)(?:呢|了)?[。.!!]?$/i;
|
|
89
|
+
const TROUBLESHOOT = /\b(?:getting|got|seeing|having|hitting|hit|receiving) (?:an?|this|the|some|that|weird|strange) (?:\w+ ){0,3}(?:error|exception|warning|crash|bug|issue|problem)s?\b|\bthis error\b|\berror when\b|\b(?:keeps?|kept) (?:crashing|failing|freezing)\b|我(?:这边|这里)?(?:遇到|碰到|出现)了?(?:一个)?(?:报错|错误|问题)|报错了/i;
|
|
90
|
+
|
|
91
|
+
// Tasks ("I'm looking for a gift") and reactions to other people ("I hate when people say…").
|
|
92
|
+
const TASK = /^i(?:'m| am) (?:currently |just )?(?:looking|searching|shopping|hunting) for (?!(?:a |an )?(?:new )?(?:job|work|role|position|apartment|flat|house|place to live|co-?founder)\b)|\btrying to (?:find|pick|choose|buy|decide)\b|^i (?:need|want) to (?:buy|find|order|book|pick)\b|^我(?:想|要|打算)?(?:买|挑|找|订)(?:个|一个|一份|件)?[一-鿿]{0,6}(?:送|给)|^我(?:在|正在)(?:找|挑)(?:个|一个|一份)?(?:礼物|餐厅|饭店|酒店)/i;
|
|
93
|
+
const REACTION = /^i (?:hate|love|like|can't stand|cannot stand) (?:it )?when\b|^我(?:的)?(?:同事|朋友|同学|室友|老板|领导|邻居|亲戚)[一-鿿A-Za-z]{0,4}说(?:他|她|他们)/i;
|
|
94
|
+
// More Chinese self-disclosure shapes: hometown, "not X", weekly routines, birth year, studies, reply style.
|
|
95
|
+
const SELF_ZH2 = /^我(?:的)?老家|^我(?:觉得|认为|感觉)(?:我|自己)|^我是[一-鿿]{1,4}人[。.!!]?$|^我(?:现在|已经|目前|其实)?不(?:是|在|再)|^我(?:每(?:周|星期|个?月)[一二三四五六日天末]?(?:[和、跟到至][一二三四五六日天末])?|每天|每晚|周末|平时)[^,,。??]{0,10}?(?:去|打|练|跑|游|上|学|做|看|玩|起床|健身|骑|写|带|陪)|^我(?:是)?(?:19|20)?\d{2}年(?:的|生的|出生)|^我(?:刚|已经|去年|今年)?(?:大学|本科|硕士|博士|研究生)?毕业|^我(?:大学|本科|研究生|硕士|博士)(?:学的|读的|专业|是)|^(?:以后|今后|之后)?(?:请)?(?:回答|回复)(?:我)?(?:的时候|时|问题)?.{0,6}(?:用|别|不要|简|详|先)|^(?:以后|今后)?(?:请)?(?:都)?先(?:给|说|讲|列)(?:出)?(?:结论|答案|重点|要点)|^我(?:已经|去年|今年|上个月|最近)?(?:戒了|戒掉了?)|^(?:以后|今后|之后)(?:都|请)?(?:用|别|不要|少).{0,8}(?:中文|英文|英语|回复|回答|表格|表情|术语|列表|markdown)|^(?:请)?(?:别|不要|少)用.{0,6}(?:表格|表情|emoji|术语|列表|markdown|英文|代码块)/i;
|
|
96
|
+
// Laughing and chat noise.
|
|
97
|
+
const NOISE = /\b(?:lol|lmao|rofl)\b|\bi'm dying\b|\bkilling me\b|笑死|哈哈哈/i;
|
|
98
|
+
|
|
99
|
+
export function isSelfStatement(s) {
|
|
100
|
+
const t = stripLeadIn(s);
|
|
101
|
+
if (QUESTION.test(s) || NOT_FACT.test(s) || NOISE.test(s) || TRANSIENT.test(t) || SMALL_TALK.test(t) || RIGHT_NOW.test(t) || TROUBLESHOOT.test(t) || TASK.test(t) || REACTION.test(t)) return false;
|
|
102
|
+
return SELF_ZH.test(t) || SELF_ZH2.test(t) || SELF_EN.test(t);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Extract self-statements from a chunk of user-authored text.
|
|
107
|
+
* @returns {{text: string, slot: string|null, value: string|null}[]}
|
|
108
|
+
*/
|
|
109
|
+
// Clauses that are requests to the AI, not facts.
|
|
110
|
+
const REQUEST = /[\s,]please[.!]*$|^(?:别|不要|帮我|帮忙|请帮|推荐|给我|写|能不能|可以|你能|告诉我|看看|顺便|另外|谢谢|please|can you|could you|help|write|recommend|suggest|give me|show me|any\b|find|explain|make|tell me|thanks)/i;
|
|
111
|
+
|
|
112
|
+
// A Chinese clause with the subject left out ("住在成都", "在上海工作", "退休前是老师").
|
|
113
|
+
const IMPLICIT_ZH = /^(?:现在|目前|平时|也|还|已经|退休前|以前)?(?:住在|定居|生活在|搬到|在[一-鿿]{1,8}(?:工作|上班|上学|读书|做|当)|做|当|是|喜欢|擅长|每天|每周|周末)/;
|
|
114
|
+
|
|
115
|
+
/** Split a sentence into fact-sized pieces: each self-statement clause plus its descriptive follow-ups. */
|
|
116
|
+
function clauses(sentence) {
|
|
117
|
+
const parts = sentence.split(/(?<=[,,;;])\s*|\s+(?=and (?:I|I'm|I've)\b)/).filter((p) => p.trim());
|
|
118
|
+
if (parts.length < 2) return [sentence];
|
|
119
|
+
const out = [];
|
|
120
|
+
let cur = null;
|
|
121
|
+
for (const p of parts) {
|
|
122
|
+
if (isSelfStatement(p.replace(/[,,;;]$/, ''))) {
|
|
123
|
+
if (cur) out.push(cur);
|
|
124
|
+
cur = p;
|
|
125
|
+
} else if (cur && /^我(?:很|也|最|特别|超)?(?:喜欢|爱|热爱)/.test(cur) && /^(?:周末|每天|每周|平时|经常|常常)/.test(p)) {
|
|
126
|
+
// "我喜欢徒步,周末常去爬山": how often is part of the hobby, not a separate fact.
|
|
127
|
+
cur += p;
|
|
128
|
+
} else if (cur && IMPLICIT_ZH.test(p) && isSelfStatement('我' + p.replace(/[,,;;]$/, ''))) {
|
|
129
|
+
// "我今年六十岁,退休前是老师,住在成都" → each clause is its own fact, subject restored.
|
|
130
|
+
out.push(cur);
|
|
131
|
+
cur = '我' + p;
|
|
132
|
+
} else if (cur && !REQUEST.test(p.trim().replace(/^(?:but|and|so|但是?|不过|所以|然后)\s*/i, '')) && !QUESTION.test(p.trim())) {
|
|
133
|
+
cur += (/^[A-Za-z0-9]/.test(p) ? ' ' : '') + p;
|
|
134
|
+
} else {
|
|
135
|
+
if (cur) out.push(cur);
|
|
136
|
+
cur = null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (cur) out.push(cur);
|
|
140
|
+
return out.map((c) => c.replace(/[,,;;]\s*$/, '').trim());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Text the user pastes for someone else (a cover letter, an essay, a bio) or asks the AI to act out.
|
|
144
|
+
const PASTED_DOC = /\b(?:here(?:'s| is| are)|this is|below is|attached is|check|review|read|look at|proofread|edit|improve|fix) (?:my|the|a) (?:\w+ ){0,2}(?:cover letter|essay|bio|biography|draft|resume|résumé|cv|personal statement|statement of purpose|speech|story|post|email|letter|profile|intro(?:duction)?|application|paragraph|text)\b[^:\n]{0,40}[::]|(?:这是|下面是|以下是|帮我看看|帮我改改?)(?:我的)?(?:求职信|简历|自我介绍|文章|草稿|作文|个人陈述|演讲稿|邮件|帖子|这段话)[^::\n]{0,20}[::]/i;
|
|
145
|
+
const ROLE_PLAY = /\bpretend (?:you(?:'re| are)|to be) me\b|\b(?:act|play|speak|respond|write) as (?:if you were )?me\b|\bimagine (?:i(?:'m| am)|you(?:'re| are) me)\b|\brole-?play\b|扮演我|假装(?:你是|成)我|你(?:来)?当我/i;
|
|
146
|
+
// Quoted passages that contain first-person text are someone else's words or a draft, not facts.
|
|
147
|
+
const QUOTED = /"[^"\n]*"|“[^”]*”|「[^」]*」|『[^』]*』/g;
|
|
148
|
+
|
|
149
|
+
/** Compound "I live in X and work as Y" → two statements, so each keeps its own slot. */
|
|
150
|
+
function splitCompound(c) {
|
|
151
|
+
const parts = c.split(/\s+and\s+(?=(?:also\s+|now\s+|currently\s+)?(?:work|live|study|teach)\b)/i);
|
|
152
|
+
return parts.map((p, i) => (i ? 'I ' + p : p).trim());
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function extractStatements(text) {
|
|
156
|
+
let src = String(text);
|
|
157
|
+
if (ROLE_PLAY.test(src)) return [];
|
|
158
|
+
const doc = src.search(PASTED_DOC);
|
|
159
|
+
if (doc >= 0) src = src.slice(0, doc);
|
|
160
|
+
src = src.replace(/(\b(?:don't|do not|never|no)\b[^.;!?\n]{2,60});\s*(?=I (?:prefer|'d rather|would rather|like)\b)/gi, '$1 — ');
|
|
161
|
+
src = src.replace(QUOTED, (q) => (/\b(?:I|I'm|I've|my|me)\b|我/i.test(q) ? ' ' : q));
|
|
162
|
+
const out = [];
|
|
163
|
+
for (const s of sentences(src)) {
|
|
164
|
+
if (NOT_FACT.test(s) || NOISE.test(s) || (QUESTION.test(s) && !/[,,;;]/.test(s))) continue;
|
|
165
|
+
for (const raw of clauses(s)) {
|
|
166
|
+
for (const c of splitCompound(stripLeadIn(raw.replace(/^and\s+/i, '')))) {
|
|
167
|
+
if (!isSelfStatement(c)) continue;
|
|
168
|
+
// "I practice every morning" means nothing on its own: attach it to the statement before.
|
|
169
|
+
const prev = out[out.length - 1];
|
|
170
|
+
if (prev && FOLLOW_UP.test(c)) {
|
|
171
|
+
prev.text = `${prev.text.replace(/[.。!!]$/, '')}${/[\u4e00-\u9fff]/.test(c) ? ',' : '; '}${c.replace(/^I /, 'I ')}`;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
const sv = slotOf(c);
|
|
175
|
+
out.push({ text: c, slot: sv?.slot ?? null, value: sv?.value ?? null });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// A short follow-up whose object is only implied by the sentence before it.
|
|
183
|
+
const FOLLOW_UP = /^(?:I (?:practi[cs]e|train|study|play|do (?:it|that|this)|go|work on it|use it|love it|enjoy it)(?: (?:it|that|them))?(?:\s+(?:every|each|once|twice|three|four|five|\d+|daily|weekly|most|on|at|in|before|after|almost|usually|a lot|regularly|whenever)\b[^,;.!?]*)?|我(?:每天|每周|一周|经常|平时)?(?:都|会)?(?:练|练习|学|去|用它|玩)(?:[一两三四五六七八九十\d]+次)?)[.。!!]?$/i;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// The profile generator for web AIs: pick a target AI and a purpose, MindFerry pre-ticks
|
|
2
|
+
// what that AI needs (sensitive things stay unticked, with the reason), the user can tick or
|
|
3
|
+
// untick anything, and gets one text to paste or download. The choice is remembered per AI.
|
|
4
|
+
import { sectionOf, SECTION_TITLES, PROFILE_SECTIONS, PROFILE_OPENER, firstPerson, dedupeLines, dated } from './profile.mjs';
|
|
5
|
+
import { CATEGORY_LABELS } from './card.mjs';
|
|
6
|
+
|
|
7
|
+
export const PURPOSES = ['all', 'work', 'coding', 'study', 'life'];
|
|
8
|
+
|
|
9
|
+
const PURPOSE_CATEGORIES = {
|
|
10
|
+
all: ['identity', 'work', 'skills', 'projects', 'goals', 'preferences', 'communication', 'location', 'other'],
|
|
11
|
+
work: ['identity', 'work', 'skills', 'projects', 'goals', 'communication'],
|
|
12
|
+
coding: ['communication', 'work', 'skills', 'projects', 'preferences'],
|
|
13
|
+
study: ['identity', 'skills', 'projects', 'goals', 'communication', 'preferences'],
|
|
14
|
+
life: ['identity', 'location', 'goals', 'preferences', 'communication', 'other'],
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// Suggested maximum length per destination (custom-instruction fields are short).
|
|
18
|
+
export const SUGGESTED_CHARS = { chatgpt: 1500, 'claude-web': 3000, 'gemini-web': 3000, default: 2500 };
|
|
19
|
+
|
|
20
|
+
/** Why an item is not ticked by default, or null if it is fine to share. */
|
|
21
|
+
export function holdReason(item) {
|
|
22
|
+
if (item.sensitivity === 'secret' || item.category === 'ids') return 'secret';
|
|
23
|
+
if (['health', 'finance', 'others', 'contact'].includes(item.category)) return item.category;
|
|
24
|
+
if (item.sensitivity === 'sensitive') return 'sensitive';
|
|
25
|
+
if (item.sensitivity === 'uncertain') return 'uncertain';
|
|
26
|
+
if (item.locked) return 'locked';
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Default tick for one item, given the purpose. */
|
|
31
|
+
export function defaultTick(item, purpose) {
|
|
32
|
+
if (holdReason(item)) return false;
|
|
33
|
+
return (PURPOSE_CATEGORIES[purpose] || PURPOSE_CATEGORIES.all).includes(item.category);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Candidate list with ticks applied. `saved` is what the user chose last time for this AI:
|
|
38
|
+
* {purpose, on: [ids], off: [ids], seen: [ids]}. Items added since are marked isNew.
|
|
39
|
+
*/
|
|
40
|
+
export function candidates(state, purpose, saved = null) {
|
|
41
|
+
const sameRun = saved && saved.purpose === purpose;
|
|
42
|
+
const on = new Set(sameRun ? saved.on : []);
|
|
43
|
+
const off = new Set(sameRun ? saved.off : []);
|
|
44
|
+
const seen = new Set(saved?.seen || []);
|
|
45
|
+
return state.items
|
|
46
|
+
.filter((i) => i.status === 'active')
|
|
47
|
+
.map((i) => {
|
|
48
|
+
const reason = holdReason(i);
|
|
49
|
+
let ticked = defaultTick(i, purpose);
|
|
50
|
+
if (on.has(i.id) && reason !== 'secret') ticked = true;
|
|
51
|
+
if (off.has(i.id)) ticked = false;
|
|
52
|
+
return {
|
|
53
|
+
id: i.id, text: i.text, category: i.category, sensitivity: i.sensitivity,
|
|
54
|
+
section: sectionOf(i), ticked, reason, canTick: reason !== 'secret',
|
|
55
|
+
isNew: !!saved && !seen.has(i.id), at: i.observedAt,
|
|
56
|
+
};
|
|
57
|
+
})
|
|
58
|
+
.sort((a, b) => (b.at > a.at ? 1 : -1));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Render the ticked items into one text. Auto-condenses to fit maxChars. */
|
|
62
|
+
export function renderProfile(list, { lang = 'en', maxChars = 2500, opener = true } = {}) {
|
|
63
|
+
const ticked = dedupeLines(list.filter((x) => x.ticked && x.canTick));
|
|
64
|
+
const build = (perSection, trim) => {
|
|
65
|
+
let text = `# ${lang === 'zh' ? '关于我' : 'About me'}\n${opener ? PROFILE_OPENER[lang] + '\n' : ''}`;
|
|
66
|
+
const used = [];
|
|
67
|
+
const groups = new Map();
|
|
68
|
+
for (const x of ticked) {
|
|
69
|
+
// Sensitive things the user ticked on purpose go under their own category heading.
|
|
70
|
+
const key = x.reason ? 'cat:' + x.category : 'sec:' + x.section;
|
|
71
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
72
|
+
groups.get(key).push(x);
|
|
73
|
+
}
|
|
74
|
+
const keys = [...PROFILE_SECTIONS.map((s) => 'sec:' + s), ...[...groups.keys()].filter((k) => k.startsWith('cat:'))];
|
|
75
|
+
for (const k of keys) {
|
|
76
|
+
const WHO = ['identity', 'work', 'location', 'preferences', 'other'];
|
|
77
|
+
const g = (groups.get(k) || []).slice().sort((a, b) => (k === 'sec:who' ? WHO.indexOf(a.category) - WHO.indexOf(b.category) : 0)).slice(0, perSection);
|
|
78
|
+
if (!g.length) continue;
|
|
79
|
+
const title = k.startsWith('sec:') ? SECTION_TITLES[k.slice(4)][lang] : CATEGORY_LABELS[k.slice(4)][lang];
|
|
80
|
+
text += `\n## ${title}\n`;
|
|
81
|
+
for (const x of g) {
|
|
82
|
+
const t = dated(firstPerson(x.text.replace(/\s+/g, ' ')), x.at);
|
|
83
|
+
text += `- ${trim && t.length > trim ? t.slice(0, trim - 1) + '…' : t}\n`;
|
|
84
|
+
used.push(x.id);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return { text, used };
|
|
88
|
+
};
|
|
89
|
+
let r = build(Infinity, 0);
|
|
90
|
+
let condensed = false;
|
|
91
|
+
for (const [n, trim] of [[8, 0], [5, 160], [3, 120], [2, 90], [1, 80]]) {
|
|
92
|
+
if (r.text.length <= maxChars) break;
|
|
93
|
+
r = build(n, trim);
|
|
94
|
+
condensed = true;
|
|
95
|
+
}
|
|
96
|
+
if (r.text.length > maxChars) { r.text = r.text.slice(0, maxChars - 1) + '…'; condensed = true; }
|
|
97
|
+
return { text: r.text, chars: r.text.length, itemIds: r.used, condensed, ticked: ticked.length };
|
|
98
|
+
}
|