@chbo297/infoflow 2026.3.4 → 2026.3.7

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.
@@ -0,0 +1,267 @@
1
+ /**
2
+ * SQLite-backed persistent store for sent message IDs.
3
+ * Records messageid + msgseqid for every outbound message so that
4
+ * recall (撤回) can look up any sub-message, including those from split sends.
5
+ *
6
+ * Uses Node 22+ built-in `node:sqlite` (DatabaseSync, synchronous API).
7
+ */
8
+
9
+ import fs from "node:fs";
10
+ import { createRequire } from "node:module";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import type { DatabaseSync } from "node:sqlite";
14
+ import { getInfoflowRuntime } from "./runtime.js";
15
+ import type { InfoflowMessageContentItem } from "./types.js";
16
+
17
+ const require = createRequire(import.meta.url);
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Constants
21
+ // ---------------------------------------------------------------------------
22
+
23
+ const DB_FILENAME = "sent-messages.db";
24
+ const AUTO_CLEANUP_DAYS = 7;
25
+ const AUTO_CLEANUP_MS = AUTO_CLEANUP_DAYS * 24 * 60 * 60 * 1000;
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // DB singleton (lazy-init)
29
+ // ---------------------------------------------------------------------------
30
+
31
+ let db: DatabaseSync | null = null;
32
+
33
+ function resolveDbPath(): string {
34
+ const env = process.env;
35
+ const stateDir = getInfoflowRuntime().state.resolveStateDir(env, os.homedir);
36
+ return path.join(stateDir, "infoflow", DB_FILENAME);
37
+ }
38
+
39
+ function getDb(): DatabaseSync {
40
+ if (db) return db;
41
+
42
+ const dbPath = resolveDbPath();
43
+ const dir = path.dirname(dbPath);
44
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
45
+
46
+ const sqlite = require("node:sqlite") as typeof import("node:sqlite");
47
+ db = new sqlite.DatabaseSync(dbPath);
48
+
49
+ db.exec(`
50
+ CREATE TABLE IF NOT EXISTS sent_messages (
51
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
52
+ account_id TEXT NOT NULL,
53
+ target TEXT NOT NULL,
54
+ from_id TEXT NOT NULL DEFAULT '',
55
+ messageid TEXT NOT NULL,
56
+ msgseqid TEXT NOT NULL DEFAULT '',
57
+ digest TEXT NOT NULL DEFAULT '',
58
+ sent_at INTEGER NOT NULL
59
+ );
60
+ `);
61
+ db.exec(`
62
+ CREATE INDEX IF NOT EXISTS idx_target_sent
63
+ ON sent_messages(account_id, target, sent_at DESC);
64
+ `);
65
+
66
+ // Migration: add from_id column to existing databases
67
+ try {
68
+ db.exec(`ALTER TABLE sent_messages ADD COLUMN from_id TEXT NOT NULL DEFAULT ''`);
69
+ } catch {
70
+ // Column already exists — ignore
71
+ }
72
+
73
+ return db;
74
+ }
75
+
76
+ // ---------------------------------------------------------------------------
77
+ // Public API
78
+ // ---------------------------------------------------------------------------
79
+
80
+ export type SentMessageRecord = {
81
+ target: string;
82
+ from: string;
83
+ messageid: string;
84
+ msgseqid: string;
85
+ digest: string;
86
+ sentAt: number;
87
+ };
88
+
89
+ /**
90
+ * Records a sent message. Also runs auto-cleanup of old records.
91
+ * Synchronous (DatabaseSync); failures are swallowed so sending is never blocked.
92
+ */
93
+ export function recordSentMessage(accountId: string, record: SentMessageRecord): void {
94
+ try {
95
+ const d = getDb();
96
+ d.prepare(
97
+ `INSERT INTO sent_messages (account_id, target, from_id, messageid, msgseqid, digest, sent_at)
98
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
99
+ ).run(
100
+ accountId,
101
+ record.target,
102
+ record.from,
103
+ record.messageid,
104
+ record.msgseqid,
105
+ record.digest,
106
+ record.sentAt,
107
+ );
108
+
109
+ // Auto-cleanup: delete records older than 7 days
110
+ const cutoff = Date.now() - AUTO_CLEANUP_MS;
111
+ d.prepare(`DELETE FROM sent_messages WHERE sent_at < ? AND account_id = ?`).run(
112
+ cutoff,
113
+ accountId,
114
+ );
115
+ } catch {
116
+ // Silently ignore — do not block sending
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Queries the most recent N sent messages for a given target, ordered by sent_at DESC.
122
+ */
123
+ export function querySentMessages(
124
+ accountId: string,
125
+ params: { target: string; count: number },
126
+ ): SentMessageRecord[] {
127
+ const d = getDb();
128
+ const rows = d
129
+ .prepare(
130
+ `SELECT target, from_id, messageid, msgseqid, digest, sent_at
131
+ FROM sent_messages
132
+ WHERE account_id = ? AND target = ?
133
+ ORDER BY sent_at DESC
134
+ LIMIT ?`,
135
+ )
136
+ .all(accountId, params.target, params.count) as Array<{
137
+ target: string;
138
+ from_id: string;
139
+ messageid: string;
140
+ msgseqid: string;
141
+ digest: string;
142
+ sent_at: number;
143
+ }>;
144
+
145
+ return rows.map((r) => ({
146
+ target: r.target,
147
+ from: r.from_id,
148
+ messageid: r.messageid,
149
+ msgseqid: r.msgseqid,
150
+ digest: r.digest,
151
+ sentAt: r.sent_at,
152
+ }));
153
+ }
154
+
155
+ /**
156
+ * Finds a single sent message by messageid.
157
+ */
158
+ export function findSentMessage(
159
+ accountId: string,
160
+ messageid: string,
161
+ ): SentMessageRecord | undefined {
162
+ const d = getDb();
163
+ const row = d
164
+ .prepare(
165
+ `SELECT target, from_id, messageid, msgseqid, digest, sent_at
166
+ FROM sent_messages
167
+ WHERE account_id = ? AND messageid = ?
168
+ LIMIT 1`,
169
+ )
170
+ .get(accountId, messageid) as
171
+ | {
172
+ target: string;
173
+ from_id: string;
174
+ messageid: string;
175
+ msgseqid: string;
176
+ digest: string;
177
+ sent_at: number;
178
+ }
179
+ | undefined;
180
+
181
+ if (!row) return undefined;
182
+ return {
183
+ target: row.target,
184
+ from: row.from_id,
185
+ messageid: row.messageid,
186
+ msgseqid: row.msgseqid,
187
+ digest: row.digest,
188
+ sentAt: row.sent_at,
189
+ };
190
+ }
191
+
192
+ /**
193
+ * Removes recalled messages from the store by their messageids.
194
+ */
195
+ export function removeRecalledMessages(accountId: string, messageids: string[]): void {
196
+ if (messageids.length === 0) return;
197
+ const d = getDb();
198
+ const placeholders = messageids.map(() => "?").join(",");
199
+ d.prepare(
200
+ `DELETE FROM sent_messages WHERE account_id = ? AND messageid IN (${placeholders})`,
201
+ ).run(accountId, ...messageids);
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // From-ID builder
206
+ // ---------------------------------------------------------------------------
207
+
208
+ /** Builds a `from` identifier for self-sent (agent) messages. */
209
+ export function buildAgentFrom(appAgentId: number | undefined): string {
210
+ return appAgentId != null ? `agent:${appAgentId}` : "agent:unknown";
211
+ }
212
+
213
+ // ---------------------------------------------------------------------------
214
+ // Digest builder
215
+ // ---------------------------------------------------------------------------
216
+
217
+ const DIGEST_MAX_LEN = 100;
218
+
219
+ /**
220
+ * Builds a short digest string from message contents.
221
+ * - Text/markdown/link: first 100 chars, truncated with "…"
222
+ * - Image only: "image"
223
+ * - Empty: ""
224
+ */
225
+ export function buildMessageDigest(contents: InfoflowMessageContentItem[]): string {
226
+ const textParts: string[] = [];
227
+ let hasImage = false;
228
+
229
+ for (const item of contents) {
230
+ const type = item.type.toLowerCase();
231
+ if (type === "text" || type === "md" || type === "markdown") {
232
+ textParts.push(item.content);
233
+ } else if (type === "link") {
234
+ textParts.push(item.content);
235
+ } else if (type === "image") {
236
+ hasImage = true;
237
+ }
238
+ }
239
+
240
+ const merged = textParts.join(" ").trim();
241
+ if (merged) {
242
+ return merged.length > DIGEST_MAX_LEN ? merged.slice(0, DIGEST_MAX_LEN) + "…" : merged;
243
+ }
244
+ if (hasImage) return "image";
245
+ return "";
246
+ }
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // Test-only exports (@internal)
250
+ // ---------------------------------------------------------------------------
251
+
252
+ /** @internal — Close and reset the DB singleton. Only use in tests. */
253
+ export function _resetStore(): void {
254
+ if (db) {
255
+ try {
256
+ db.close();
257
+ } catch {
258
+ // ignore
259
+ }
260
+ db = null;
261
+ }
262
+ }
263
+
264
+ /** @internal — Override the DB instance for testing. */
265
+ export function _setDb(next: DatabaseSync): void {
266
+ db = next;
267
+ }
package/src/types.ts CHANGED
@@ -42,6 +42,8 @@ export type InfoflowInboundBodyItem = {
42
42
  name?: string;
43
43
  /** 人类用户 AT 时有此字段(uuap name),与 robotid 互斥 */
44
44
  userid?: string;
45
+ /** IMAGE 类型 body item 的图片下载地址 */
46
+ downloadurl?: string;
45
47
  };
46
48
 
47
49
  /** Mention IDs extracted from inbound group AT items (excluding the bot itself) */
@@ -69,14 +71,25 @@ export type InfoflowGroupMessageBodyItem =
69
71
  | { type: "TEXT"; content: string }
70
72
  | { type: "MD"; content: string }
71
73
  | { type: "AT"; atall?: boolean; atuserids: string[]; atagentids?: number[] }
72
- | { type: "LINK"; href: string };
74
+ | { type: "LINK"; href: string }
75
+ | { type: "IMAGE"; content: string };
73
76
 
74
77
  /** Content item for sendInfoflowMessage */
75
78
  export type InfoflowMessageContentItem = {
76
- type: "text" | "markdown" | "at" | "at-agent" | "link";
79
+ type: "text" | "markdown" | "at" | "at-agent" | "link" | "image";
77
80
  content: string;
78
81
  };
79
82
 
83
+ /** Outbound reply/quote context for group messages */
84
+ export type InfoflowOutboundReply = {
85
+ /** Message ID of the message being replied to (string to preserve large integer precision) */
86
+ messageid: string;
87
+ /** Preview text of the quoted message */
88
+ preview?: string;
89
+ /** "1" = reply (default), "2" = quote */
90
+ replytype?: "1" | "2";
91
+ };
92
+
80
93
  // ---------------------------------------------------------------------------
81
94
  // Account configuration
82
95
  // ---------------------------------------------------------------------------
@@ -105,6 +118,8 @@ export type InfoflowAccountConfig = {
105
118
  followUp?: boolean;
106
119
  /** Follow-up window in seconds after last bot reply (default: 300) */
107
120
  followUpWindow?: number;
121
+ /** 如流企业后台的应用ID(私聊消息撤回依赖此字段) */
122
+ appAgentId?: number;
108
123
  /** Per-group configuration overrides, keyed by group ID */
109
124
  groups?: Record<string, InfoflowGroupConfig>;
110
125
  accounts?: Record<string, InfoflowAccountConfig>;
@@ -140,6 +155,8 @@ export type ResolvedInfoflowAccount = {
140
155
  followUp?: boolean;
141
156
  /** Follow-up window in seconds after last bot reply (default: 300) */
142
157
  followUpWindow?: number;
158
+ /** 如流企业后台的应用ID(私聊消息撤回依赖此字段) */
159
+ appAgentId?: number;
143
160
  /** Per-group configuration overrides, keyed by group ID */
144
161
  groups?: Record<string, InfoflowGroupConfig>;
145
162
  };
@@ -169,6 +186,8 @@ export type InfoflowMessageEvent = {
169
186
  mentionIds?: InfoflowMentionIds;
170
187
  /** Reply/quote context extracted from replyData body items (supports multiple quotes) */
171
188
  replyContext?: string[];
189
+ /** Image download URLs extracted from IMAGE body items (group) or PicUrl (private) */
190
+ imageUrls?: string[];
172
191
  };
173
192
 
174
193
  // ---------------------------------------------------------------------------