@nestim/koishi-plugin-qqgm-webui 0.2.12 → 0.2.14

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/index.js CHANGED
@@ -10,8 +10,24 @@ const { execFile } = require('node:child_process');
10
10
  const { promisify } = require('node:util');
11
11
  const { Schema } = require('koishi');
12
12
  const { pluginList, monitor, memory } = require('./lib/data');
13
+ const { readMemoryConfig, writeMemoryConfig } = require('./lib/config');
14
+ const { scan: scanMemoryMd, scopeOfFile } = require('./lib/memory-md');
13
15
  const run = promisify(execFile);
14
16
 
17
+ async function readBody(koa) {
18
+ const parsed = koa.request && koa.request.body;
19
+ if (parsed && typeof parsed === 'object') return parsed;
20
+ if (typeof parsed === 'string' && parsed.trim()) {
21
+ try { return JSON.parse(parsed); } catch { return {}; }
22
+ }
23
+ let raw = '';
24
+ try {
25
+ for await (const chunk of koa.req) raw += chunk;
26
+ } catch { /* body already consumed */ }
27
+ if (!raw) return {};
28
+ try { return JSON.parse(raw); } catch { return {}; }
29
+ }
30
+
15
31
  const name = 'qqgm-webui';
16
32
  const inject = ['server'];
17
33
 
@@ -98,7 +114,7 @@ function apply(ctx, config) {
98
114
  ctx.server.get(`${route}/api/health`, (koa) => json(koa, {
99
115
  ok: true,
100
116
  name,
101
- version: '0.2.12',
117
+ version: '0.2.14',
102
118
  route,
103
119
  tokenRequired: !!config.token,
104
120
  remoteAllowed: !!config.allowRemote,
@@ -122,6 +138,75 @@ function apply(ctx, config) {
122
138
  }));
123
139
  });
124
140
 
