dsh-workbench-message 0.0.0-stage → 0.1.1

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/lib/db/db.js ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * 消息子插件:表结构与通用行转换。
3
+ *
4
+ * 只依赖 api.db(node:sqlite DatabaseSync),不 import 宿主模块。
5
+ * 消息只在本机保存:apply 里显式 `sync: { tables: [] }`(默认按行同步),
6
+ * 也不提供 exportData/importData,因此不会进入备份包。
7
+ */
8
+
9
+ export const MESSAGE_TABLE = "message";
10
+
11
+ export const MESSAGE_DDL = [
12
+ "CREATE TABLE IF NOT EXISTS message (" +
13
+ "id TEXT PRIMARY KEY," +
14
+ "title TEXT NOT NULL," +
15
+ "body TEXT NOT NULL DEFAULT ''," +
16
+ "level TEXT NOT NULL DEFAULT 'info'," +
17
+ "source TEXT NOT NULL DEFAULT ''," +
18
+ "audience TEXT NOT NULL DEFAULT 'all'," +
19
+ "dedupe_key TEXT," +
20
+ "meta TEXT NOT NULL DEFAULT ''," +
21
+ "created_at INTEGER NOT NULL," +
22
+ "read_at INTEGER," +
23
+ "deleted_at INTEGER," +
24
+ "rev INTEGER NOT NULL DEFAULT 1" +
25
+ ");",
26
+ ];
27
+
28
+ export const MESSAGE_INDEX_DDL = [
29
+ // 去重键只在存活行之间唯一:软删掉的旧消息不占位。
30
+ "CREATE UNIQUE INDEX IF NOT EXISTS uk_message_dedupe ON message(dedupe_key) WHERE dedupe_key IS NOT NULL AND deleted_at IS NULL;",
31
+ "CREATE INDEX IF NOT EXISTS idx_message_created ON message(deleted_at, created_at DESC);",
32
+ "CREATE INDEX IF NOT EXISTS idx_message_unread ON message(deleted_at, read_at);",
33
+ ];
34
+
35
+ let clockNow = null;
36
+ let lastTs = 0;
37
+
38
+ /** 宿主注入同步时钟;未注入时退回本地单调时钟,保证同一毫秒内创建的多条消息有序。 */
39
+ export function bindClock(fn) {
40
+ clockNow = typeof fn === "function" ? fn : null;
41
+ }
42
+
43
+ export function now() {
44
+ if (clockNow) return clockNow();
45
+ const t = Date.now();
46
+ lastTs = t > lastTs ? t : lastTs + 1;
47
+ return lastTs;
48
+ }
49
+
50
+ export function newId(prefix) {
51
+ const head = prefix || "msg";
52
+ let tail = "";
53
+ for (let i = 0; i < 8; i += 1) tail += Math.floor(Math.random() * 36).toString(36);
54
+ return head + "_" + now().toString(36) + "_" + tail;
55
+ }
56
+
57
+ export function tableExists(db, name) {
58
+ try {
59
+ return !!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(String(name));
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ export function tx(db, fn) {
66
+ db.exec("BEGIN IMMEDIATE");
67
+ try {
68
+ const result = fn();
69
+ db.exec("COMMIT");
70
+ return result;
71
+ } catch (error) {
72
+ try {
73
+ db.exec("ROLLBACK");
74
+ } catch {
75
+ /* ignore rollback failure */
76
+ }
77
+ throw error;
78
+ }
79
+ }
80
+
81
+ /** 行 → 对外对象。时间统一用毫秒时间戳,由客户端本地化显示。 */
82
+ export function rowMessage(row) {
83
+ if (!row) return null;
84
+ return {
85
+ id: row.id,
86
+ title: row.title,
87
+ body: row.body || "",
88
+ level: row.level || "info",
89
+ source: row.source || "",
90
+ audience: row.audience || "all",
91
+ dedupeKey: row.dedupe_key || null,
92
+ meta: row.meta || "",
93
+ createdAt: row.created_at,
94
+ readAt: row.read_at || null,
95
+ read: !!row.read_at,
96
+ rev: row.rev,
97
+ };
98
+ }
99
+
100
+ export function ensureSchema(db, log) {
101
+ const logger = typeof log === "function" ? log : function () {};
102
+ for (const sql of MESSAGE_DDL) db.exec(sql);
103
+ for (const sql of MESSAGE_INDEX_DDL) {
104
+ try {
105
+ db.exec(sql);
106
+ } catch (error) {
107
+ logger("message addon: 索引创建失败:" + String((error && error.message) || error));
108
+ }
109
+ }
110
+ }
@@ -0,0 +1,374 @@
1
+ /**
2
+ * 消息域:统一发送入口(agent / 子插件 / 界面共用)、收件箱查询、未读计数与保留清理。
3
+ *
4
+ * 只认 api.db、api.now、api.emit、api.action,不 import 任何业务插件;
5
+ * 其他插件调用本域只能走宿主 `host.invoke("message.send", args, origin)`。
6
+ */
7
+
8
+ import { MESSAGE_TABLE, newId, now, rowMessage } from "../db/db.js";
9
+ import { configValues } from "../infra/config.js";
10
+
11
+ export const LEVELS = ["info", "success", "warning", "error"];
12
+ export const AUDIENCES = ["user", "agent", "all"];
13
+ export const MAX_ROWS = 5000;
14
+ const PRUNE_LIMIT = 200;
15
+
16
+ function fail(message) {
17
+ throw new Error(message);
18
+ }
19
+
20
+ function readString(args, key, max, options) {
21
+ const opts = options || {};
22
+ const raw = args ? args[key] : undefined;
23
+ if (raw === undefined || raw === null) {
24
+ if (opts.required) fail(key + " 必填");
25
+ return opts.fallback === undefined ? "" : opts.fallback;
26
+ }
27
+ if (typeof raw !== "string") fail(key + " 需要字符串");
28
+ const text = raw.trim();
29
+ if (opts.required && !text) fail(key + " 不能为空");
30
+ if (text.length > max) fail(key + " 不能超过 " + max + " 个字符");
31
+ return text;
32
+ }
33
+
34
+ /** 读字符串值本身(供静态扫描能识别 input.<key> 的字段使用)。 */
35
+ function readText(raw, max, key) {
36
+ if (raw === undefined || raw === null) return "";
37
+ if (typeof raw !== "string") fail(key + " 需要字符串");
38
+ const text = raw.trim();
39
+ if (text.length > max) fail(key + " 不能超过 " + max + " 个字符");
40
+ return text;
41
+ }
42
+
43
+ function readEnum(args, key, values, fallback) {
44
+ const raw = args ? args[key] : undefined;
45
+ if (raw === undefined || raw === null || raw === "") return fallback;
46
+ if (typeof raw !== "string" || values.indexOf(raw) < 0) fail(key + " 只接受:" + values.join(" / "));
47
+ return raw;
48
+ }
49
+
50
+ /** 把 meta(对象或字符串)压成不超过 2000 字节的 JSON 字符串。 */
51
+ function readMeta(raw) {
52
+ if (raw === undefined || raw === null || raw === "") return "";
53
+ let text;
54
+ if (typeof raw === "string") {
55
+ text = raw.trim();
56
+ } else if (typeof raw === "object") {
57
+ try {
58
+ text = JSON.stringify(raw);
59
+ } catch {
60
+ fail("meta 无法序列化");
61
+ }
62
+ } else {
63
+ fail("meta 需要对象或 JSON 字符串");
64
+ }
65
+ if (!text) return "";
66
+ if (Buffer.byteLength(text, "utf8") > 2000) fail("meta 不能超过 2000 字节");
67
+ return text;
68
+ }
69
+
70
+ export function normalizeSend(args) {
71
+ const input = args || {};
72
+ const title = readString(input, "title", 120, { required: true });
73
+ const body = readString(input, "body", 4000, {});
74
+ const level = readEnum(input, "level", LEVELS, "info");
75
+ const audience = readEnum(input, "audience", AUDIENCES, "all");
76
+ const source = readString(input, "source", 40, {});
77
+ const dedupeKey = readString(input, "dedupeKey", 120, {});
78
+ return {
79
+ title: title,
80
+ body: body,
81
+ level: level,
82
+ audience: audience,
83
+ source: source,
84
+ dedupeKey: dedupeKey || null,
85
+ meta: readMeta(input.meta),
86
+ };
87
+ }
88
+
89
+ function findDedupe(db, key) {
90
+ if (!key) return null;
91
+ return db.prepare("SELECT * FROM " + MESSAGE_TABLE + " WHERE dedupe_key=? AND deleted_at IS NULL").get(key) || null;
92
+ }
93
+
94
+ /** 清理:已读超过保留天数的物理删除,以及总量超过上限时从最旧的已读开始删;单次最多 200 条。 */
95
+ export function pruneMessages(db, values, ts) {
96
+ const at = typeof ts === "number" ? ts : now();
97
+ let removed = 0;
98
+ const days = Number(values && values["retention.readDays"]);
99
+ if (Number.isFinite(days) && days > 0) {
100
+ const cutoff = at - days * 86400000;
101
+ const result = db
102
+ .prepare(
103
+ "DELETE FROM " + MESSAGE_TABLE +
104
+ " WHERE id IN (SELECT id FROM " + MESSAGE_TABLE +
105
+ " WHERE deleted_at IS NULL AND read_at IS NOT NULL AND read_at < ? ORDER BY read_at LIMIT " + PRUNE_LIMIT + ")",
106
+ )
107
+ .run(cutoff);
108
+ removed += Number(result.changes || 0);
109
+ }
110
+ const total = db.prepare("SELECT COUNT(*) AS n FROM " + MESSAGE_TABLE + " WHERE deleted_at IS NULL").get().n;
111
+ const overflow = Number(total) - MAX_ROWS;
112
+ if (overflow > 0) {
113
+ const result = db
114
+ .prepare(
115
+ "DELETE FROM " + MESSAGE_TABLE +
116
+ " WHERE id IN (SELECT id FROM " + MESSAGE_TABLE +
117
+ " WHERE deleted_at IS NULL AND read_at IS NOT NULL ORDER BY read_at LIMIT " + Math.min(overflow, PRUNE_LIMIT) + ")",
118
+ )
119
+ .run();
120
+ removed += Number(result.changes || 0);
121
+ }
122
+ return removed;
123
+ }
124
+
125
+ export function sendMessage(api, args) {
126
+ const db = api.db;
127
+ const input = normalizeSend(args);
128
+ const existing = findDedupe(db, input.dedupeKey);
129
+ if (existing) return { message: rowMessage(existing), deduped: true, pruned: 0 };
130
+ const ts = now();
131
+ const id = newId("msg");
132
+ db.prepare(
133
+ "INSERT INTO " + MESSAGE_TABLE +
134
+ " (id,title,body,level,source,audience,dedupe_key,meta,created_at,read_at,deleted_at,rev) VALUES (?,?,?,?,?,?,?,?,?,NULL,NULL,1)",
135
+ ).run(id, input.title, input.body, input.level, input.source, input.audience, input.dedupeKey, input.meta, ts);
136
+ const message = rowMessage(db.prepare("SELECT * FROM " + MESSAGE_TABLE + " WHERE id=?").get(id));
137
+ const pruned = pruneMessages(db, configValues(db), ts);
138
+ if (typeof api.emit === "function") api.emit("message.created", { version: 1, message: message });
139
+ return { message: message, deduped: false, pruned: pruned };
140
+ }
141
+
142
+ function buildFilter(args) {
143
+ const input = args || {};
144
+ const where = ["deleted_at IS NULL"];
145
+ const params = [];
146
+ if (input.unreadOnly === true) where.push("read_at IS NULL");
147
+ const levels = Array.isArray(input.levels) ? input.levels : input.level ? [input.level] : [];
148
+ if (levels.length) {
149
+ for (const level of levels) {
150
+ if (LEVELS.indexOf(level) < 0) fail("level 只接受:" + LEVELS.join(" / "));
151
+ }
152
+ where.push("level IN (" + levels.map(() => "?").join(",") + ")");
153
+ params.push(...levels);
154
+ }
155
+ const source = readString(input, "source", 40, {});
156
+ if (source) {
157
+ where.push("source = ?");
158
+ params.push(source);
159
+ }
160
+ const audience = readEnum(input, "audience", AUDIENCES, "");
161
+ if (audience) {
162
+ where.push("audience = ?");
163
+ params.push(audience);
164
+ }
165
+ const text = readText(input.text, 120, "text");
166
+ if (text) {
167
+ where.push("(instr(lower(title), lower(?)) > 0 OR instr(lower(body), lower(?)) > 0)");
168
+ params.push(text, text);
169
+ }
170
+ if (typeof input.since === "number") {
171
+ where.push("created_at >= ?");
172
+ params.push(input.since);
173
+ }
174
+ if (typeof input.before === "number") {
175
+ where.push("created_at < ?");
176
+ params.push(input.before);
177
+ }
178
+ return { where: where.join(" AND "), params: params };
179
+ }
180
+
181
+ function pageOf(args) {
182
+ const input = args || {};
183
+ const pageSize = Math.max(1, Math.min(100, Number(input.pageSize) || 20));
184
+ const pageNumber = Math.max(1, Number(input.pageNumber) || 1);
185
+ return { pageSize: pageSize, pageNumber: pageNumber };
186
+ }
187
+
188
+ export function unreadSummary(db) {
189
+ const unread = db.prepare("SELECT COUNT(*) AS n FROM " + MESSAGE_TABLE + " WHERE deleted_at IS NULL AND read_at IS NULL").get().n;
190
+ const byLevel = db
191
+ .prepare("SELECT level, COUNT(*) AS n FROM " + MESSAGE_TABLE + " WHERE deleted_at IS NULL AND read_at IS NULL GROUP BY level")
192
+ .all();
193
+ const latest = db
194
+ .prepare("SELECT * FROM " + MESSAGE_TABLE + " WHERE deleted_at IS NULL AND read_at IS NULL ORDER BY created_at DESC LIMIT 1")
195
+ .get();
196
+ return {
197
+ unread: Number(unread),
198
+ byLevel: byLevel.map((row) => ({ level: row.level, count: Number(row.n) })),
199
+ latest: latest ? rowMessage(latest) : null,
200
+ };
201
+ }
202
+
203
+ export function listMessages(api, args) {
204
+ const db = api.db;
205
+ const filter = buildFilter(args);
206
+ const page = pageOf(args);
207
+ const total = db.prepare("SELECT COUNT(*) AS n FROM " + MESSAGE_TABLE + " WHERE " + filter.where).get(...filter.params).n;
208
+ const rows = db
209
+ .prepare(
210
+ "SELECT * FROM " + MESSAGE_TABLE + " WHERE " + filter.where +
211
+ " ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?",
212
+ )
213
+ .all(...filter.params, page.pageSize, (page.pageNumber - 1) * page.pageSize);
214
+ const unread = unreadSummary(db);
215
+ return {
216
+ records: rows.map(rowMessage),
217
+ total: Number(total),
218
+ pageNumber: page.pageNumber,
219
+ pageSize: page.pageSize,
220
+ unread: unread.unread,
221
+ };
222
+ }
223
+
224
+ export function markReadMessages(api, args) {
225
+ const db = api.db;
226
+ const input = args || {};
227
+ const ids = Array.isArray(input.ids) ? input.ids.map((id) => String(id)).filter(Boolean) : [];
228
+ const all = input.all === true;
229
+ if (!ids.length && !all && typeof input.before !== "number") fail("需要 ids、all:true 或 before 其中一个");
230
+ const ts = now();
231
+ let updated = 0;
232
+ if (ids.length) {
233
+ const stmt = db.prepare("UPDATE " + MESSAGE_TABLE + " SET read_at=? WHERE id=? AND deleted_at IS NULL AND read_at IS NULL");
234
+ for (const id of ids) updated += Number(stmt.run(ts, id).changes || 0);
235
+ } else if (all) {
236
+ updated = Number(db.prepare("UPDATE " + MESSAGE_TABLE + " SET read_at=? WHERE deleted_at IS NULL AND read_at IS NULL").run(ts).changes || 0);
237
+ } else {
238
+ updated = Number(
239
+ db.prepare("UPDATE " + MESSAGE_TABLE + " SET read_at=? WHERE deleted_at IS NULL AND read_at IS NULL AND created_at <= ?").run(ts, input.before).changes || 0,
240
+ );
241
+ }
242
+ const unread = unreadSummary(db);
243
+ if (updated && typeof api.emit === "function") api.emit("message.read", { version: 1, updated: updated, unread: unread.unread, ids: ids });
244
+ return { updated: updated, unread: unread.unread, at: ts };
245
+ }
246
+
247
+ function dayKey(ts) {
248
+ return new Date(ts).toISOString().slice(0, 10);
249
+ }
250
+
251
+ export function messageStats(api, args) {
252
+ const db = api.db;
253
+ const input = args || {};
254
+ const days = Math.max(1, Math.min(90, Number(input.days) || 14));
255
+ const ts = now();
256
+ const start = ts - days * 86400000;
257
+ const total = Number(db.prepare("SELECT COUNT(*) AS n FROM " + MESSAGE_TABLE + " WHERE deleted_at IS NULL").get().n);
258
+ const unread = unreadSummary(db);
259
+ const byLevel = db
260
+ .prepare("SELECT level, COUNT(*) AS n, SUM(CASE WHEN read_at IS NULL THEN 1 ELSE 0 END) AS unread FROM " + MESSAGE_TABLE + " WHERE deleted_at IS NULL GROUP BY level")
261
+ .all()
262
+ .map((row) => ({ level: row.level, total: Number(row.n), unread: Number(row.unread || 0) }));
263
+ const bySource = db
264
+ .prepare("SELECT source, COUNT(*) AS n FROM " + MESSAGE_TABLE + " WHERE deleted_at IS NULL GROUP BY source ORDER BY n DESC LIMIT 10")
265
+ .all()
266
+ .map((row) => ({ source: row.source || "(未标注)", total: Number(row.n) }));
267
+ const rows = db.prepare("SELECT created_at FROM " + MESSAGE_TABLE + " WHERE deleted_at IS NULL AND created_at >= ?").all(start);
268
+ const buckets = new Map();
269
+ for (let i = days - 1; i >= 0; i -= 1) buckets.set(dayKey(ts - i * 86400000), 0);
270
+ for (const row of rows) {
271
+ const key = dayKey(row.created_at);
272
+ if (buckets.has(key)) buckets.set(key, buckets.get(key) + 1);
273
+ }
274
+ const oldestUnread = db
275
+ .prepare("SELECT * FROM " + MESSAGE_TABLE + " WHERE deleted_at IS NULL AND read_at IS NULL ORDER BY created_at ASC LIMIT 1")
276
+ .get();
277
+ return {
278
+ generatedAt: ts,
279
+ days: days,
280
+ totals: { total: total, unread: unread.unread, read: total - unread.unread },
281
+ byLevel: LEVELS.map((level) => {
282
+ const hit = byLevel.find((row) => row.level === level);
283
+ return { level: level, total: hit ? hit.total : 0, unread: hit ? hit.unread : 0 };
284
+ }),
285
+ bySource: bySource,
286
+ trend: Array.from(buckets, ([date, count]) => ({ date: date, count: count })),
287
+ oldestUnread: oldestUnread ? rowMessage(oldestUnread) : null,
288
+ };
289
+ }
290
+
291
+ export function registerMessageActions(api) {
292
+ const action = api.action;
293
+ action("message.send", {
294
+ description:
295
+ "发送一条消息到工作台消息中心(agent、子插件、界面共用入口)。level 越严重越显眼;dedupeKey 相同且未删除时幂等返回已有消息(deduped=true)。写入只落本机库,不参与同步与备份。",
296
+ input: {
297
+ type: "object",
298
+ properties: {
299
+ title: { type: "string", description: "消息标题,必填,最多 120 字" },
300
+ body: { type: "string", description: "正文,最多 4000 字,可空" },
301
+ level: { type: "string", enum: LEVELS, description: "级别:info(默认)/ success / warning / error" },
302
+ source: { type: "string", description: "来源标识,最多 40 字,建议用插件名或任务 id(如 tasks、sites)" },
303
+ audience: { type: "string", enum: AUDIENCES, description: "收件人:user(给人看)/ agent(给 agent 看)/ all(默认)" },
304
+ dedupeKey: { type: "string", description: "去重键,最多 120 字;同一键在未删除前只保留一条" },
305
+ meta: { type: "object", description: "附加 JSON,最多 2000 字节,如 {taskId, url}" },
306
+ },
307
+ required: ["title"],
308
+ },
309
+ examples: [
310
+ { purpose: "最小调用", args: { title: "备份完成", body: "本次导出 18 个域", level: "success", source: "host" } },
311
+ { purpose: "幂等重试", args: { title: "同步失败", level: "error", source: "host", dedupeKey: "sync-failed-2026-11-12" } },
312
+ ],
313
+ execute: (args) => sendMessage(api, args),
314
+ render: (r) => {
315
+ const m = r.message || {};
316
+ return "已" + (r.deduped ? "命中已有" : "发送") + "消息「" + m.title + "」(" + m.level + ", " + m.id + ")" + (r.pruned ? ",顺带清理 " + r.pruned + " 条旧消息" : "") + "。";
317
+ },
318
+ });
319
+
320
+ action("message.list", {
321
+ description: "分页列出消息,按创建时间倒序;可按未读、级别、来源、收件人、关键词与时间区间过滤",
322
+ input: {
323
+ type: "object",
324
+ properties: {
325
+ unreadOnly: { type: "boolean", description: "只看未读" },
326
+ level: { type: "string", enum: LEVELS, description: "按单个级别过滤" },
327
+ levels: { type: "array", items: { type: "string", enum: LEVELS }, description: "按多个级别过滤" },
328
+ source: { type: "string", description: "按来源精确过滤" },
329
+ audience: { type: "string", enum: AUDIENCES, description: "按收件人过滤" },
330
+ text: { type: "string", description: "标题或正文模糊搜索" },
331
+ since: { type: "number", description: "创建时间下限(毫秒时间戳,含)" },
332
+ before: { type: "number", description: "创建时间上限(毫秒时间戳,不含)" },
333
+ pageNumber: { type: "number", description: "页码,从 1 开始,默认 1" },
334
+ pageSize: { type: "number", description: "每页数量,默认 20,最大 100" },
335
+ },
336
+ },
337
+ execute: (args) => listMessages(api, args),
338
+ render: (r) =>
339
+ "消息 " + r.total + " 条(未读 " + r.unread + "),第 " + r.pageNumber + " 页返回 " + r.records.length + " 条:" +
340
+ r.records.slice(0, 5).map((m) => "[" + m.level + "] " + m.title).join(";"),
341
+ });
342
+
343
+ action("message.unreadCount", {
344
+ description: "未读消息计数:总数、按级别分布与最新一条未读",
345
+ input: { type: "object", properties: {}, additionalProperties: false },
346
+ execute: () => unreadSummary(api.db),
347
+ render: (r) => "未读 " + r.unread + " 条" + (r.latest ? ",最新:「" + r.latest.title + "」" : "") + "。",
348
+ });
349
+
350
+ action("message.markRead", {
351
+ description: "把消息标记为已读:传 ids、all:true 或 before(毫秒时间戳)三者之一",
352
+ input: {
353
+ type: "object",
354
+ properties: {
355
+ ids: { type: "array", items: { type: "string" }, description: "要标记的消息 id 列表" },
356
+ all: { type: "boolean", description: "全部标记为已读" },
357
+ before: { type: "number", description: "把该时间(毫秒时间戳)及之前创建的消息标记为已读" },
358
+ },
359
+ },
360
+ execute: (args) => markReadMessages(api, args),
361
+ render: (r) => "已标记 " + r.updated + " 条为已读,剩余未读 " + r.unread + " 条。",
362
+ });
363
+
364
+ action("message.stats", {
365
+ description: "消息统计:总量、未读、按级别/来源分布与最近 N 天趋势(默认 14 天)",
366
+ input: {
367
+ type: "object",
368
+ properties: { days: { type: "number", description: "趋势天数,1–90,默认 14" } },
369
+ },
370
+ execute: (args) => messageStats(api, args),
371
+ render: (r) =>
372
+ "消息共 " + r.totals.total + " 条(未读 " + r.totals.unread + ");来源 " + r.bySource.length + " 个;统计 " + r.days + " 天。",
373
+ });
374
+ }
package/lib/index.js ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * 消息业务插件(DSH 原生插件)。
3
+ *
4
+ * 定位:工作台内统一的「消息发送入口」——agent、子插件、界面都调用 message.send;
5
+ * 消息只落本机 SQLite(显式 sync:{tables:[]},也不提供备份导入导出),
6
+ * 有新消息时由客户端 notifier 播放提示音。
7
+ *
8
+ * 与其他插件保持弱耦合:本插件不 import 任何业务插件;其他插件调用本域只能走
9
+ * 宿主的 host.invoke("message.send", args),或用客户端 api.call 的前缀路由。
10
+ */
11
+
12
+ import { bindClock, ensureSchema, now, rowMessage } from "./db/db.js";
13
+ import { configValues, registerConfigActions } from "./infra/config.js";
14
+ import { registerDataActions } from "./infra/data.js";
15
+ import { pruneMessages, registerMessageActions } from "./domain/messages.js";
16
+
17
+ export const inject = ["workbench"];
18
+
19
+ let domainApi = null;
20
+ function requireApi() {
21
+ if (!domainApi) throw new Error("消息模块尚未初始化");
22
+ return domainApi;
23
+ }
24
+
25
+ /** 只读「Action」页的数据源由插件自己维护,不经过宿主 schema 接口。 */
26
+ function trackActions(api) {
27
+ const defs = new Map();
28
+ const rawAction = typeof api.action === "function" ? api.action.bind(api) : null;
29
+ if (rawAction) {
30
+ api.action = function (name, def) {
31
+ defs.set(name, def || {});
32
+ return rawAction(name, def);
33
+ };
34
+ }
35
+ return defs;
36
+ }
37
+
38
+ function registerActionSchemaAction(api, defs, domain) {
39
+ const prefix = domain.replace(/^wb-addon-/, "");
40
+ api.action(prefix + ".actionSchema", {
41
+ description: "只读:返回本插件运行时注册的 action schema(供「Action」页渲染;不执行任何 action、不写库、不产生审计)",
42
+ input: { type: "object", properties: {}, additionalProperties: false },
43
+ execute: () => ({
44
+ shellVersion: api.shellVersion || "",
45
+ domains: [{ id: domain, version: api.addon && api.addon.version ? api.addon.version : "" }],
46
+ actions: Array.from(defs, ([name, def]) => ({
47
+ name: name,
48
+ domain: domain,
49
+ description: typeof def.description === "string" ? def.description : "",
50
+ input: def.input && typeof def.input === "object" ? def.input : { type: "object", properties: {} },
51
+ examples: Array.isArray(def.examples) ? def.examples : [],
52
+ })),
53
+ }),
54
+ });
55
+ }
56
+
57
+ export function setup(api) {
58
+ domainApi = api;
59
+ if (typeof api.now === "function") bindClock(api.now);
60
+ ensureSchema(api.db, api.log);
61
+ const actionDefs = trackActions(api);
62
+ registerMessageActions(api);
63
+ registerConfigActions(api);
64
+ registerDataActions(api);
65
+ registerActionSchemaAction(api, actionDefs, "wb-addon-message");
66
+ // 启动时先按保留策略清一次,避免长期不开工作台后积压。
67
+ try {
68
+ const pruned = pruneMessages(api.db, configValues(api.db), now());
69
+ if (pruned) api.log("message addon: 启动清理 " + pruned + " 条");
70
+ } catch (error) {
71
+ api.log("message addon: 启动清理失败:" + String((error && error.message) || error));
72
+ }
73
+ api.log("message domain ready", api.addon.version);
74
+ }
75
+
76
+ export function apply(ctx) {
77
+ const host = ctx.workbench;
78
+ if (!host) throw new Error("dsh-workbench 未加载:缺少 workbench 服务");
79
+ ctx.effect(
80
+ () =>
81
+ host.registerDomain({
82
+ id: "wb-addon-message",
83
+ title: "消息",
84
+ description: "统一消息入口:子插件与 agent 都能发消息,含未读计数、提示音与保留期清理;含统计、收件箱、配置、数据与 Action 五个视图",
85
+ version: "0.1.1",
86
+ tables: ["message"],
87
+ // 只在本机保存:显式声明不同步任何表(不写 sync 时宿主默认按行同步)。
88
+ sync: { tables: [] },
89
+ views: [
90
+ { id: "stats", title: { zh: "统计", en: "Stats" } },
91
+ { id: "inbox", title: { zh: "收件箱", en: "Inbox" } },
92
+ { id: "config", title: { zh: "配置", en: "Config" } },
93
+ { id: "data", title: { zh: "数据", en: "Data" } },
94
+ { id: "actions", title: { zh: "Action", en: "Actions" } },
95
+ ],
96
+ capability: {
97
+ taskOwnership: { boundary: "发消息用 message.send;开发、修复消息插件的工作项用 tasks.create。", query: "message" },
98
+ summary: "工作台内统一的消息入口;只负责消息本身,不负责任务、站点或储存记录。",
99
+ records: [
100
+ {
101
+ kind: "message",
102
+ title: "消息",
103
+ description: "一条发给用户或 agent 的通知,含级别、来源与可选的去重键。",
104
+ when: [
105
+ "某个动作完成、失败或需要用户注意,且不应打断当前操作",
106
+ "子插件愿意在失败时留下可回看的痕迹",
107
+ "同一条通知可能重复触发,需要 dedupeKey 抑制重复",
108
+ ],
109
+ notFor: [
110
+ "不要用消息代替任务或日志;需要后续跟进时仍建任务",
111
+ "不要高频发送无害提示,避免淹没真正需要注意的消息",
112
+ ],
113
+ primaryAction: "message.send",
114
+ keyArgs: ["title", "body", "level", "source"],
115
+ dedupe: "dedupeKey 相同且未删除时幂等返回已有消息(deduped=true),不会新建第二条。",
116
+ relations: [
117
+ { kind: "agent", via: "message.send(audience=agent)", description: "给 agent 留一条待处理通知。" },
118
+ { kind: "plugin", via: "host.invoke(\"message.send\", args, \"ui\")", description: "子插件通过宿主调用,不 import 本插件。" },
119
+ ],
120
+ examples: [{ purpose: "成功通知", args: { title: "备份完成", level: "success", source: "host" } }],
121
+ },
122
+ ],
123
+ fields: [
124
+ { name: "title", type: "string", description: "标题,必填,最多 120 字" },
125
+ { name: "body", type: "string", description: "正文,最多 4000 字" },
126
+ { name: "level", type: "string", description: "info / success / warning / error,默认 info" },
127
+ { name: "source", type: "string", description: "来源标识,最多 40 字,建议用插件名" },
128
+ { name: "audience", type: "string", description: "user / agent / all,默认 all" },
129
+ { name: "dedupeKey", type: "string", description: "去重键,最多 120 字" },
130
+ { name: "meta", type: "object", description: "附加 JSON,最多 2000 字节" },
131
+ { name: "unreadOnly / levels / text / since / before", type: "boolean|string[]|string|number", description: "message.list 的过滤条件" },
132
+ { name: "ids / all / before", type: "string[]|boolean|number", description: "message.markRead 的三种标记方式" },
133
+ ],
134
+ notFor: ["不要用它承载需要长期跟进的事项(那是任务)", "不要在插件加载期反复发送启动成功之类的噪音"],
135
+ notes: [
136
+ "消息只在本机保存:不参与同步,也不进入备份包,换机后不会带过去。",
137
+ "已读消息默认保留 30 天(可配置),未读不按时间清理;总量上限 5000 条,超出从最旧的已读开始删。",
138
+ "提示音由客户端播放,可在配置页关闭、调音量并设置免打扰时间段。",
139
+ ],
140
+ },
141
+ setup,
142
+ }),
143
+ "message-domain",
144
+ );
145
+ }
146
+
147
+ // 便于测试与外部引用:域 id、版本、导出面保持一致。
148
+ export const MESSAGE_DOMAIN = "wb-addon-message";
149
+ export { rowMessage, requireApi };