@zhin.js/core 1.0.25 → 1.0.26
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/CHANGELOG.md +10 -0
- package/README.md +84 -342
- package/lib/adapter.d.ts +17 -0
- package/lib/adapter.d.ts.map +1 -1
- package/lib/adapter.js +84 -2
- package/lib/adapter.js.map +1 -1
- package/lib/ai/agent.d.ts +126 -0
- package/lib/ai/agent.d.ts.map +1 -0
- package/lib/ai/agent.js +645 -0
- package/lib/ai/agent.js.map +1 -0
- package/lib/ai/context-manager.d.ts +213 -0
- package/lib/ai/context-manager.d.ts.map +1 -0
- package/lib/ai/context-manager.js +313 -0
- package/lib/ai/context-manager.js.map +1 -0
- package/lib/ai/conversation-memory.d.ts +181 -0
- package/lib/ai/conversation-memory.d.ts.map +1 -0
- package/lib/ai/conversation-memory.js +581 -0
- package/lib/ai/conversation-memory.js.map +1 -0
- package/lib/ai/follow-up.d.ts +131 -0
- package/lib/ai/follow-up.d.ts.map +1 -0
- package/lib/ai/follow-up.js +265 -0
- package/lib/ai/follow-up.js.map +1 -0
- package/lib/ai/index.d.ts +29 -0
- package/lib/ai/index.d.ts.map +1 -0
- package/lib/ai/index.js +34 -0
- package/lib/ai/index.js.map +1 -0
- package/lib/ai/init.d.ts +30 -0
- package/lib/ai/init.d.ts.map +1 -0
- package/lib/ai/init.js +424 -0
- package/lib/ai/init.js.map +1 -0
- package/lib/ai/output.d.ts +93 -0
- package/lib/ai/output.d.ts.map +1 -0
- package/lib/ai/output.js +176 -0
- package/lib/ai/output.js.map +1 -0
- package/lib/ai/providers/anthropic.d.ts +23 -0
- package/lib/ai/providers/anthropic.d.ts.map +1 -0
- package/lib/ai/providers/anthropic.js +322 -0
- package/lib/ai/providers/anthropic.js.map +1 -0
- package/lib/ai/providers/base.d.ts +43 -0
- package/lib/ai/providers/base.d.ts.map +1 -0
- package/lib/ai/providers/base.js +135 -0
- package/lib/ai/providers/base.js.map +1 -0
- package/lib/ai/providers/index.d.ts +12 -0
- package/lib/ai/providers/index.d.ts.map +1 -0
- package/lib/ai/providers/index.js +9 -0
- package/lib/ai/providers/index.js.map +1 -0
- package/lib/ai/providers/ollama.d.ts +25 -0
- package/lib/ai/providers/ollama.d.ts.map +1 -0
- package/lib/ai/providers/ollama.js +243 -0
- package/lib/ai/providers/ollama.js.map +1 -0
- package/lib/ai/providers/openai.d.ts +46 -0
- package/lib/ai/providers/openai.d.ts.map +1 -0
- package/lib/ai/providers/openai.js +132 -0
- package/lib/ai/providers/openai.js.map +1 -0
- package/lib/ai/rate-limiter.d.ts +38 -0
- package/lib/ai/rate-limiter.d.ts.map +1 -0
- package/lib/ai/rate-limiter.js +86 -0
- package/lib/ai/rate-limiter.js.map +1 -0
- package/lib/ai/service.d.ts +81 -0
- package/lib/ai/service.d.ts.map +1 -0
- package/lib/ai/service.js +274 -0
- package/lib/ai/service.js.map +1 -0
- package/lib/ai/session.d.ts +186 -0
- package/lib/ai/session.d.ts.map +1 -0
- package/lib/ai/session.js +443 -0
- package/lib/ai/session.js.map +1 -0
- package/lib/ai/tone-detector.d.ts +19 -0
- package/lib/ai/tone-detector.d.ts.map +1 -0
- package/lib/ai/tone-detector.js +72 -0
- package/lib/ai/tone-detector.js.map +1 -0
- package/lib/ai/tools.d.ts +45 -0
- package/lib/ai/tools.d.ts.map +1 -0
- package/lib/ai/tools.js +206 -0
- package/lib/ai/tools.js.map +1 -0
- package/lib/ai/types.d.ts +264 -0
- package/lib/ai/types.d.ts.map +1 -0
- package/lib/ai/types.js +6 -0
- package/lib/ai/types.js.map +1 -0
- package/lib/ai/user-profile.d.ts +56 -0
- package/lib/ai/user-profile.d.ts.map +1 -0
- package/lib/ai/user-profile.js +130 -0
- package/lib/ai/user-profile.js.map +1 -0
- package/lib/ai/zhin-agent.d.ts +165 -0
- package/lib/ai/zhin-agent.d.ts.map +1 -0
- package/lib/ai/zhin-agent.js +707 -0
- package/lib/ai/zhin-agent.js.map +1 -0
- package/lib/built/ai-trigger.d.ts.map +1 -1
- package/lib/built/ai-trigger.js +7 -3
- package/lib/built/ai-trigger.js.map +1 -1
- package/lib/built/command.d.ts +33 -17
- package/lib/built/command.d.ts.map +1 -1
- package/lib/built/command.js +71 -44
- package/lib/built/command.js.map +1 -1
- package/lib/built/component.d.ts +42 -15
- package/lib/built/component.d.ts.map +1 -1
- package/lib/built/component.js +84 -52
- package/lib/built/component.js.map +1 -1
- package/lib/built/config.d.ts +54 -5
- package/lib/built/config.d.ts.map +1 -1
- package/lib/built/config.js +76 -10
- package/lib/built/config.js.map +1 -1
- package/lib/built/cron.d.ts +41 -18
- package/lib/built/cron.d.ts.map +1 -1
- package/lib/built/cron.js +106 -63
- package/lib/built/cron.js.map +1 -1
- package/lib/built/database.d.ts +55 -6
- package/lib/built/database.d.ts.map +1 -1
- package/lib/built/database.js +93 -22
- package/lib/built/database.js.map +1 -1
- package/lib/built/dispatcher.d.ts +118 -0
- package/lib/built/dispatcher.d.ts.map +1 -0
- package/lib/built/dispatcher.js +196 -0
- package/lib/built/dispatcher.js.map +1 -0
- package/lib/built/permission.d.ts +45 -5
- package/lib/built/permission.d.ts.map +1 -1
- package/lib/built/permission.js +56 -11
- package/lib/built/permission.js.map +1 -1
- package/lib/built/skill.d.ts +117 -0
- package/lib/built/skill.d.ts.map +1 -0
- package/lib/built/skill.js +191 -0
- package/lib/built/skill.js.map +1 -0
- package/lib/built/tool.d.ts +71 -164
- package/lib/built/tool.d.ts.map +1 -1
- package/lib/built/tool.js +212 -297
- package/lib/built/tool.js.map +1 -1
- package/lib/feature.d.ts +75 -0
- package/lib/feature.d.ts.map +1 -0
- package/lib/feature.js +69 -0
- package/lib/feature.js.map +1 -0
- package/lib/index.d.ts +4 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +7 -0
- package/lib/index.js.map +1 -1
- package/lib/plugin.d.ts +25 -17
- package/lib/plugin.d.ts.map +1 -1
- package/lib/plugin.js +180 -20
- package/lib/plugin.js.map +1 -1
- package/lib/types.d.ts +4 -9
- package/lib/types.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/adapter.ts +101 -2
- package/src/ai/agent.ts +772 -0
- package/src/ai/context-manager.ts +440 -0
- package/src/ai/conversation-memory.ts +774 -0
- package/src/ai/follow-up.ts +357 -0
- package/src/ai/index.ts +128 -0
- package/src/ai/init.ts +502 -0
- package/src/ai/output.ts +261 -0
- package/src/ai/providers/anthropic.ts +375 -0
- package/src/ai/providers/base.ts +173 -0
- package/src/ai/providers/index.ts +13 -0
- package/src/ai/providers/ollama.ts +292 -0
- package/src/ai/providers/openai.ts +167 -0
- package/src/ai/rate-limiter.ts +129 -0
- package/src/ai/service.ts +319 -0
- package/src/ai/session.ts +544 -0
- package/src/ai/tone-detector.ts +89 -0
- package/src/ai/tools.ts +218 -0
- package/src/ai/types.ts +296 -0
- package/src/ai/user-profile.ts +181 -0
- package/src/ai/zhin-agent.ts +845 -0
- package/src/built/ai-trigger.ts +6 -3
- package/src/built/command.ts +75 -69
- package/src/built/component.ts +94 -76
- package/src/built/config.ts +238 -128
- package/src/built/cron.ts +117 -101
- package/src/built/database.ts +128 -33
- package/src/built/dispatcher.ts +332 -0
- package/src/built/permission.ts +146 -54
- package/src/built/skill.ts +280 -0
- package/src/built/tool.ts +245 -366
- package/src/feature.ts +113 -0
- package/src/index.ts +7 -0
- package/src/plugin.ts +198 -33
- package/src/types.ts +6 -10
- package/tests/adapter.test.ts +153 -1
- package/tests/ai/agent.test.ts +614 -0
- package/tests/ai/ai-trigger.test.ts +368 -0
- package/tests/ai/context-manager.test.ts +413 -0
- package/tests/ai/conversation-memory.test.ts +128 -0
- package/tests/ai/follow-up.test.ts +175 -0
- package/tests/ai/integration.test.ts +584 -0
- package/tests/ai/output.test.ts +128 -0
- package/tests/ai/providers.integration.test.ts +227 -0
- package/tests/ai/rate-limiter.test.ts +108 -0
- package/tests/ai/session.test.ts +375 -0
- package/tests/ai/setup.ts +308 -0
- package/tests/ai/tone-detector.test.ts +80 -0
- package/tests/ai/tool.test.ts +800 -0
- package/tests/ai/tools-builtin.test.ts +346 -0
- package/tests/ai/user-profile.test.ts +73 -0
- package/tests/ai/zhin-agent.test.ts +177 -0
- package/tests/config.test.ts +46 -0
- package/tests/cron.test.ts +94 -5
- package/tests/dispatcher.test.ts +146 -0
- package/tests/feature.test.ts +145 -0
- package/tests/features-builtin.test.ts +191 -0
- package/tests/plugin.test.ts +88 -14
- package/tests/skill-feature.test.ts +179 -0
- package/tests/tool-feature.test.ts +254 -0
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FollowUpStore — 定时跟进任务的持久化存储
|
|
3
|
+
*
|
|
4
|
+
* 解决纯 setTimeout 重启即丢失的问题:
|
|
5
|
+
* 1. 创建任务时同步写入数据库
|
|
6
|
+
* 2. 执行完成 / 过期后从数据库中删除
|
|
7
|
+
* 3. 机器人启动时从数据库加载所有未完成任务,重新挂定时器
|
|
8
|
+
* 4. 同一会话创建新任务时,自动取消旧的 pending 任务(防止重复提醒)
|
|
9
|
+
*
|
|
10
|
+
* ai_followups 表:
|
|
11
|
+
* ┌──────────────────────────────────────────────────────────────────┐
|
|
12
|
+
* │ id (PK) | session_id | platform | sender_id | scene_id │
|
|
13
|
+
* │ | message | fire_at | created_at | status │
|
|
14
|
+
* └──────────────────────────────────────────────────────────────────┘
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { Logger } from '@zhin.js/logger';
|
|
18
|
+
|
|
19
|
+
const logger = new Logger(null, 'FollowUp');
|
|
20
|
+
|
|
21
|
+
// ============================================================================
|
|
22
|
+
// 数据库模型
|
|
23
|
+
// ============================================================================
|
|
24
|
+
|
|
25
|
+
export const AI_FOLLOWUP_MODEL = {
|
|
26
|
+
session_id: { type: 'text' as const, nullable: false },
|
|
27
|
+
platform: { type: 'text' as const, nullable: false },
|
|
28
|
+
bot_id: { type: 'text' as const, nullable: false },
|
|
29
|
+
sender_id: { type: 'text' as const, nullable: false },
|
|
30
|
+
scene_id: { type: 'text' as const, nullable: false },
|
|
31
|
+
scene_type: { type: 'text' as const, nullable: false },
|
|
32
|
+
message: { type: 'text' as const, nullable: false },
|
|
33
|
+
/** 触发时间戳 (ms) */
|
|
34
|
+
fire_at: { type: 'integer' as const, nullable: false },
|
|
35
|
+
created_at: { type: 'integer' as const, default: 0 },
|
|
36
|
+
/** pending | fired | cancelled */
|
|
37
|
+
status: { type: 'text' as const, default: 'pending' },
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// ============================================================================
|
|
41
|
+
// 类型
|
|
42
|
+
// ============================================================================
|
|
43
|
+
|
|
44
|
+
export interface FollowUpRecord {
|
|
45
|
+
id?: number;
|
|
46
|
+
session_id: string;
|
|
47
|
+
platform: string;
|
|
48
|
+
bot_id: string;
|
|
49
|
+
sender_id: string;
|
|
50
|
+
scene_id: string;
|
|
51
|
+
scene_type: string;
|
|
52
|
+
message: string;
|
|
53
|
+
fire_at: number;
|
|
54
|
+
created_at: number;
|
|
55
|
+
status: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 数据库模型接口(与 RelatedModel 的链式查询 API 对齐)
|
|
60
|
+
*/
|
|
61
|
+
interface DbModel {
|
|
62
|
+
select(...fields: string[]): any; // 返回 Selection (thenable, 支持 .where())
|
|
63
|
+
create(data: Record<string, any>): Promise<any>;
|
|
64
|
+
update(data: Partial<any>): any; // 返回 Updation (thenable, 支持 .where())
|
|
65
|
+
delete(condition: Record<string, any>): any; // 返回 Deletion (thenable, 支持 .where())
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 发送提醒的回调函数
|
|
70
|
+
*
|
|
71
|
+
* 由 ZhinAgent 在 init 阶段注入,负责把提醒消息发到正确的会话。
|
|
72
|
+
*/
|
|
73
|
+
export type FollowUpSender = (record: FollowUpRecord) => Promise<void>;
|
|
74
|
+
|
|
75
|
+
// ============================================================================
|
|
76
|
+
// Store 接口
|
|
77
|
+
// ============================================================================
|
|
78
|
+
|
|
79
|
+
interface IFollowUpStore {
|
|
80
|
+
create(record: Omit<FollowUpRecord, 'id'>): Promise<FollowUpRecord>;
|
|
81
|
+
markFired(id: number): Promise<void>;
|
|
82
|
+
cancel(id: number): Promise<void>;
|
|
83
|
+
getPending(): Promise<FollowUpRecord[]>;
|
|
84
|
+
getPendingBySession(sessionId: string): Promise<FollowUpRecord[]>;
|
|
85
|
+
dispose(): void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ============================================================================
|
|
89
|
+
// 内存实现
|
|
90
|
+
// ============================================================================
|
|
91
|
+
|
|
92
|
+
class MemoryFollowUpStore implements IFollowUpStore {
|
|
93
|
+
private records: FollowUpRecord[] = [];
|
|
94
|
+
private nextId = 1;
|
|
95
|
+
|
|
96
|
+
async create(record: Omit<FollowUpRecord, 'id'>): Promise<FollowUpRecord> {
|
|
97
|
+
const full: FollowUpRecord = { ...record, id: this.nextId++ };
|
|
98
|
+
this.records.push(full);
|
|
99
|
+
return full;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async markFired(id: number): Promise<void> {
|
|
103
|
+
const r = this.records.find(r => r.id === id);
|
|
104
|
+
if (r) r.status = 'fired';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async cancel(id: number): Promise<void> {
|
|
108
|
+
const r = this.records.find(r => r.id === id);
|
|
109
|
+
if (r) r.status = 'cancelled';
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async getPending(): Promise<FollowUpRecord[]> {
|
|
113
|
+
return this.records.filter(r => r.status === 'pending');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async getPendingBySession(sessionId: string): Promise<FollowUpRecord[]> {
|
|
117
|
+
return this.records.filter(r => r.status === 'pending' && r.session_id === sessionId);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
dispose(): void {
|
|
121
|
+
this.records = [];
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ============================================================================
|
|
126
|
+
// 数据库实现
|
|
127
|
+
// ============================================================================
|
|
128
|
+
|
|
129
|
+
class DatabaseFollowUpStore implements IFollowUpStore {
|
|
130
|
+
constructor(private model: DbModel) {}
|
|
131
|
+
|
|
132
|
+
async create(record: Omit<FollowUpRecord, 'id'>): Promise<FollowUpRecord> {
|
|
133
|
+
const created = await this.model.create(record);
|
|
134
|
+
return { ...record, id: created.id ?? created };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async markFired(id: number): Promise<void> {
|
|
138
|
+
await this.model.update({ status: 'fired' }).where({ id });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async cancel(id: number): Promise<void> {
|
|
142
|
+
await this.model.update({ status: 'cancelled' }).where({ id });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async getPending(): Promise<FollowUpRecord[]> {
|
|
146
|
+
return this.model.select().where({ status: 'pending' }) as Promise<FollowUpRecord[]>;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async getPendingBySession(sessionId: string): Promise<FollowUpRecord[]> {
|
|
150
|
+
return this.model.select().where({ status: 'pending', session_id: sessionId }) as Promise<FollowUpRecord[]>;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
dispose(): void {}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ============================================================================
|
|
157
|
+
// FollowUpManager
|
|
158
|
+
// ============================================================================
|
|
159
|
+
|
|
160
|
+
export class FollowUpManager {
|
|
161
|
+
private store: IFollowUpStore;
|
|
162
|
+
/** 内存中活跃的定时器: recordId → timer */
|
|
163
|
+
private timers: Map<number, ReturnType<typeof setTimeout>> = new Map();
|
|
164
|
+
private sender: FollowUpSender | null = null;
|
|
165
|
+
|
|
166
|
+
constructor() {
|
|
167
|
+
this.store = new MemoryFollowUpStore();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 注入消息发送回调 */
|
|
171
|
+
setSender(sender: FollowUpSender): void {
|
|
172
|
+
this.sender = sender;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** 升级到数据库存储 */
|
|
176
|
+
upgradeToDatabase(model: DbModel): void {
|
|
177
|
+
const old = this.store;
|
|
178
|
+
this.store = new DatabaseFollowUpStore(model);
|
|
179
|
+
old.dispose();
|
|
180
|
+
logger.debug('FollowUpManager: 已升级到数据库存储');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 创建一个跟进任务
|
|
185
|
+
*
|
|
186
|
+
* 重要:同一会话的旧 pending 任务会被自动取消,防止重复提醒。
|
|
187
|
+
*
|
|
188
|
+
* @returns 人类可读的确认文本
|
|
189
|
+
*/
|
|
190
|
+
async schedule(params: {
|
|
191
|
+
sessionId: string;
|
|
192
|
+
platform: string;
|
|
193
|
+
botId: string;
|
|
194
|
+
senderId: string;
|
|
195
|
+
sceneId: string;
|
|
196
|
+
sceneType: string;
|
|
197
|
+
message: string;
|
|
198
|
+
delayMinutes: number;
|
|
199
|
+
}): Promise<string> {
|
|
200
|
+
const { sessionId, platform, botId, senderId, sceneId, sceneType, message, delayMinutes } = params;
|
|
201
|
+
|
|
202
|
+
// ── 详细参数日志(方便排查问题) ──
|
|
203
|
+
logger.debug(`[跟进] 收到请求: delay_minutes=${delayMinutes}, message="${message}", session=${sessionId}`);
|
|
204
|
+
|
|
205
|
+
// 限制最大延迟 7 天
|
|
206
|
+
const maxDelay = 7 * 24 * 60;
|
|
207
|
+
const actualDelay = Math.min(Math.max(delayMinutes, 1), maxDelay);
|
|
208
|
+
const delayMs = actualDelay * 60 * 1000;
|
|
209
|
+
const fireAt = Date.now() + delayMs;
|
|
210
|
+
|
|
211
|
+
// ── 自动取消同一会话的旧 pending 任务 ──
|
|
212
|
+
const existingPending = await this.store.getPendingBySession(sessionId);
|
|
213
|
+
if (existingPending.length > 0) {
|
|
214
|
+
for (const old of existingPending) {
|
|
215
|
+
if (old.id != null) {
|
|
216
|
+
// 取消数据库记录
|
|
217
|
+
await this.store.cancel(old.id);
|
|
218
|
+
// 清除内存中的定时器
|
|
219
|
+
const timer = this.timers.get(old.id);
|
|
220
|
+
if (timer) {
|
|
221
|
+
clearTimeout(timer);
|
|
222
|
+
this.timers.delete(old.id);
|
|
223
|
+
}
|
|
224
|
+
logger.debug(`[跟进] 自动取消旧任务: id=${old.id}, "${old.message}"`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const record = await this.store.create({
|
|
230
|
+
session_id: sessionId,
|
|
231
|
+
platform,
|
|
232
|
+
bot_id: botId,
|
|
233
|
+
sender_id: senderId,
|
|
234
|
+
scene_id: sceneId,
|
|
235
|
+
scene_type: sceneType,
|
|
236
|
+
message,
|
|
237
|
+
fire_at: fireAt,
|
|
238
|
+
created_at: Date.now(),
|
|
239
|
+
status: 'pending',
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// 挂定时器
|
|
243
|
+
this.scheduleTimer(record);
|
|
244
|
+
|
|
245
|
+
const readableTime = actualDelay >= 1440
|
|
246
|
+
? `${(actualDelay / 1440).toFixed(1)} 天后`
|
|
247
|
+
: actualDelay >= 60
|
|
248
|
+
? `${(actualDelay / 60).toFixed(1)} 小时后`
|
|
249
|
+
: `${actualDelay} 分钟后`;
|
|
250
|
+
|
|
251
|
+
// 精确触发时间(方便日志对照)
|
|
252
|
+
const fireDate = new Date(fireAt);
|
|
253
|
+
const fireTimeStr = fireDate.toLocaleString('zh-CN', { hour12: false });
|
|
254
|
+
|
|
255
|
+
logger.debug(`[跟进] 已创建: id=${record.id}, delay=${actualDelay}分钟(${delayMs}ms), 触发时间=${fireTimeStr}, "${message}"`);
|
|
256
|
+
return `✅ 已安排提醒,将在 ${readableTime}(${fireTimeStr})提醒你:${message}`;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* 取消指定会话的所有 pending 任务
|
|
261
|
+
*/
|
|
262
|
+
async cancelBySession(sessionId: string): Promise<number> {
|
|
263
|
+
const pending = await this.store.getPendingBySession(sessionId);
|
|
264
|
+
let count = 0;
|
|
265
|
+
for (const record of pending) {
|
|
266
|
+
if (record.id != null) {
|
|
267
|
+
await this.store.cancel(record.id);
|
|
268
|
+
const timer = this.timers.get(record.id);
|
|
269
|
+
if (timer) {
|
|
270
|
+
clearTimeout(timer);
|
|
271
|
+
this.timers.delete(record.id);
|
|
272
|
+
}
|
|
273
|
+
count++;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (count > 0) {
|
|
277
|
+
logger.debug(`[跟进] 已取消 ${count} 个待执行任务 (session=${sessionId})`);
|
|
278
|
+
}
|
|
279
|
+
return count;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* 启动时从数据库恢复所有未完成的跟进任务
|
|
284
|
+
*/
|
|
285
|
+
async restore(): Promise<number> {
|
|
286
|
+
const pending = await this.store.getPending();
|
|
287
|
+
const now = Date.now();
|
|
288
|
+
let restored = 0;
|
|
289
|
+
|
|
290
|
+
for (const record of pending) {
|
|
291
|
+
if (record.fire_at <= now) {
|
|
292
|
+
// 已过期但未执行 → 立即触发(延迟 2 秒,等系统完全就绪)
|
|
293
|
+
const overdueSec = Math.round((now - record.fire_at) / 1000);
|
|
294
|
+
logger.debug(`[跟进恢复] id=${record.id} 已过期 ${overdueSec}s,立即触发`);
|
|
295
|
+
this.scheduleTimerWithDelay(record, 2000);
|
|
296
|
+
restored++;
|
|
297
|
+
} else {
|
|
298
|
+
// 还没到时间 → 重新挂定时器
|
|
299
|
+
this.scheduleTimer(record);
|
|
300
|
+
const remainMs = record.fire_at - now;
|
|
301
|
+
const remainMin = (remainMs / 60_000).toFixed(1);
|
|
302
|
+
logger.debug(`[跟进恢复] id=${record.id} 剩余 ${remainMin} 分钟, "${record.message}"`);
|
|
303
|
+
restored++;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (restored > 0) {
|
|
308
|
+
logger.info(`[跟进恢复] 共恢复 ${restored} 个待执行任务`);
|
|
309
|
+
}
|
|
310
|
+
return restored;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* 为一条记录挂定时器
|
|
315
|
+
*/
|
|
316
|
+
private scheduleTimer(record: FollowUpRecord): void {
|
|
317
|
+
const delay = Math.max(record.fire_at - Date.now(), 0);
|
|
318
|
+
this.scheduleTimerWithDelay(record, delay);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private scheduleTimerWithDelay(record: FollowUpRecord, delayMs: number): void {
|
|
322
|
+
if (!record.id) return;
|
|
323
|
+
|
|
324
|
+
// 清除旧定时器(如果有)
|
|
325
|
+
const existing = this.timers.get(record.id);
|
|
326
|
+
if (existing) clearTimeout(existing);
|
|
327
|
+
|
|
328
|
+
const timer = setTimeout(async () => {
|
|
329
|
+
try {
|
|
330
|
+
this.timers.delete(record.id!);
|
|
331
|
+
|
|
332
|
+
// 发送提醒
|
|
333
|
+
if (this.sender) {
|
|
334
|
+
await this.sender(record);
|
|
335
|
+
logger.info(`[跟进提醒] 已发送: id=${record.id}, "${record.message}"`);
|
|
336
|
+
} else {
|
|
337
|
+
logger.warn(`[跟进提醒] 无法发送 (sender 未注入): id=${record.id}`);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// 标记完成
|
|
341
|
+
await this.store.markFired(record.id!);
|
|
342
|
+
} catch (e) {
|
|
343
|
+
logger.warn(`[跟进提醒] 发送失败: id=${record.id}`, e);
|
|
344
|
+
}
|
|
345
|
+
}, delayMs);
|
|
346
|
+
|
|
347
|
+
this.timers.set(record.id, timer);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
dispose(): void {
|
|
351
|
+
for (const timer of this.timers.values()) {
|
|
352
|
+
clearTimeout(timer);
|
|
353
|
+
}
|
|
354
|
+
this.timers.clear();
|
|
355
|
+
this.store.dispose();
|
|
356
|
+
}
|
|
357
|
+
}
|
package/src/ai/index.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zhin.js/core — AI 模块
|
|
3
|
+
*
|
|
4
|
+
* 原 @zhin.js/ai 包已合并至此,所有 AI 能力内置在 core 中。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
// ── 类型定义 ──
|
|
8
|
+
export type {
|
|
9
|
+
AIConfig,
|
|
10
|
+
AIProvider,
|
|
11
|
+
ProviderConfig,
|
|
12
|
+
ChatMessage,
|
|
13
|
+
ChatCompletionRequest,
|
|
14
|
+
ChatCompletionResponse,
|
|
15
|
+
ChatCompletionChunk,
|
|
16
|
+
ContentPart,
|
|
17
|
+
// 注意:ToolDefinition 已从 core/types.ts 导出,此处不重复导出
|
|
18
|
+
ToolCall,
|
|
19
|
+
MessageRole,
|
|
20
|
+
AgentTool,
|
|
21
|
+
AgentConfig,
|
|
22
|
+
AgentResult,
|
|
23
|
+
} from './types.js';
|
|
24
|
+
|
|
25
|
+
// ── AI Service ──
|
|
26
|
+
export { AIService } from './service.js';
|
|
27
|
+
|
|
28
|
+
// ── Agent ──
|
|
29
|
+
export { Agent, createAgent } from './agent.js';
|
|
30
|
+
|
|
31
|
+
// ── Session ──
|
|
32
|
+
export {
|
|
33
|
+
SessionManager,
|
|
34
|
+
createMemorySessionManager,
|
|
35
|
+
createDatabaseSessionManager,
|
|
36
|
+
AI_SESSION_MODEL,
|
|
37
|
+
} from './session.js';
|
|
38
|
+
|
|
39
|
+
// ── Context Manager ──
|
|
40
|
+
export {
|
|
41
|
+
createContextManager,
|
|
42
|
+
CHAT_MESSAGE_MODEL,
|
|
43
|
+
CONTEXT_SUMMARY_MODEL,
|
|
44
|
+
} from './context-manager.js';
|
|
45
|
+
export type {
|
|
46
|
+
ContextManager,
|
|
47
|
+
ContextConfig,
|
|
48
|
+
MessageRecord,
|
|
49
|
+
} from './context-manager.js';
|
|
50
|
+
|
|
51
|
+
// ── ZhinAgent ──
|
|
52
|
+
export { ZhinAgent } from './zhin-agent.js';
|
|
53
|
+
export type { ZhinAgentConfig, OnChunkCallback } from './zhin-agent.js';
|
|
54
|
+
|
|
55
|
+
// ── Conversation Memory ──
|
|
56
|
+
export {
|
|
57
|
+
ConversationMemory,
|
|
58
|
+
AI_MESSAGE_MODEL,
|
|
59
|
+
AI_SUMMARY_MODEL,
|
|
60
|
+
} from './conversation-memory.js';
|
|
61
|
+
export type { ConversationMemoryConfig } from './conversation-memory.js';
|
|
62
|
+
|
|
63
|
+
// ── User Profile ──
|
|
64
|
+
export {
|
|
65
|
+
UserProfileStore,
|
|
66
|
+
AI_USER_PROFILE_MODEL,
|
|
67
|
+
} from './user-profile.js';
|
|
68
|
+
|
|
69
|
+
// ── Rate Limiter ──
|
|
70
|
+
export { RateLimiter } from './rate-limiter.js';
|
|
71
|
+
export type { RateLimitConfig, RateLimitResult } from './rate-limiter.js';
|
|
72
|
+
|
|
73
|
+
// ── Follow-Up ──
|
|
74
|
+
export { FollowUpManager, AI_FOLLOWUP_MODEL } from './follow-up.js';
|
|
75
|
+
export type { FollowUpRecord, FollowUpSender } from './follow-up.js';
|
|
76
|
+
|
|
77
|
+
// ── Tone Detector ──
|
|
78
|
+
export { detectTone } from './tone-detector.js';
|
|
79
|
+
export type { Tone } from './tone-detector.js';
|
|
80
|
+
|
|
81
|
+
// ── 多模态输出 ──
|
|
82
|
+
export {
|
|
83
|
+
parseOutput,
|
|
84
|
+
renderToPlainText,
|
|
85
|
+
renderToSatori,
|
|
86
|
+
} from './output.js';
|
|
87
|
+
export type {
|
|
88
|
+
OutputElement,
|
|
89
|
+
TextElement,
|
|
90
|
+
ImageElement,
|
|
91
|
+
AudioElement,
|
|
92
|
+
VideoElement,
|
|
93
|
+
CardElement,
|
|
94
|
+
FileElement,
|
|
95
|
+
CardField,
|
|
96
|
+
CardButton,
|
|
97
|
+
} from './output.js';
|
|
98
|
+
|
|
99
|
+
// ── 内置工具 ──
|
|
100
|
+
export {
|
|
101
|
+
calculatorTool,
|
|
102
|
+
timeTool,
|
|
103
|
+
searchTool,
|
|
104
|
+
codeRunnerTool,
|
|
105
|
+
httpTool,
|
|
106
|
+
memoryTool,
|
|
107
|
+
getBuiltinTools,
|
|
108
|
+
getAllBuiltinTools,
|
|
109
|
+
} from './tools.js';
|
|
110
|
+
|
|
111
|
+
// ── Providers ──
|
|
112
|
+
export {
|
|
113
|
+
BaseProvider,
|
|
114
|
+
OpenAIProvider,
|
|
115
|
+
DeepSeekProvider,
|
|
116
|
+
MoonshotProvider,
|
|
117
|
+
ZhipuProvider,
|
|
118
|
+
AnthropicProvider,
|
|
119
|
+
OllamaProvider,
|
|
120
|
+
} from './providers/index.js';
|
|
121
|
+
export type {
|
|
122
|
+
OpenAIConfig,
|
|
123
|
+
AnthropicConfig,
|
|
124
|
+
OllamaConfig,
|
|
125
|
+
} from './providers/index.js';
|
|
126
|
+
|
|
127
|
+
// ── 初始化 ──
|
|
128
|
+
export { initAIModule } from './init.js';
|