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,366 @@
|
|
|
1
|
+
// Importers: whole-account exports (ChatGPT, Claude, Gemini Takeout, Grok, DeepSeek,
|
|
2
|
+
// Open WebUI) and single conversations (pasted text, Markdown, saved web pages, JSON).
|
|
3
|
+
// Each parser returns { client, messages: [{role, text, at, conv, title}], memories: [{text, at}] }.
|
|
4
|
+
// messages — every message; facts are extracted only from role "user"
|
|
5
|
+
// memories — the vendor's own memory notes about the user
|
|
6
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
7
|
+
import { basename } from 'node:path';
|
|
8
|
+
import { isZip, listZip } from './zip.mjs';
|
|
9
|
+
import { FriendlyError } from '../core/errors.mjs';
|
|
10
|
+
import { clientInfo, detectVendor } from '../core/clients.mjs';
|
|
11
|
+
import { hash } from '../core/text.mjs';
|
|
12
|
+
|
|
13
|
+
const MAX_FILE = 512 * 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
function toIso(v) {
|
|
16
|
+
if (v === undefined || v === null || v === '') return null;
|
|
17
|
+
if (typeof v === 'object' && v.$date) v = v.$date;
|
|
18
|
+
if (typeof v === 'object' && v.$numberLong) v = Number(v.$numberLong);
|
|
19
|
+
if (typeof v === 'number') return new Date(v < 1e12 ? v * 1000 : v).toISOString();
|
|
20
|
+
const d = new Date(v);
|
|
21
|
+
return isNaN(d) ? null : d.toISOString();
|
|
22
|
+
}
|
|
23
|
+
const roleOf = (r) => (/^(user|human|me|you)$/i.test(String(r || '')) ? 'user' : 'assistant');
|
|
24
|
+
|
|
25
|
+
// ---- ChatGPT (and DeepSeek, which uses a similar "mapping" tree) -------------
|
|
26
|
+
function parseMapping(json) {
|
|
27
|
+
const messages = [];
|
|
28
|
+
let deepseek = false;
|
|
29
|
+
for (const conv of json) {
|
|
30
|
+
const cid = conv.id || conv.conversation_id || hash(String(conv.title) + conv.create_time);
|
|
31
|
+
for (const node of Object.values(conv.mapping || {})) {
|
|
32
|
+
const m = node?.message;
|
|
33
|
+
if (!m) continue;
|
|
34
|
+
if (Array.isArray(m.fragments)) { // DeepSeek
|
|
35
|
+
deepseek = true;
|
|
36
|
+
for (const f of m.fragments) {
|
|
37
|
+
if (typeof f?.content !== 'string' || f.type === 'THINK') continue;
|
|
38
|
+
messages.push({ role: f.type === 'REQUEST' ? 'user' : 'assistant', text: f.content, at: toIso(m.inserted_at), conv: cid, title: conv.title });
|
|
39
|
+
}
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const role = m.author?.role;
|
|
43
|
+
if (role !== 'user' && role !== 'assistant') continue;
|
|
44
|
+
const text = (m.content?.parts || []).filter((x) => typeof x === 'string').join('\n');
|
|
45
|
+
if (text.trim()) messages.push({ role, text, at: toIso(m.create_time) || toIso(conv.update_time), conv: cid, title: conv.title });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return { client: deepseek ? 'deepseek' : 'chatgpt', messages, memories: [] };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ---- Claude web: conversations.json (+ memories.json) -----------------------
|
|
52
|
+
function parseClaude(json) {
|
|
53
|
+
const messages = [];
|
|
54
|
+
for (const conv of json) {
|
|
55
|
+
for (const m of conv.chat_messages || []) {
|
|
56
|
+
let text = m.text || '';
|
|
57
|
+
if (!text && Array.isArray(m.content)) text = m.content.filter((c) => c.type === 'text').map((c) => c.text).join('\n');
|
|
58
|
+
if (text.trim()) messages.push({ role: m.sender === 'human' ? 'user' : 'assistant', text, at: toIso(m.created_at) || toIso(conv.updated_at), conv: conv.uuid, title: conv.name });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return { client: 'claude-web', messages, memories: [] };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function parseClaudeMemories(json) {
|
|
65
|
+
const memories = [];
|
|
66
|
+
for (const m of Array.isArray(json) ? json : [json]) {
|
|
67
|
+
if (typeof m?.conversations_memory === 'string') memories.push({ text: m.conversations_memory, at: null });
|
|
68
|
+
for (const v of Object.values(m?.project_memories || {})) if (typeof v === 'string') memories.push({ text: v, at: null });
|
|
69
|
+
}
|
|
70
|
+
return { client: 'claude-web', messages: [], memories };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---- Gemini: Google Takeout "My Activity" (JSON or HTML) ---------------------
|
|
74
|
+
const GEMINI_PREFIX = /^(?:Prompted|已提示|提示了|已发送提示|You said|你说)\s*[::]?\s*/i;
|
|
75
|
+
function parseGeminiJson(json) {
|
|
76
|
+
const messages = [];
|
|
77
|
+
for (const a of json) {
|
|
78
|
+
if (typeof a?.title !== 'string' || !GEMINI_PREFIX.test(a.title)) continue;
|
|
79
|
+
const at = toIso(a.time);
|
|
80
|
+
messages.push({ role: 'user', text: a.title.replace(GEMINI_PREFIX, ''), at, conv: at?.slice(0, 10) || null, title: 'Gemini' });
|
|
81
|
+
}
|
|
82
|
+
return { client: 'gemini-web', messages, memories: [] };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function decodeEntities(s) {
|
|
86
|
+
return s.replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
87
|
+
.replace(/"/g, '"').replace(/'|'/g, "'").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(+n));
|
|
88
|
+
}
|
|
89
|
+
const stripTags = (h) => decodeEntities(h.replace(/<(script|style)[\s\S]*?<\/\1>/gi, ' ').replace(/<br\s*\/?>|<\/(p|div|li|h\d|pre)>/gi, '\n').replace(/<[^>]+>/g, ' ')).replace(/[ \t]+/g, ' ').replace(/\n\s*\n+/g, '\n\n').trim();
|
|
90
|
+
|
|
91
|
+
function parseGeminiHtml(html) {
|
|
92
|
+
const messages = [];
|
|
93
|
+
for (const cell of html.split(/<div class="[^"]*content-cell[^"]*"[^>]*>/).slice(1)) {
|
|
94
|
+
const txt = stripTags(cell.split('</div>')[0]);
|
|
95
|
+
if (GEMINI_PREFIX.test(txt)) messages.push({ role: 'user', text: txt.replace(GEMINI_PREFIX, ''), at: null, conv: null, title: 'Gemini' });
|
|
96
|
+
}
|
|
97
|
+
return { client: 'gemini-web', messages, memories: [] };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ---- Grok ---------------------------------------------------------------------
|
|
101
|
+
function parseGrok(json) {
|
|
102
|
+
const messages = [];
|
|
103
|
+
for (const c of json.conversations || []) {
|
|
104
|
+
const cid = c.conversation?.id || c.id || null;
|
|
105
|
+
const title = c.conversation?.title || c.title || null;
|
|
106
|
+
for (const r of c.responses || []) {
|
|
107
|
+
const resp = r.response || r;
|
|
108
|
+
const text = resp.message || resp.text || resp.query || '';
|
|
109
|
+
if (typeof text === 'string' && text.trim()) messages.push({ role: roleOf(resp.sender || resp.role), text, at: toIso(resp.create_time || resp.createTime), conv: cid, title });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { client: 'grok-web', messages, memories: [] };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ---- Open WebUI (local models) --------------------------------------------------
|
|
116
|
+
function parseOpenWebUI(json) {
|
|
117
|
+
const messages = [];
|
|
118
|
+
for (const c of json) {
|
|
119
|
+
for (const m of c.chat?.messages || []) {
|
|
120
|
+
if (typeof m.content === 'string' && m.content.trim()) messages.push({ role: roleOf(m.role), text: m.content, at: toIso(m.timestamp), conv: c.id, title: c.title || c.chat?.title });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return { client: 'local-llm', messages, memories: [] };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ---- Generic JSON fallback: any object with a role/sender + text --------------
|
|
127
|
+
// Any JSON chat format, including ones that don't exist yet: find objects that look like a
|
|
128
|
+
// message (a speaker + some text), group them by the nearest object that looks like a chat.
|
|
129
|
+
const SPEAKER_USER = /^(user|human|me|you|customer|prompt|question|user_message|human_message|q)$/i;
|
|
130
|
+
const SPEAKER_AI = /^(assistant|ai|bot|model|gpt|chatbot|answer|response|a|assistant_message|ai_message|copilot|gemini|claude|grok|deepseek|kimi|doubao|qwen)$/i;
|
|
131
|
+
const TEXT_KEYS = ['text', 'content', 'message', 'body', 'value', 'prompt', 'response', 'markdown', 'msg', 'said', 'utterance'];
|
|
132
|
+
function textOf(o) {
|
|
133
|
+
for (const k of TEXT_KEYS) {
|
|
134
|
+
const v = o[k];
|
|
135
|
+
if (typeof v === 'string' && v.trim()) return v;
|
|
136
|
+
if (Array.isArray(v?.parts)) return v.parts.filter((x) => typeof x === 'string').join('\n');
|
|
137
|
+
if (Array.isArray(v)) { const t = v.map((x) => (typeof x === 'string' ? x : x?.text || '')).filter(Boolean).join('\n'); if (t.trim()) return t; }
|
|
138
|
+
if (v && typeof v === 'object' && typeof v.text === 'string') return v.text;
|
|
139
|
+
}
|
|
140
|
+
return '';
|
|
141
|
+
}
|
|
142
|
+
function speakerOf(o) {
|
|
143
|
+
if (typeof o.is_user === 'boolean') return o.is_user ? 'user' : 'assistant';
|
|
144
|
+
if (typeof o.isUser === 'boolean') return o.isUser ? 'user' : 'assistant';
|
|
145
|
+
if (typeof o.fromUser === 'boolean') return o.fromUser ? 'user' : 'assistant';
|
|
146
|
+
const r = o.role ?? o.sender ?? o.author?.role ?? o.author ?? o.from ?? o.speaker ?? o.type ?? o.who;
|
|
147
|
+
if (typeof r !== 'string') return null;
|
|
148
|
+
if (/system|tool|function/i.test(r)) return 'skip';
|
|
149
|
+
if (SPEAKER_USER.test(r.trim())) return 'user';
|
|
150
|
+
if (SPEAKER_AI.test(r.trim())) return 'assistant';
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
export function parseGeneric(json, client) {
|
|
154
|
+
const messages = [];
|
|
155
|
+
let convN = 0;
|
|
156
|
+
const walk = (o, depth, conv, title) => {
|
|
157
|
+
if (!o || typeof o !== 'object' || depth > 16) return;
|
|
158
|
+
if (Array.isArray(o)) { for (const x of o) walk(x, depth + 1, conv, title); return; }
|
|
159
|
+
const sp = speakerOf(o);
|
|
160
|
+
if (sp === 'skip') return;
|
|
161
|
+
if (sp) {
|
|
162
|
+
const t = textOf(o);
|
|
163
|
+
if (t.trim()) { messages.push({ role: sp, text: t, at: toIso(o.created_at || o.create_time || o.createdAt || o.timestamp || o.time || o.date || o.at), conv, title }); return; }
|
|
164
|
+
}
|
|
165
|
+
// A pair object: {question, answer} / {prompt, response} / {input, output}
|
|
166
|
+
const q = o.question ?? o.prompt ?? o.input ?? o.query;
|
|
167
|
+
const a = o.answer ?? o.response ?? o.output ?? o.reply ?? o.completion;
|
|
168
|
+
if (typeof q === 'string' && q.trim() && (typeof a === 'string' || a === undefined) && !sp) {
|
|
169
|
+
const at = toIso(o.created_at || o.timestamp || o.time || o.date || o.at);
|
|
170
|
+
messages.push({ role: 'user', text: q, at, conv, title });
|
|
171
|
+
if (typeof a === 'string' && a.trim()) messages.push({ role: 'assistant', text: a, at, conv, title });
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const looksLikeChat = Object.values(o).some((v) => Array.isArray(v) && v.length && typeof v[0] === 'object');
|
|
175
|
+
const nextConv = looksLikeChat && (o.id || o.uuid || o.title || o.name) ? String(o.id || o.uuid || ('c' + ++convN)) : conv;
|
|
176
|
+
const nextTitle = looksLikeChat && (o.title || o.name) ? String(o.title || o.name).slice(0, 200) : title;
|
|
177
|
+
for (const v of Object.values(o)) walk(v, depth + 1, nextConv, nextTitle);
|
|
178
|
+
};
|
|
179
|
+
walk(json, 0, 'import', null);
|
|
180
|
+
return { client, messages, memories: [] };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// CSV with a speaker column and a text column (e.g. activity exports), or a prompt/response pair per row.
|
|
184
|
+
function parseCsvRows(text) {
|
|
185
|
+
const rows = [];
|
|
186
|
+
let row = [], cell = '', q = false;
|
|
187
|
+
for (let i = 0; i < text.length; i++) {
|
|
188
|
+
const c = text[i];
|
|
189
|
+
if (q) { if (c === '"') { if (text[i + 1] === '"') { cell += '"'; i++; } else q = false; } else cell += c; continue; }
|
|
190
|
+
if (c === '"') q = true;
|
|
191
|
+
else if (c === ',' || c === '\t') { row.push(cell); cell = ''; }
|
|
192
|
+
else if (c === '\n' || c === '\r') { if (c === '\r' && text[i + 1] === '\n') i++; row.push(cell); rows.push(row); row = []; cell = ''; }
|
|
193
|
+
else cell += c;
|
|
194
|
+
}
|
|
195
|
+
if (cell || row.length) { row.push(cell); rows.push(row); }
|
|
196
|
+
return rows.filter((r) => r.some((x) => x.trim()));
|
|
197
|
+
}
|
|
198
|
+
export function parseCsv(text, client) {
|
|
199
|
+
const rows = parseCsvRows(text);
|
|
200
|
+
if (rows.length < 2) return { client, messages: [], memories: [] };
|
|
201
|
+
const head = rows[0].map((h) => h.trim().toLowerCase());
|
|
202
|
+
const find = (re) => head.findIndex((h) => re.test(h));
|
|
203
|
+
const iSpeaker = find(/^(role|sender|speaker|author|from|who|type)$/);
|
|
204
|
+
const iText = find(/^(text|content|message|body|msg)$/);
|
|
205
|
+
const iQ = find(/^(prompt|question|query|input|user ?(message|prompt|input)?|request)$/);
|
|
206
|
+
const iA = find(/^(response|answer|output|reply|ai ?(message|response)?|assistant|completion)$/);
|
|
207
|
+
const iTime = find(/time|date|created/);
|
|
208
|
+
const iConv = find(/^(conversation|conversation ?id|chat ?id|thread|thread ?id|session|title)$/);
|
|
209
|
+
const messages = [];
|
|
210
|
+
for (const r of rows.slice(1)) {
|
|
211
|
+
const at = iTime >= 0 ? toIso(r[iTime]) : null;
|
|
212
|
+
const conv = iConv >= 0 && r[iConv] ? r[iConv] : 'import';
|
|
213
|
+
if (iSpeaker >= 0 && iText >= 0) {
|
|
214
|
+
const sp = speakerOf({ role: r[iSpeaker] });
|
|
215
|
+
if (sp && sp !== 'skip' && r[iText]?.trim()) messages.push({ role: sp, text: r[iText], at, conv, title: iConv >= 0 ? r[iConv] : null });
|
|
216
|
+
} else if (iQ >= 0) {
|
|
217
|
+
if (r[iQ]?.trim()) messages.push({ role: 'user', text: r[iQ], at, conv, title: null });
|
|
218
|
+
if (iA >= 0 && r[iA]?.trim()) messages.push({ role: 'assistant', text: r[iA], at, conv, title: null });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { client, messages, memories: [] };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ---- Single conversation as text / Markdown -----------------------------------
|
|
225
|
+
const USER_LABEL = /^\s*(?:#{1,4}\s*)?(?:\*\*)?(?:you said|you|user|me|human|q|我说|我|用户|提问)(?:\*\*)?\s*[::]\s*(?:\*\*)?\s*/i;
|
|
226
|
+
const AI_LABEL = /^\s*(?:#{1,4}\s*)?(?:\*\*)?(?:chatgpt said|chatgpt|claude said|claude|gemini said|gemini|grok said|grok|assistant|ai|a|bot|model|deepseek|kimi|豆包|通义千问|通义|千问|qwen|助手|回答)(?:\*\*)?\s*[::]\s*(?:\*\*)?\s*/i;
|
|
227
|
+
const MD_HEADING_USER = /^\s*#{1,4}\s*(?:you|user|me|human|我|用户)\s*$/i;
|
|
228
|
+
const MD_HEADING_AI = /^\s*#{1,4}\s*(?:assistant|chatgpt|claude|gemini|grok|ai|deepseek|kimi|豆包|通义|助手)\s*$/i;
|
|
229
|
+
|
|
230
|
+
/** Parse a pasted chat. With speaker labels → roles; without → treated as the user's own text. */
|
|
231
|
+
export function parseTranscript(text, { title } = {}) {
|
|
232
|
+
const lines = String(text).replace(/\r/g, '').split('\n');
|
|
233
|
+
const messages = [];
|
|
234
|
+
let cur = null;
|
|
235
|
+
let labelled = false;
|
|
236
|
+
const conv = 'paste-' + hash(String(text).slice(0, 2000));
|
|
237
|
+
const flush = () => { if (cur && cur.text.trim()) messages.push({ ...cur, text: cur.text.trim() }); cur = null; };
|
|
238
|
+
for (const line of lines) {
|
|
239
|
+
let m;
|
|
240
|
+
if (MD_HEADING_USER.test(line)) { flush(); cur = { role: 'user', text: '' }; labelled = true; continue; }
|
|
241
|
+
if (MD_HEADING_AI.test(line)) { flush(); cur = { role: 'assistant', text: '' }; labelled = true; continue; }
|
|
242
|
+
if ((m = line.match(USER_LABEL))) { flush(); cur = { role: 'user', text: line.slice(m[0].length) + '\n' }; labelled = true; continue; }
|
|
243
|
+
if ((m = line.match(AI_LABEL))) { flush(); cur = { role: 'assistant', text: line.slice(m[0].length) + '\n' }; labelled = true; continue; }
|
|
244
|
+
if (!cur) cur = { role: 'user', text: '' };
|
|
245
|
+
cur.text += line + '\n';
|
|
246
|
+
}
|
|
247
|
+
flush();
|
|
248
|
+
if (!labelled) return { messages: [{ role: 'user', text: String(text).trim(), conv, title: title || null, at: null }], labelled: false };
|
|
249
|
+
return { messages: messages.map((m) => ({ ...m, conv, title: title || null, at: null })), labelled: true };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Saved conversation web page (ChatGPT has data-message-author-role; others → text). */
|
|
253
|
+
function parseSavedPage(html, name) {
|
|
254
|
+
const title = (html.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1]?.trim() || name;
|
|
255
|
+
const conv = 'page-' + hash(html.slice(0, 5000));
|
|
256
|
+
const roleBlocks = [...html.matchAll(/data-message-author-role="(user|assistant)"[^>]*>([\s\S]*?)(?=data-message-author-role="|<\/main>|$)/g)];
|
|
257
|
+
if (roleBlocks.length) {
|
|
258
|
+
return { client: 'chatgpt', messages: roleBlocks.map((b) => ({ role: b[1], text: stripTags(b[2]), conv, title, at: null })).filter((m) => m.text), memories: [] };
|
|
259
|
+
}
|
|
260
|
+
const text = stripTags(html);
|
|
261
|
+
const t = parseTranscript(text, { title });
|
|
262
|
+
return { client: detectVendor(title + '\n' + text), messages: t.messages.map((m) => ({ ...m, conv })), memories: [] };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Detect + parse one file. Returns a parse result, {generic: json}, or null. */
|
|
266
|
+
export function detect(name, data) {
|
|
267
|
+
const lower = name.toLowerCase();
|
|
268
|
+
const str = () => data.toString('utf8').replace(/^/, '');
|
|
269
|
+
if (lower.endsWith('.html') || lower.endsWith('.htm')) {
|
|
270
|
+
const html = str();
|
|
271
|
+
if (/content-cell/.test(html) && /Gemini|Bard/i.test(html)) return parseGeminiHtml(html);
|
|
272
|
+
if (/content-cell/.test(html)) return null; // other Takeout activity pages
|
|
273
|
+
if (/^chat\.html$/i.test(basename(lower))) return null; // ChatGPT's duplicate of conversations.json
|
|
274
|
+
return parseSavedPage(html, name);
|
|
275
|
+
}
|
|
276
|
+
if (lower.endsWith('.md') || lower.endsWith('.txt') || lower.endsWith('.markdown')) {
|
|
277
|
+
const text = str();
|
|
278
|
+
const t = parseTranscript(text, { title: basename(name) });
|
|
279
|
+
return { client: detectVendor(name + '\n' + text), messages: t.messages, memories: [] };
|
|
280
|
+
}
|
|
281
|
+
if (lower.endsWith('.csv') || lower.endsWith('.tsv')) {
|
|
282
|
+
const text = str();
|
|
283
|
+
const p = parseCsv(text, detectVendor(name + '\n' + text.slice(0, 2000)));
|
|
284
|
+
return p.messages.length ? p : null;
|
|
285
|
+
}
|
|
286
|
+
if (!lower.endsWith('.json') && !lower.endsWith('.jsonl') && !lower.endsWith('.ndjson')) return null;
|
|
287
|
+
if (lower.endsWith('.jsonl') || lower.endsWith('.ndjson')) {
|
|
288
|
+
const arr = str().split(/\n+/).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
289
|
+
return { generic: arr };
|
|
290
|
+
}
|
|
291
|
+
let json;
|
|
292
|
+
try { json = JSON.parse(str()); } catch { return null; }
|
|
293
|
+
if (/memor/.test(lower) && !Array.isArray(json?.[0]?.chat_messages)) return parseClaudeMemories(json);
|
|
294
|
+
if (Array.isArray(json)) {
|
|
295
|
+
const s = json.find((x) => x && typeof x === 'object') || {};
|
|
296
|
+
if ('mapping' in s) return parseMapping(json);
|
|
297
|
+
if ('chat_messages' in s) return parseClaude(json);
|
|
298
|
+
if ('header' in s && 'title' in s) return parseGeminiJson(json);
|
|
299
|
+
if (s.chat && Array.isArray(s.chat.messages)) return parseOpenWebUI(json);
|
|
300
|
+
if (/users?\.json$|projects?\.json$|shared_conversations|message_feedback|model_comparisons/.test(lower)) return null;
|
|
301
|
+
}
|
|
302
|
+
if (Array.isArray(json?.conversations) && json.conversations.some((c) => Array.isArray(c?.responses))) return parseGrok(json);
|
|
303
|
+
return { generic: json };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Import an export file or a single saved chat (path or {name, buffer}).
|
|
308
|
+
* @param {import('../core/hub.mjs').Hub} hub
|
|
309
|
+
* @param {string|{name: string, buffer: Buffer}} input
|
|
310
|
+
* @param {{client?: string, sync?: boolean}} [opts] client: force the source AI
|
|
311
|
+
*/
|
|
312
|
+
export async function importFile(hub, input, opts = {}) {
|
|
313
|
+
const name = typeof input === 'string' ? basename(input) : input.name;
|
|
314
|
+
if (typeof input === 'string' && !existsSync(input)) throw new FriendlyError('FILE_NOT_FOUND', { path: input }, 404);
|
|
315
|
+
const buf = typeof input === 'string' ? readFileSync(input) : input.buffer;
|
|
316
|
+
if (buf.length > MAX_FILE) throw new FriendlyError('FILE_TOO_LARGE', {}, 413);
|
|
317
|
+
if (!buf.toString('utf8', 0, 4096).trim() && buf.length < 4096) throw new FriendlyError('FILE_BLANK', {}, 422);
|
|
318
|
+
const ext = (name.match(/\.([a-z0-9]+)$/i)?.[1] || '').toLowerCase();
|
|
319
|
+
const kind = /^(png|jpe?g|gif|webp|heic|bmp|tiff?|svg)$/.test(ext) ? 'image' : ext === 'pdf' ? 'pdf'
|
|
320
|
+
: /^(docx?|pages|xlsx?|pptx?|key|numbers|rtf|odt)$/.test(ext) ? 'doc' : /^(mp[34]|mov|m4a|wav|exe|dmg|app|pkg)$/.test(ext) ? 'other' : null;
|
|
321
|
+
if (kind) throw new FriendlyError('FILE_NOT_CHAT', { kind }, 422);
|
|
322
|
+
if (opts.client && !clientInfo(opts.client)) throw new FriendlyError('UNKNOWN_CLIENT', { id: opts.client });
|
|
323
|
+
|
|
324
|
+
const files = isZip(buf)
|
|
325
|
+
? listZip(buf).filter((e) => /\.(json|jsonl|ndjson|csv|tsv|html?|md|txt)$/i.test(e.name) && !/\/__MACOSX\//.test(e.name) && e.size < MAX_FILE)
|
|
326
|
+
: [{ name, read: () => buf }];
|
|
327
|
+
|
|
328
|
+
const byClient = {};
|
|
329
|
+
let unknown = 0;
|
|
330
|
+
for (const f of files) {
|
|
331
|
+
const r = detect(f.name, f.read());
|
|
332
|
+
if (!r) continue;
|
|
333
|
+
let parsed = r;
|
|
334
|
+
if (r.generic !== undefined) {
|
|
335
|
+
parsed = parseGeneric(r.generic, opts.client || detectVendor(f.name) || null);
|
|
336
|
+
if (!parsed.messages.length) continue;
|
|
337
|
+
}
|
|
338
|
+
const client = opts.client || parsed.client;
|
|
339
|
+
if (!client) { unknown++; continue; }
|
|
340
|
+
const b = (byClient[client] ||= { messages: [], memories: [] });
|
|
341
|
+
b.messages.push(...parsed.messages);
|
|
342
|
+
b.memories.push(...parsed.memories);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
if (!Object.keys(byClient).length) {
|
|
346
|
+
if (unknown) throw new FriendlyError('FILE_UNRECOGNIZED', {}, 422);
|
|
347
|
+
throw new FriendlyError('FILE_EMPTY', {}, 422);
|
|
348
|
+
}
|
|
349
|
+
const result = { file: name, imported: {} };
|
|
350
|
+
for (const [client, parsed] of Object.entries(byClient)) result.imported[client] = await hub.ingest(client, parsed);
|
|
351
|
+
if (opts.sync) result.sync = await hub.sync();
|
|
352
|
+
return result;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Import a pasted conversation. The source AI is guessed from labels unless given. */
|
|
356
|
+
export async function importText(hub, text, opts = {}) {
|
|
357
|
+
if (!text || !String(text).trim()) throw new FriendlyError('PASTE_EMPTY');
|
|
358
|
+
const client = opts.client || detectVendor(text);
|
|
359
|
+
if (!client) throw new FriendlyError('FILE_UNRECOGNIZED', {}, 422);
|
|
360
|
+
if (!clientInfo(client)) throw new FriendlyError('UNKNOWN_CLIENT', { id: client });
|
|
361
|
+
const t = parseTranscript(text, { title: opts.title });
|
|
362
|
+
const r = await hub.ingest(client, { messages: t.messages, memories: [] });
|
|
363
|
+
const result = { file: opts.title || 'paste', imported: { [client]: r }, labelled: t.labelled };
|
|
364
|
+
if (opts.sync) result.sync = await hub.sync();
|
|
365
|
+
return result;
|
|
366
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Minimal zip reader (stored + deflate), zero dependencies. Reads from a Buffer.
|
|
2
|
+
import { inflateRawSync } from 'node:zlib';
|
|
3
|
+
import { FriendlyError } from '../core/errors.mjs';
|
|
4
|
+
|
|
5
|
+
export function isZip(buf) {
|
|
6
|
+
return buf.length > 4 && buf.readUInt32LE(0) === 0x04034b50;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** @returns {{name: string, size: number, read: () => Buffer}[]} */
|
|
10
|
+
export function listZip(buf) {
|
|
11
|
+
// Find End Of Central Directory (scan back up to 64KB + 22).
|
|
12
|
+
let eocd = -1;
|
|
13
|
+
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
|
|
14
|
+
if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
|
|
15
|
+
}
|
|
16
|
+
if (eocd < 0) throw new FriendlyError('ZIP_BAD');
|
|
17
|
+
const count = buf.readUInt16LE(eocd + 10);
|
|
18
|
+
let p = buf.readUInt32LE(eocd + 16);
|
|
19
|
+
if (p === 0xffffffff || count === 0xffff) throw new FriendlyError('ZIP64');
|
|
20
|
+
const entries = [];
|
|
21
|
+
for (let n = 0; n < count; n++) {
|
|
22
|
+
if (buf.readUInt32LE(p) !== 0x02014b50) throw new FriendlyError('ZIP_BAD');
|
|
23
|
+
const method = buf.readUInt16LE(p + 10);
|
|
24
|
+
const csize = buf.readUInt32LE(p + 20);
|
|
25
|
+
const usize = buf.readUInt32LE(p + 24);
|
|
26
|
+
const nlen = buf.readUInt16LE(p + 28);
|
|
27
|
+
const xlen = buf.readUInt16LE(p + 30);
|
|
28
|
+
const clen = buf.readUInt16LE(p + 32);
|
|
29
|
+
const local = buf.readUInt32LE(p + 42);
|
|
30
|
+
const name = buf.subarray(p + 46, p + 46 + nlen).toString('utf8');
|
|
31
|
+
p += 46 + nlen + xlen + clen;
|
|
32
|
+
if (name.endsWith('/')) continue;
|
|
33
|
+
entries.push({
|
|
34
|
+
name,
|
|
35
|
+
size: usize,
|
|
36
|
+
read() {
|
|
37
|
+
const lnlen = buf.readUInt16LE(local + 26);
|
|
38
|
+
const lxlen = buf.readUInt16LE(local + 28);
|
|
39
|
+
const start = local + 30 + lnlen + lxlen;
|
|
40
|
+
const data = buf.subarray(start, start + csize);
|
|
41
|
+
if (method === 0) return Buffer.from(data);
|
|
42
|
+
if (method === 8) { try { return inflateRawSync(data); } catch { throw new FriendlyError('ZIP_BAD'); } }
|
|
43
|
+
throw new FriendlyError('ZIP_BAD');
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return entries;
|
|
48
|
+
}
|