141
+ ctx.server.get(`${route}/api/memory/config`, (koa) => {
142
+ const cfg = readMemoryConfig(ctx);
143
+ const md = scanMemoryMd(ctx.baseDir || process.cwd());
144
+ json(koa, { ...cfg, md: { files: md.files, total: md.entries.length } });
145
+ });
146
+
147
+ ctx.server.post(`${route}/api/config/memory`, async (koa) => {
148
+ if (!guard(koa)) return;
149
+ const body = await readBody(koa);
150
+ const backend = String(body.backend || '');
151
+ const dbFile = String(body.dbFile || readMemoryConfig(ctx).dbFile);
152
+ try {
153
+ const result = writeMemoryConfig(ctx, { backend, dbFile });
154
+ json(koa, { ok: true, ...result, restartRequired: true });
155
+ } catch (error) {
156
+ koa.status = 400;
157
+ koa.body = { ok: false, error: String(error && error.message || error) };
158
+ }
159
+ });
160
+
161
+ ctx.server.post(`${route}/api/memory/migrate`, async (koa) => {
162
+ if (!guard(koa)) return;
163
+ const body = await readBody(koa);
164
+ const cfg = readMemoryConfig(ctx);
165
+ const dbFile = String(body.dbFile || cfg.dbFile || 'data/qqgm-memory.sqlite');
166
+ const abs = path.resolve(ctx.baseDir || process.cwd(), dbFile);
167
+ let Store;
168
+ try {
169
+ Store = require('@nestim/koishi-plugin-qqgm-memory/lib/store').SqliteMemoryStore;
170
+ } catch {
171
+ koa.status = 501;
172
+ koa.body = { ok: false, error: '请先安装 qqgm-memory' };
173
+ return;
174
+ }
175
+ const md = scanMemoryMd(ctx.baseDir || process.cwd());
176
+ if (!md.entries.length) {
177
+ koa.status = 400;
178
+ koa.body = { ok: false, error: '没有找到 Memory_*.md' };
179
+ return;
180
+ }
181
+ let store;
182
+ try {
183
+ store = new Store(abs);
184
+ for (const file of md.files) {
185
+ const content = fs.readFileSync(path.join(ctx.baseDir || process.cwd(), file.file), 'utf8');
186
+ store.replaceFromMarkdown({ kind: file.kind, id: file.id }, content);
187
+ }
188
+ const stats = store.stats();
189
+ store.close();
190
+ let configResult = null;
191
+ if (body.switchBackend !== false) {
192
+ configResult = writeMemoryConfig(ctx, { backend: 'sqlite', dbFile });
193
+ }
194
+ json(koa, {
195
+ ok: true,
196
+ imported: md.entries.length,
197
+ total: stats.total,
198
+ mdFiles: md.files.length,
199
+ switchBackend: !!configResult,
200
+ backup: configResult && configResult.backup,
201
+ restartRequired: !!configResult,
202
+ });
203
+ } catch (error) {
204
+ try { if (store) store.close(); } catch { /* ignore */ }
205
+ koa.status = 500;
206
+ koa.body = { ok: false, error: String(error && error.message || error) };
207
+ }
208
+ });
209
+
125
210
  ctx.server.get(`${route}/api/logs`, (koa) => {
126
211
  const file = path.join(ctx.baseDir || process.cwd(), 'data', 'logs', 'qqgm.log');
127
212
  let lines = [];
package/lib/config.js ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 只改主插件记忆相关的两个字段;先备份,再原子写。
3
+ * 不重写整份 YAML,保留注释和插件顺序。
4
+ */
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ let yaml = null;
8
+ try { yaml = require('js-yaml'); } catch { /* 没装 js-yaml 时跳过语法校验 */ }
9
+
10
+ const KEY_RE = /^(\s*)'?@nestim\/(?:koishi-plugin-)?qq-group-manager(?::[^']*)?'?\s*:\s*$/;
11
+
12
+ function findBlock(lines) {
13
+ const start = lines.findIndex((line) => KEY_RE.test(line));
14
+ if (start < 0) throw new Error('未找到主插件配置块 @nestim/qq-group-manager');
15
+ const indent = (lines[start].match(/^\s*/) || [''])[0].length;
16
+ let end = start + 1;
17
+ while (end < lines.length) {
18
+ const line = lines[end];
19
+ if (!line.trim()) { end += 1; continue; }
20
+ const current = (line.match(/^\s*/) || [''])[0].length;
21
+ if (current <= indent && !line.trim().startsWith('#')) break;
22
+ end += 1;
23
+ }
24
+ return { start, end, indent };
25
+ }
26
+
27
+ function readValue(lines, block, key) {
28
+ const re = new RegExp(`^\\s*${key}\\s*:\\s*(.*)$`);
29
+ for (let i = block.start + 1; i < block.end; i += 1) {
30
+ const match = re.exec(lines[i]);
31
+ if (match) return match[1].replace(/\s+#.*$/, '').trim().replace(/^['"]|['"]$/g, '');
32
+ }
33
+ return null;
34
+ }
35
+
36
+ function setValue(lines, key, value) {
37
+ const block = findBlock(lines);
38
+ const re = new RegExp(`^(\\s*)${key}\\s*:\\s*.*$`);
39
+ let found = false;
40
+ for (let i = block.start + 1; i < block.end; i += 1) {
41
+ const match = re.exec(lines[i]);
42
+ if (match) {
43
+ lines[i] = `${match[1]}${key}: ${value}`;
44
+ found = true;
45
+ break;
46
+ }
47
+ }
48
+ if (!found) {
49
+ const indent = ' '.repeat(block.indent + 2);
50
+ lines.splice(block.end, 0, `${indent}${key}: ${value}`);
51
+ }
52
+ }
53
+
54
+ function readMemoryConfig(ctx) {
55
+ const file = path.join(ctx.baseDir || process.cwd(), 'koishi.yml');
56
+ let text = '';
57
+ try { text = fs.readFileSync(file, 'utf8'); } catch { /* ignore */ }
58
+ const lines = text.split(/\r?\n/);
59
+ let backend = 'md';
60
+ let dbFile = 'data/qqgm-memory.sqlite';
61
+ try {
62
+ const block = findBlock(lines);
63
+ backend = readValue(lines, block, 'memoryBackend') || backend;
64
+ dbFile = readValue(lines, block, 'memoryDbFile') || dbFile;
65
+ } catch { /* ignore */ }
66
+ return { backend, dbFile, file };
67
+ }
68
+
69
+ function writeMemoryConfig(ctx, { backend, dbFile }) {
70
+ if (!['md', 'sqlite'].includes(backend)) throw new Error('memoryBackend 只能是 md 或 sqlite');
71
+ if (!/^[A-Za-z0-9_./-]+\.sqlite$/.test(dbFile)) throw new Error('memoryDbFile 必须是 .sqlite 路径');
72
+ const file = path.join(ctx.baseDir || process.cwd(), 'koishi.yml');
73
+ const before = fs.readFileSync(file, 'utf8');
74
+ const lines = before.split(/\r?\n/);
75
+ setValue(lines, 'memoryBackend', backend);
76
+ setValue(lines, 'memoryDbFile', dbFile);
77
+ const next = lines.join('\n');
78
+ if (yaml) yaml.load(next);
79
+ const stamp = new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14);
80
+ const backup = `${file}.bak-memory-${stamp}`;
81
+ fs.copyFileSync(file, backup);
82
+ const tmp = `${file}.tmp`;
83
+ fs.writeFileSync(tmp, next, 'utf8');
84
+ fs.renameSync(tmp, file);
85
+ return { backup, backend, dbFile };
86
+ }
87
+
88
+ module.exports = { readMemoryConfig, writeMemoryConfig };
package/lib/data.js CHANGED
@@ -5,6 +5,8 @@
5
5
  const fs = require('node:fs');
6
6
  const path = require('node:path');
7
7
  const { DatabaseSync } = require('node:sqlite');
8
+ const { readMemoryConfig } = require('./config');
9
+ const { scan: scanMemoryMd } = require('./memory-md');
8
10
 
9
11
  const AUTHOR = 'Miseat';
10
12
  const KNOWN = [
@@ -153,33 +155,53 @@ function parseScope(text) {
153
155
  function memory(ctx, { scope = '', query = '', limit = 50 } = {}) {
154
156
  const base = ctx.baseDir || process.cwd();
155
157
  const file = path.join(base, 'data', 'qqgm-memory.sqlite');
156
- if (!fs.existsSync(file)) return { installed: false, items: [] };
157
- let db;
158
- try { db = new DatabaseSync(file); } catch { return { installed: false, error: 'SQLite 打开失败', items: [] }; }
159
- try {
160
- const parsed = parseScope(scope);
161
- let sql = 'SELECT * FROM memories WHERE active=1';
162
- const params = [];
163
- if (parsed) { sql += ' AND scope_kind=? AND scope_id=?'; params.push(parsed.kind, parsed.id); }
164
- if (query) { sql += ' AND (content LIKE ? OR label LIKE ?)'; params.push(`%${query}%`, `%${query}%`); }
165
- sql += ' ORDER BY created_at DESC LIMIT ?';
166
- params.push(Math.max(1, Math.min(200, Number(limit) || 50)));
167
- const items = db.prepare(sql).all(...params);
168
- const total = db.prepare('SELECT COUNT(*) n FROM memories WHERE active=1').get().n;
169
- const scopes = db.prepare(`
170
- SELECT scope_kind, scope_id, COUNT(*) n FROM memories
171
- WHERE active=1 GROUP BY scope_kind, scope_id ORDER BY n DESC
172
- `).all();
173
- const categories = db.prepare(`
174
- SELECT COALESCE(category, '未分类') category, COUNT(*) n FROM memories
175
- WHERE active=1 GROUP BY COALESCE(category, '未分类') ORDER BY n DESC
176
- `).all();
177
- return { installed: true, items, total, scopes, categories };
178
- } catch (error) {
179
- return { installed: false, error: String(error), items: [] };
180
- } finally {
181
- try { db.close(); } catch { /* ignore */ }
158
+ const cfg = readMemoryConfig(ctx);
159
+ const md = scanMemoryMd(base);
160
+ let sqliteItems = [];
161
+ let sqliteInstalled = false;
162
+ if (fs.existsSync(file)) {
163
+ let db;
164
+ try { db = new DatabaseSync(file); } catch { db = null; }
165
+ if (db) {
166
+ sqliteInstalled = true;
167
+ try {
168
+ sqliteItems = db.prepare('SELECT * FROM memories WHERE active=1 ORDER BY created_at DESC').all();
169
+ } catch { sqliteItems = []; }
170
+ try { db.close(); } catch { /* ignore */ }
171
+ }
172
+ }
173
+
174
+ // 主插件后端是 sqlite 且已有数据才展示 SQLite;否则优先识别旧 MD
175
+ const useSqlite = cfg.backend === 'sqlite' && sqliteItems.length > 0;
176
+ const source = useSqlite ? sqliteItems : (md.entries.length ? md.entries : sqliteItems);
177
+ const parsed = parseScope(scope);
178
+ let filtered = source;
179
+ if (parsed) filtered = filtered.filter((item) => item.scope_kind === parsed.kind && String(item.scope_id) === String(parsed.id));
180
+ if (query) filtered = filtered.filter((item) => String(item.content).includes(query) || String(item.label || '').includes(query));
181
+ const items = filtered.slice(0, Math.max(1, Math.min(200, Number(limit) || 50)));
182
+ const scopes = new Map();
183
+ const categories = new Map();
184
+ for (const item of source) {
185
+ const key = `${item.scope_kind}:${item.scope_id || ''}`;
186
+ scopes.set(key, (scopes.get(key) || 0) + 1);
187
+ const category = item.category || '未分类';
188
+ categories.set(category, (categories.get(category) || 0) + 1);
182
189
  }
190
+ return {
191
+ installed: sqliteInstalled || md.entries.length > 0,
192
+ backend: cfg.backend,
193
+ sqliteInstalled,
194
+ useSqlite,
195
+ needsMigration: md.entries.length > 0 && !useSqlite,
196
+ items,
197
+ total: source.length,
198
+ md: { files: md.files, total: md.entries.length },
199
+ scopes: [...scopes].map(([key, n]) => {
200
+ const [scope_kind, scope_id] = key.split(':');
201
+ return { scope_kind, scope_id, n };
202
+ }),
203
+ categories: [...categories].map(([category, n]) => ({ category, n })),
204
+ };
183
205
  }
184
206
 
185
207
  module.exports = { pluginList, monitor, memory, AUTHOR };
@@ -0,0 +1,62 @@
1
+ /**
2
+ * 旧 Memory_*.md 的识别与解析。
3
+ * 只读,不改原文件;迁移时交给 SQLite store。
4
+ */
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+
8
+ const FILE_RE = /^Memory(_.+_(群聊|私聊))?\.md$/;
9
+
10
+ function scopeOfFile(file) {
11
+ const match = /^Memory_(.+)_(群聊|私聊)\.md$/.exec(file);
12
+ if (!match) return { kind: 'global', id: '' };
13
+ return { kind: match[2] === '私聊' ? 'private' : 'group', id: match[1] };
14
+ }
15
+
16
+ function parseBlocks(text, file, scope) {
17
+ return String(text || '')
18
+ .split(/\r?\n---\r?\n/)
19
+ .map((block) => block.trim())
20
+ .filter(Boolean)
21
+ .map((block, index) => {
22
+ const match = /^##\s+(.+?)\s+·\s+(.+?)\n([\s\S]*)$/.exec(block);
23
+ if (!match) return null;
24
+ const [, stamp, label, content] = match;
25
+ const parts = label.split(/\s*·\s*/);
26
+ const category = parts.length > 1 ? parts.pop() : '未分类';
27
+ return {
28
+ id: `md:${file}:${index}`,
29
+ source: 'md',
30
+ file,
31
+ scope_kind: scope.kind,
32
+ scope_id: scope.id,
33
+ category,
34
+ label: parts.join(' · ') || '记忆',
35
+ content: content.trim(),
36
+ created_at: Date.parse(stamp) || Date.now(),
37
+ order: index,
38
+ hash: null,
39
+ };
40
+ })
41
+ .filter(Boolean);
42
+ }
43
+
44
+ function scan(baseDir) {
45
+ const files = [];
46
+ const entries = [];
47
+ try {
48
+ for (const file of fs.readdirSync(baseDir)) {
49
+ if (!FILE_RE.test(file)) continue;
50
+ const scope = scopeOfFile(file);
51
+ const full = path.join(baseDir, file);
52
+ let text = '';
53
+ try { text = fs.readFileSync(full, 'utf8'); } catch { continue; }
54
+ const parsed = parseBlocks(text, file, scope);
55
+ files.push({ file, ...scope, entries: parsed.length });
56
+ entries.push(...parsed);
57
+ }
58
+ } catch { /* ignore */ }
59
+ return { files, entries };
60
+ }
61
+
62
+ module.exports = { scan, parseBlocks, scopeOfFile };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestim/koishi-plugin-qqgm-webui",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "description": "QQGM 附属 WebUI:插件识别、监控看板、记忆库、配置与日志。",
5
5
  "main": "index.js",
6
6
  "files": [
package/public/app.js CHANGED
@@ -126,6 +126,18 @@ async function initMemoryData() {
126
126
  if (!data || !data.installed) return;
127
127
  const badge = $('.nav-badge');
128
128
  if (badge) badge.textContent = String(data.total || 0);
129
+ const migrateBtn = $('#migrateMemory');
130
+ const switchBtn = $('#switchMd');
131
+ if (migrateBtn) migrateBtn.hidden = !data.needsMigration;
132
+ if (switchBtn) switchBtn.hidden = !data.useSqlite;
133
+ const note = $('#memoryBackend');
134
+ if (note) {
135
+ note.innerHTML = data.useSqlite
136
+ ? '当前使用 SQLite;修改前会备份 <code>koishi.yml</code>,旧 MD 文件保留可回滚。'
137
+ : (data.needsMigration
138
+ ? `当前使用 MD,识别到 ${data.md?.total || 0} 条旧记忆、${data.md?.files?.length || 0} 个文件。迁移会导入 SQLite 并切换后端,迁移前不改 MD。`
139
+ : '默认使用 MD;没有识别到旧记忆文件。');
140
+ }
129
141
  const scopes = $('#memoryScopes');
130
142
  if (scopes) {
131
143
  const scopeButtons = [`<h3>范围</h3><button class="scope active"><span>全部</span><b>${data.total || 0}</b></button>`];
@@ -159,6 +171,41 @@ async function initMemoryData() {
159
171
  }
160
172
  initMemoryData();
161
173
 
174
+ async function memoryPost(path, body) {
175
+ const token = new URLSearchParams(location.search).get('token') || '';
176
+ const res = await fetch(`${path}${token ? `?token=${encodeURIComponent(token)}` : ''}`, {
177
+ method: 'POST',
178
+ headers: { 'content-type': 'application/json' },
179
+ body: JSON.stringify(body || {}),
180
+ });
181
+ const data = await res.json();
182
+ if (!res.ok || !data.ok) throw new Error(data.error || `HTTP ${res.status}`);
183
+ return data;
184
+ }
185
+
186
+ $('#migrateMemory')?.addEventListener('click', async () => {
187
+ if (!confirm('把 Memory_*.md 导入 SQLite,并把主插件后端切到 sqlite?\\n\\n会先备份 koishi.yml,MD 文件不改。')) return;
188
+ try {
189
+ showToast('正在迁移…');
190
+ const data = await memoryPost('api/memory/migrate', { switchBackend: true });
191
+ showToast(`迁移 ${data.imported} 条,已切换;重启后生效`);
192
+ setTimeout(() => location.reload(), 1800);
193
+ } catch (error) {
194
+ showToast(`迁移失败:${String(error.message || error)}`);
195
+ }
196
+ });
197
+
198
+ $('#switchMd')?.addEventListener('click', async () => {
199
+ if (!confirm('把主插件记忆后端切回 md?SQLite 数据不会删除,可随时切回。')) return;
200
+ try {
201
+ await memoryPost('api/config/memory', { backend: 'md' });
202
+ showToast('已切回 md,重启后生效');
203
+ setTimeout(() => location.reload(), 1500);
204
+ } catch (error) {
205
+ showToast(`切换失败:${String(error.message || error)}`);
206
+ }
207
+ });
208
+
162
209
  async function installPackage(pkg) {
163
210
  const token = new URLSearchParams(location.search).get('token') || '';
164
211
  showToast(`正在安装 ${pkg}…`);
package/public/index.html CHANGED
@@ -319,8 +319,9 @@
319
319
  <div class="page-head">
320
320
  <div><h1>记忆库</h1><p>默认 MD;已安装 qqgm-memory,切换主插件后端后可用 SQLite</p></div>
321
321
  <div class="head-actions">
322
- <div class="segmented"><button class="active">MD</button><button data-toast="SQLite 需要安装 qqgm-memory 并切换主插件后端">SQLite(需切换)</button></div>
323
- <button class="btn primary" data-toast="新增记忆(原型)">+ 新增</button>
322
+ <div class="segmented"><button class="active">MD</button><button data-toast="SQLite 需要迁移后切换">SQLite</button></div>
323
+ <button class="btn ghost" id="switchMd">切回 MD</button>
324
+ <button class="btn primary" id="migrateMemory">迁移到 SQLite</button>
324
325
  </div>
325
326
  </div>
326
327
  <div class="memory-note" id="memoryBackend">默认使用 MD,兼容现有记忆文件;安装数据库附属插件 <b>qqgm-memory</b> 后可切换 SQLite,迁移前会先备份。</div>