Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1729 lines (1494 loc) · 62.1 KB
/
Copy pathserver.js
File metadata and controls
1729 lines (1494 loc) · 62.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 统一 AI CLI 连接器服务器
*
* 支持多个 AI CLI 工具:
* - Claude Code
* - IFlow
*
* 功能:
* - Web API 接口
* - 钉钉机器人集成
* - 流式事件处理
* - 会话管理
*/
// 首先加载环境变量(覆盖已存在的环境变量)
require('dotenv').config({ override: true })
const express = require('express')
const config = require('./utils/config')
const Logger = require('./integrations/logger')
const AuditLogger = require('./integrations/audit-logger')
const RobotEventFormatter = require('./integrations/robot-event-formatter')
const RobotDedup = require('./integrations/robot-dedup')
const DingTalkIntegration = require('./integrations/dingtalk')
const QQBotIntegration = require('./integrations/qqbot')
const ClaudeConnector = require('./connectors/claude-connector')
const IFlowConnector = require('./connectors/iflow-connector')
const CodexConnector = require('./connectors/codex-connector')
const AgentConnector = require('./connectors/agent-connector')
const SchedulerModule = require('./scheduler')
const SessionScanner = require('./utils/session-scanner')
const { parseCommand } = require('./server/commands')
const { dispatchCommand } = require('./server/command-dispatcher')
const { setupHttpRoutes } = require('./server/http-routes')
class UnifiedServer {
constructor() {
this.config = config
this.app = express()
this.logger = new Logger(config.logging)
this.dingtalk = new DingTalkIntegration(config.dingtalk, this.logger)
this.qqbot = new QQBotIntegration(config.qqbot, this.logger)
// 多模型支持
this.connectors = new Map() // 'claude' | 'iflow' -> connector instance
this.defaultProvider = config.provider
// 定时任务模块
this.scheduler = null
this.auditLogger = AuditLogger
this.robotFormatter = new RobotEventFormatter({ maxChars: config.robotStream?.maxChars || 1200 })
this.robotDedup = new RobotDedup(config.robotStream?.dedupWindowMs || 5000)
// 会话管理
this.sessionScanner = new SessionScanner(this.logger)
this._setupMiddleware()
this._setupRoutes()
}
_setupMiddleware() {
// 基础中间件配置
this.app.use(express.json({ limit: '10mb' }))
this.app.use(express.urlencoded({ extended: true, limit: '10mb' }))
}
_setupRoutes() {
setupHttpRoutes(this)
}
async _initializeAllConnectors() {
const availableProviders = []
const errors = []
// 并行初始化任务列表
const initTasks = []
// 准备 Claude 初始化任务
if (config.claude.cmdPath && config.claude.workDir) {
initTasks.push(this._initConnector('claude', ClaudeConnector))
}
// 准备 IFlow 初始化任务
if (config.iflow.workDir) {
initTasks.push(this._initConnector('iflow', IFlowConnector))
}
// 准备 Codex 初始化任务
if (config.codex.workDir) {
initTasks.push(this._initConnector('codex', CodexConnector))
}
// 准备 Agent 初始化任务
if (config.agent.enabled && config.agent.apiKey) {
initTasks.push(this._initConnector('agent', AgentConnector))
}
// 并行执行所有初始化任务
if (initTasks.length > 0) {
this.logger.info('CONNECTOR', `并行初始化 ${initTasks.length} 个模型...`)
const results = await Promise.all(initTasks)
// 收集结果
results.forEach(result => {
if (result.success) {
const providerName = typeof result.provider === 'string' ? result.provider : String(result.provider)
this.connectors.set(result.provider, result.connector)
availableProviders.push(result.provider)
this.logger.success('CONNECTOR', `${providerName.toUpperCase()} 初始化成功 (版本: ${result.version || 'unknown'})`)
} else {
errors.push(result.error)
}
})
}
// 如果有错误,记录警告
if (errors.length > 0) {
this.logger.warning('CONNECTOR', '部分模型初始化失败', { errors })
}
return availableProviders
}
/**
* 通用连接器初始化方法
* @param {string} provider - 提供商名称 ('claude' | 'iflow')
* @param {class} ConnectorClass - 连接器类
* @returns {Promise<Object>} { success, provider, connector?, version?, error? }
*/
async _initConnector(provider, ConnectorClass) {
const providerName = provider.toUpperCase()
try {
this.logger.info('CONNECTOR', `正在初始化 ${providerName}...`)
const options = await config.getConnectorOptions(provider)
// Agent Connector 需要 server 实例访问定时任务
if (provider === 'agent') {
options.server = this
options.logger = this.logger
}
const connector = new ConnectorClass(options)
const result = await connector.connect()
if (result.success) {
return {
success: true,
provider,
connector,
version: result.version
}
}
return {
success: false,
error: `${providerName}: ${result.error}`
}
} catch (error) {
this.logger.warning('CONNECTOR', `${providerName} 初始化失败`, { error: error.message })
return {
success: false,
error: `${providerName}: ${error.message}`
}
}
}
// ==================== 命令处理 ====================
/**
* 解析用户命令
* 支持多词命令,使用最长匹配原则
* @param {string} content - 用户输入内容
* @returns {Object|null} 命令对象 { type, provider?, arg? }
*/
_parseCommand(content) {
return parseCommand(content, this.logger, this.config.commands)
}
async _handleCommand(command, conversationId, replyTarget, platform, originalMessage, type) {
return dispatchCommand(this, command, conversationId, replyTarget, platform, originalMessage, type)
}
async _handleSwitch(provider, conversationId, replyTarget, platform, originalMessage, type, arg = null) {
// 检查 connector 是否可用
const connector = this.connectors.get(provider)
if (!connector || !connector.connected) {
const availableProviders = Array.from(this.connectors.keys()).map(p => p.toUpperCase()).join(', ')
await platform.send(
replyTarget,
`❌ ${provider.toUpperCase()} 模型不可用\n\n💡 可用模型:${availableProviders || '无'}`,
originalMessage,
type
)
return { status: 'SUCCESS' }
}
// 中断当前任务(如果有)
const currentSession = platform.getSession(conversationId)
if (currentSession?.sessionId) {
const currentConnector = this.connectors.get(currentSession.provider)
if (currentConnector) {
currentConnector.interruptSession(currentSession.sessionId)
this.logger.info('PROVIDER', `中断旧任务: ${currentSession.sessionId}`)
}
}
// 解析参数:[-r] [自定义提示词]
let promptMode = 'append' // 默认拼接
let customPrompt = null
if (arg) {
const trimmedArg = arg.trim()
if (trimmedArg.startsWith('-r ') || trimmedArg === '-r') {
// -r 标志:替换模式
promptMode = 'replace'
customPrompt = trimmedArg.startsWith('-r ') ? trimmedArg.substring(3).trim() : null
} else {
// 无 -r 标志:拼接模式
promptMode = 'append'
customPrompt = trimmedArg
}
}
// 构建会话选项
const sessionOptions = {
...currentSession,
promptMode,
customPrompt
}
// 切换模型(清空旧 sessionId,保留设置)
platform.setSession(conversationId, null, provider, sessionOptions)
// 构建响应消息
let responseMsg = `✅ 已切换到 ${provider.toUpperCase()} 模型`
if (customPrompt) {
const modeText = promptMode === 'replace' ? '替换' : '拼接'
const previewPrompt = customPrompt.length > 50 ? customPrompt.substring(0, 50) + '...' : customPrompt
responseMsg += `\n\n📝 自定义提示词(${modeText}):\n${previewPrompt}`
}
const availableProviders = Array.from(this.connectors.keys()).map(p => p.toUpperCase()).join(', ')
responseMsg += `\n\n💡 可用模型:${availableProviders}`
await platform.send(replyTarget, responseMsg, originalMessage, type)
this.logger.info('PROVIDER', `会话 ${conversationId} 切换到 ${provider}${customPrompt ? `, promptMode=${promptMode}` : ''}`)
return { status: 'SUCCESS' }
}
async _handleInterrupt(conversationId, replyTarget, platform, originalMessage, type) {
const session = platform.getSession(conversationId)
if (!session?.sessionId) {
await platform.send(replyTarget, '⚠️ 没有运行中的任务', originalMessage, type)
return { status: 'SUCCESS' }
}
const connector = this.connectors.get(session.provider)
if (connector) {
connector.interruptSession(session.sessionId)
platform.deleteSession(conversationId)
await platform.send(replyTarget, '✅ 任务已中断', originalMessage, type)
this.logger.info('PROVIDER', `会话 ${conversationId} 任务已中断`)
} else {
await platform.send(replyTarget, '❌ 无法中断任务:模型不可用', originalMessage, type)
}
return { status: 'SUCCESS' }
}
async _handleRestart(conversationId, replyTarget, platform, originalMessage, type) {
try {
await platform.send(replyTarget, '🔄 正在重启服务,5到10秒后再试', originalMessage, type)
const { exec } = require('child_process')
// 从 ecosystem.config.js 读取应用名称,支持多实例部署
let appName = 'oprcli'
try {
const ecosystemConfig = require('./ecosystem.config.js')
appName = ecosystemConfig.apps[0]?.name || 'oprcli'
} catch (e) {
this.logger.warn('SERVER', 'Failed to read ecosystem.config.js, using default name:', e.message)
}
this.logger.info('SERVER', 'PM2 restart triggered', { appName })
// PM2 重启命令
exec(`pm2 restart ${appName}`, (error, stdout, stderr) => {
if (error) {
this.logger.error('SERVER', 'PM2 restart error:', error.message)
} else {
this.logger.info('SERVER', 'PM2 restart success:', stdout)
}
})
} catch (error) {
this.logger.error('SERVER', 'Restart failed:', error)
await platform.send(replyTarget, `❌ 重启失败: ${error.message}`, originalMessage, type)
}
return { status: 'SUCCESS' }
}
async _handleStatus(conversationId, replyTarget, platform, originalMessage, type) {
const session = platform.getSession(conversationId)
const provider = session?.provider || this.defaultProvider
const sessionId = session?.sessionId || null
const promptMode = session?.promptMode || 'append'
const customPrompt = session?.customPrompt
const availableProviders = Array.from(this.connectors.entries())
.filter(([_, conn]) => conn.connected)
.map(([p, _]) => p.toUpperCase())
.join(', ')
const status = {
当前模型: provider.toUpperCase(),
提示词模式: promptMode === 'replace' ? '替换' : '拼接',
自定义提示词: customPrompt ? (customPrompt.length > 30 ? customPrompt.substring(0, 30) + '...' : customPrompt) : '无',
会话状态: sessionId ? '运行中' : '空闲',
可用模型: availableProviders || '无'
}
const statusText = `📊 系统状态\n\n${Object.entries(status).map(([k, v]) => `• ${k}:${v}`).join('\n')}`
await platform.send(replyTarget, statusText, originalMessage, type)
return { status: 'SUCCESS' }
}
async _handleHelp(replyTarget, platform, originalMessage, type) {
const availableProviders = Array.from(this.connectors.entries())
.filter(([_, conn]) => conn.connected)
.map(([p, _]) => p.toUpperCase())
.join(', ')
const schedulerEnabled = this.scheduler?.enabled || false
const help = `📖 命令帮助
🤖 模型切换:
• claude [-r] [提示词] - 切换到 Claude 模型
• iflow [-r] [提示词] - 切换到 IFlow 模型
• codex [-r] [提示词] - 切换到 Codex 模型
参数说明:
- 无参数:使用默认提示词
- [提示词]:拼接到默认提示词后
- -r [提示词]:替换默认提示词
🛑 任务控制:
• end / 停止 / stop - 中断当前任务
📅 定时任务${schedulerEnabled ? '' : ' (未启用)'}:
• tasks - 查看任务列表
• tasks status - 查看任务状态
• tasks reload - 重载任务配置
• tasks on - 启用定时任务功能
• tasks off - 禁用定时任务功能
• tasks run <id> - 手动执行任务
• tasks enable <id> - 启用任务
• tasks disable <id> - 禁用任务
• tasks add <id> <间隔> <消息> - 创建任务
• tasks rm <id> - 删除任务
间隔格式:30s/10m/1h 或 cron 表达式
选项:--name=名称 --provider=模型 --enabled=true/false
示例:tasks add drink 30m 该喝水了 --provider=iflow
🔄 服务管理:
• rs / restart / 重启 - 远程重启服务 (PM2模式)
ℹ️ 信息查询:
• status / 状态 - 查看当前状态
• path [目录] - 查看或设置工作目录
• help / 帮助 - 显示此帮助
📋 会话管理:
• sessions / 会话 - 查看历史会话列表
• resume / 继续 - 继续上次会话或指定会话
💡 可用模型:${availableProviders || '无'}`
await platform.send(replyTarget, help.trim(), originalMessage, type)
return { status: 'SUCCESS' }
}
/**
* 处理会话列表命令
*/
async _handleSessionsList(conversationId, replyTarget, platform, originalMessage, type) {
const workDir = this._getWorkDir(conversationId, platform)
const sessions = await this.sessionScanner.scanSessions(workDir)
return this._listSessions(sessions, replyTarget, platform, originalMessage, type)
}
/**
* 处理会话恢复命令
*/
async _handleSessionsResume(arg, conversationId, replyTarget, platform, originalMessage, type) {
const workDir = this._getWorkDir(conversationId, platform)
const session = platform.getSession(conversationId)
const currentProvider = session?.provider || this.defaultProvider
const sessions = await this.sessionScanner.scanSessions(workDir)
// 过滤当前 Provider 的会话
const providerSessions = sessions.filter(s => s.provider === currentProvider)
// 无参数:继续最新会话(优先当前 Provider)
if (!arg?.trim()) {
// 优先使用当前 Provider 的会话
const targetSessions = providerSessions.length > 0 ? providerSessions : sessions
if (targetSessions.length === 0) {
await platform.send(replyTarget, '❌ 没有找到历史会话', originalMessage, type)
return { status: 'SUCCESS' }
}
return this._resumeSession(targetSessions[0], conversationId, replyTarget, platform, originalMessage, type)
}
// 有参数:优先在当前 Provider 中搜索,再全局搜索
const targetSession = providerSessions.find(s =>
s.id.startsWith(arg) ||
s.shortId?.startsWith(arg) ||
s.id.includes(arg) ||
arg === s.id
) || sessions.find(s =>
s.id.startsWith(arg) ||
s.shortId?.startsWith(arg) ||
s.id.includes(arg) ||
arg === s.id
)
if (!targetSession) {
await platform.send(
replyTarget,
`❌ 未找到会话: ${arg}\n\n💡 提示:使用 /sessions 查看所有会话`,
originalMessage,
type
)
return { status: 'SUCCESS' }
}
return this._resumeSession(targetSession, conversationId, replyTarget, platform, originalMessage, type)
}
/**
* 获取工作目录
*/
_getWorkDir(conversationId, platform) {
const session = platform.getSession(conversationId)
return session?.workDir || this.config.claude.workDir || this.config.iflow.workDir || process.cwd()
}
/**
* 列出会话
*/
async _listSessions(sessions, replyTarget, platform, originalMessage, type) {
if (sessions.length === 0) {
const message = '📭 暂无历史会话'
await platform.send(replyTarget, message, originalMessage, type)
return { status: 'SUCCESS' }
}
// 按 Provider 分组
const grouped = sessions.reduce((acc, s) => {
if (!acc[s.provider]) acc[s.provider] = []
acc[s.provider].push(s)
return acc
}, {})
// 构建消息
const lines = ['📋 历史会话列表:\n']
for (const [provider, providerSessions] of Object.entries(grouped)) {
const providerName = provider.toUpperCase()
lines.push(`📂 ${providerName} (${providerSessions.length})`)
for (const session of providerSessions.slice(0, 5)) {
const icon = session === sessions[0] ? '🔸' : '•'
const time = new Date(session.mtime).toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
const size = (session.size / 1024).toFixed(1) + 'KB'
// 优先使用 shortId(Codex),否则截取 ID 前12位
const displayId = session.shortId || session.id.substring(0, 12)
lines.push(` ${icon} [${displayId}] ${time} (${size})`)
lines.push(` └─ ${session.preview}`)
}
if (providerSessions.length > 5) {
lines.push(` ... 还有 ${providerSessions.length - 5} 个会话`)
}
lines.push('')
}
lines.push('💡 提示:')
lines.push('- 发送 /resume 继续上次会话')
lines.push('- 发送 /resume {id前几位} 继续指定会话')
const message = lines.join('\n')
await platform.send(replyTarget, message, originalMessage, type)
return { status: 'SUCCESS' }
}
/**
* 恢复指定会话
*/
async _resumeSession(session, conversationId, replyTarget, platform, originalMessage, type) {
const connector = this.connectors.get(session.provider)
if (!connector) {
await platform.send(
replyTarget,
`❌ ${session.provider} 连接器未启用`,
originalMessage,
type
)
return { status: 'SUCCESS' }
}
// 更新当前会话状态(不发送消息,避免触发新轮次)
const currentSession = platform.getSession(conversationId) || {}
const newSession = {
...currentSession,
sessionId: session.id,
provider: session.provider,
startTime: currentSession.startTime || Date.now()
}
platform.conversations.set(conversationId, newSession)
console.log(`[DEBUG] 会话已恢复:`, {
conversationId,
sessionId: session.id,
provider: session.provider,
shortId: session.shortId || session.id.substring(0, 12)
})
this.logger.success('SESSION', `✅ 会话已恢复: ${session.provider.toUpperCase()} / ${session.shortId || session.id.substring(0, 12)}`)
// 发送恢复通知
const displayId = session.shortId || session.id.substring(0, 12)
await platform.send(
replyTarget,
`✅ 已恢复 ${session.provider.toUpperCase()} 会话: ${displayId}...\n\n💡 下一条消息将发送到此会话`,
originalMessage,
type
)
return { status: 'SUCCESS' }
}
async _handlePath(pathArg, conversationId, replyTarget, platform, originalMessage, type) {
const session = platform.getSession(conversationId)
const currentProvider = session?.provider || this.defaultProvider
const currentWorkDir = session?.workDir || null
// 如果没有参数,显示当前工作目录信息
if (!pathArg) {
const actualWorkDir = config.getWorkDir(currentProvider, currentWorkDir)
const defaultWorkDir = config.getDefaultWorkDir()
const projectDir = config.getProjectDir()
const pathInfo = {
'当前工作目录': actualWorkDir,
'默认工作目录': defaultWorkDir,
'项目目录(文档路径)': projectDir,
'当前模型': currentProvider.toUpperCase()
}
const infoText = `📁 工作目录信息\n\n${Object.entries(pathInfo).map(([k, v]) => `• ${k}:\n ${v}`).join('\n')}\n\n💡 使用命令:\n/path <目录> - 设置工作目录\n/path ~ - 切换到默认工作目录\n/path reset - 重置为默认工作目录`
await platform.send(replyTarget, infoText, originalMessage, type)
return { status: 'SUCCESS' }
}
// 处理特殊参数
const trimmedPath = pathArg.trim().toLowerCase()
// 切换到默认工作目录
if (trimmedPath === '~' || trimmedPath === 'reset') {
platform.setSession(conversationId, session?.sessionId || null, currentProvider, {
...session,
workDir: null // 清除会话级别的工作目录设置,使用默认配置
})
const defaultDir = config.getDefaultWorkDir()
await platform.send(
replyTarget,
`✅ 已切换到默认工作目录\n\n📍 ${defaultDir}`,
originalMessage,
type
)
this.logger.info('WORK_DIR', `会话 ${conversationId} 工作目录重置为默认: ${defaultDir}`)
return { status: 'SUCCESS' }
}
// 设置新的工作目录
const newPath = pathArg.trim()
const fs = require('fs')
// 检查目录是否存在
if (!fs.existsSync(newPath)) {
await platform.send(
replyTarget,
`❌ 目录不存在:${newPath}\n\n💡 请检查路径是否正确`,
originalMessage,
type
)
return { status: 'SUCCESS' }
}
// 检查是否为目录
try {
const stats = fs.statSync(newPath)
if (!stats.isDirectory()) {
await platform.send(
replyTarget,
`❌ 路径不是目录:${newPath}\n\n💡 请提供一个有效的目录路径`,
originalMessage,
type
)
return { status: 'SUCCESS' }
}
} catch (err) {
await platform.send(
replyTarget,
`❌ 无法访问目录:${newPath}\n\n错误:${err.message}`,
originalMessage,
type
)
return { status: 'SUCCESS' }
}
// 设置新的工作目录
platform.setSession(conversationId, session?.sessionId || null, currentProvider, {
...session,
workDir: newPath
})
await platform.send(
replyTarget,
`✅ 工作目录已更新\n\n📍 ${newPath}\n\n💡 使用 /path 查看详细信息`,
originalMessage,
type
)
this.logger.info('WORK_DIR', `会话 ${conversationId} 工作目录更新为: ${newPath}`)
return { status: 'SUCCESS' }
}
_buildRuntimeContext({ platformName, type, conversationId, provider, sessionWorkDir, promptMode, customPrompt }) {
return {
platform: (platformName || 'UNKNOWN').toLowerCase(),
message_type: type || 'default',
conversation_id: conversationId,
provider,
promptMode: promptMode || 'append',
customPrompt: customPrompt || null,
work_dir: config.getWorkDir(provider, sessionWorkDir),
project_dir: config.getProjectDir(),
default_work_dir: config.getDefaultWorkDir(),
timestamp: new Date().toISOString()
}
}
async _buildContextualMessage(content, runtimeContext, attachments = []) {
// 加载默认系统提示词
const defaultPrompt = await config.getSystemPrompt(runtimeContext.provider)
// 构建最终提示词
let finalPrompt = ''
if (runtimeContext.customPrompt) {
if (runtimeContext.promptMode === 'replace') {
// 替换模式:使用用户提示词
finalPrompt = runtimeContext.customPrompt
} else {
// 拼接模式:默认提示词 + 用户提示词
if (defaultPrompt) {
finalPrompt = defaultPrompt + '\n\n' + runtimeContext.customPrompt
} else {
finalPrompt = runtimeContext.customPrompt
}
}
} else {
// 无自定义提示词,使用默认提示词
finalPrompt = defaultPrompt || ''
}
const modePromptBlock = finalPrompt ? `[MODE_PROMPT]\n${finalPrompt}\n[/MODE_PROMPT]` : ''
// 构建附件块(支持图片、文件、音频、视频)
let attachmentBlock = ''
if (attachments && attachments.length > 0) {
const attachmentInfos = []
// 按类型分组
const images = attachments.filter(a => a.type === 'image')
const files = attachments.filter(a => a.type === 'file')
const audios = attachments.filter(a => a.type === 'audio')
const videos = attachments.filter(a => a.type === 'video')
// 处理图片
if (images.length > 0) {
images.forEach((a, i) => {
if (a.localPath) {
attachmentInfos.push(`[图片${i + 1}] 本地文件: ${a.localPath}`)
} else if (a.url) {
attachmentInfos.push(`[图片${i + 1}] URL: ${a.url}`)
}
})
}
// 处理文件
if (files.length > 0) {
files.forEach((a, i) => {
const fileName = a.fileName || `文件${i + 1}`
const sizeStr = a.fileSize ? ` (${(a.fileSize / 1024).toFixed(2)} KB)` : ''
if (a.localPath) {
attachmentInfos.push(`[文件${i + 1}] ${fileName}${sizeStr}\n 本地路径: ${a.localPath}`)
} else if (a.url) {
attachmentInfos.push(`[文件${i + 1}] ${fileName}${sizeStr}\n URL: ${a.url}`)
}
})
}
// 处理音频
if (audios.length > 0) {
audios.forEach((a, i) => {
const fileName = a.fileName || `音频${i + 1}`
const sizeStr = a.fileSize ? ` (${(a.fileSize / 1024).toFixed(2)} KB)` : ''
if (a.transcript) {
// 语音识别成功,直接使用识别结果
attachmentInfos.push(`[语音消息] ${a.transcript}`)
} else if (a.localPath) {
attachmentInfos.push(`[音频${i + 1}] ${fileName}${sizeStr}\n 本地路径: ${a.localPath} (语音识别未启用或失败)`)
} else if (a.url) {
attachmentInfos.push(`[音频${i + 1}] ${fileName}${sizeStr}\n URL: ${a.url} (语音识别未启用或失败)`)
}
})
}
// 处理视频
if (videos.length > 0) {
videos.forEach((a, i) => {
const fileName = a.fileName || `视频${i + 1}`
const sizeStr = a.fileSize ? ` (${(a.fileSize / 1024 / 1024).toFixed(2)} MB)` : ''
if (a.localPath) {
attachmentInfos.push(`[视频${i + 1}] ${fileName}${sizeStr}\n 本地路径: ${a.localPath} (已保存,AI 无法分析视频内容)`)
} else if (a.url) {
attachmentInfos.push(`[视频${i + 1}] ${fileName}${sizeStr}\n URL: ${a.url} (AI 无法分析视频内容)`)
}
})
}
if (attachmentInfos.length > 0) {
attachmentBlock = `\n\n[ATTACHMENTS]\n用户发送了 ${attachments.length} 个附件:\n${attachmentInfos.join('\n')}\n[/ATTACHMENTS]`
}
}
if (config.systemPrompts?.channelAware === false && config.systemPrompts?.includeSourceContext === false) {
return `${content}${attachmentBlock}`
}
if (config.systemPrompts?.includeSourceContext === false) {
return `${modePromptBlock ? `${modePromptBlock}\n\n` : ''}${content}${attachmentBlock}`
}
const contextBlock = `[RUNTIME_CONTEXT]\n${JSON.stringify(runtimeContext)}\n[/RUNTIME_CONTEXT]`
if (config.systemPrompts?.channelAware === false) {
return `${modePromptBlock ? `${modePromptBlock}\n\n` : ''}${content}${attachmentBlock}`
}
return `${contextBlock}\n\n${modePromptBlock ? `${modePromptBlock}\n\n` : ''}${content}${attachmentBlock}`
}
_mapProviderEventType(event) {
if (!event || !event.type) return 'unknown'
if (event.type === 'assistant') return 'assistant_chunk'
if (event.type === 'result' || event.type === 'done') return 'result'
if (event.type === 'tool_use') return 'tool_use'
if (event.type === 'tool_end' || event.type === 'tool_result') return 'tool_result'
if (event.type === 'session_end') return 'end'
if (event.type === 'error') return 'error'
if (event.type.includes('thinking')) return 'thinking_exposed'
return event.type
}
_shouldSendByMode(eventType, cfg) {
const profile = cfg.profile || 'standard'
if (profile === 'compact') {
return eventType === 'assistant_chunk' || eventType === 'result'
}
if (profile === 'standard') {
return ['assistant_chunk', 'result', 'tool_result', 'error', 'end'].includes(eventType)
}
return true // full/debug
}
_shouldSendEvent(eventType, cfg) {
if (!cfg.enabled) return eventType === 'assistant_chunk' || eventType === 'result'
if (!this._shouldSendByMode(eventType, cfg)) return false
if (cfg.types && cfg.types.length > 0 && !cfg.types.includes(eventType)) return false
if (eventType === 'thinking_exposed' && !cfg.sendThinking) return false
if ((eventType === 'http_request' || eventType === 'http_response') && !cfg.sendHttp) return false
return true
}
_trimText(text, maxChars) {
if (!text) return ''
const raw = String(text)
if (raw.length <= maxChars) return raw
return `${raw.slice(0, maxChars)}...[截断:${raw.length}]`
}
_formatEventMessage(eventType, event, extractedText, cfg, elapsedMs) {
return this.robotFormatter.format(eventType, event, extractedText, {
profile: cfg.profile,
elapsedMs
})
}
_shouldSendMessage(traceId, eventType, msg) {
return this.robotDedup.shouldSend(traceId, eventType, msg)
}
// ==================== 定时任务命令处理 ====================
async _handleTasksList(conversationId, replyTarget, platform, originalMessage, type) {
if (!this.scheduler || !this.scheduler.enabled) {
await platform.send(replyTarget, '⚠️ 定时任务功能未启用', originalMessage, type)
return { status: 'SUCCESS' }
}
const status = this.scheduler.getStatus()
if (status.tasks.length === 0) {
await platform.send(replyTarget, '📋 暂无定时任务', originalMessage, type)
return { status: 'SUCCESS' }
}
const lines = ['📋 定时任务列表\n']
status.tasks.forEach(task => {
const enabled = task.enabled ? '✅' : '❌'
const scheduled = task.scheduled ? '运行中' : '已停止'
lines.push(`\n${enabled} ${task.name}`)
lines.push(` ID: ${task.id}`)
lines.push(` 调度: ${task.schedule}`)
lines.push(` 模型: ${task.provider}`)
lines.push(` 状态: ${scheduled}`)
})
lines.push('\n💡 命令:')
lines.push('• tasks status - 查看详细状态')
lines.push('• tasks run <id> - 手动执行任务')
lines.push('• tasks enable <id> - 启用任务')
lines.push('• tasks disable <id> - 禁用任务')
await platform.send(replyTarget, lines.join('\n'), originalMessage, type)
return { status: 'SUCCESS' }
}
async _handleTasksStatus(conversationId, replyTarget, platform, originalMessage, type) {
if (!this.scheduler) {
await platform.send(replyTarget, '⚠️ 定时任务管理器未初始化', originalMessage, type)
return { status: 'SUCCESS' }
}
const status = this.scheduler.getStatus()
const lines = [
'📊 定时任务状态',
`\n功能状态: ${status.enabled ? '✅ 已启用' : '❌ 已禁用'}`,
`配置文件: ${status.configPath}`,
`总任务数: ${status.totalTasks}`,
`启用任务: ${status.enabledTasks}`,
`运行中任务: ${status.scheduledJobs}`
]
await platform.send(replyTarget, lines.join('\n'), originalMessage, type)
return { status: 'SUCCESS' }
}
async _handleTasksReload(conversationId, replyTarget, platform, originalMessage, type) {
if (!this.scheduler) {
await platform.send(replyTarget, '⚠️ 定时任务管理器未初始化', originalMessage, type)
return { status: 'SUCCESS' }
}
try {
await this.scheduler.taskManager.reload()
await platform.send(replyTarget, '✅ 任务配置已重载', originalMessage, type)
} catch (error) {
await platform.send(replyTarget, `❌ 重载失败: ${error.message}`, originalMessage, type)
}
return { status: 'SUCCESS' }
}
async _handleTasksRun(taskId, conversationId, replyTarget, platform, originalMessage, type) {
if (!this.scheduler || !this.scheduler.enabled) {
await platform.send(replyTarget, '⚠️ 定时任务功能未启用', originalMessage, type)
return { status: 'SUCCESS' }
}
if (!taskId) {
await platform.send(replyTarget, '❌ 请指定任务 ID:tasks run <id>', originalMessage, type)
return { status: 'SUCCESS' }
}
try {
const result = await this.scheduler.taskManager.runTask(taskId)
if (result.success) {
await platform.send(replyTarget,
`✅ 任务执行完成\n耗时: ${result.elapsed}s`, originalMessage, type
)
} else {
await platform.send(replyTarget,
`❌ 任务执行失败: ${result.error}`, originalMessage, type
)
}
} catch (error) {
await platform.send(replyTarget,
`❌ 执行失败: ${error.message}`, originalMessage, type
)
}
return { status: 'SUCCESS' }
}
async _handleTasksEnable(taskId, conversationId, replyTarget, platform, originalMessage, type) {
if (!this.scheduler || !this.scheduler.enabled) {
await platform.send(replyTarget, '⚠️ 定时任务功能未启用', originalMessage, type)
return { status: 'SUCCESS' }
}
if (!taskId) {
await platform.send(replyTarget, '❌ 请指定任务 ID:tasks enable <id>', originalMessage, type)
return { status: 'SUCCESS' }
}
try {
this.scheduler.taskManager.enableTask(taskId)
await platform.send(replyTarget, `✅ 任务已启用: ${taskId}`, originalMessage, type)
} catch (error) {
await platform.send(replyTarget, `❌ 启用失败: ${error.message}`, originalMessage, type)
}
return { status: 'SUCCESS' }
}
async _handleTasksDisable(taskId, conversationId, replyTarget, platform, originalMessage, type) {
if (!this.scheduler || !this.scheduler.enabled) {
await platform.send(replyTarget, '⚠️ 定时任务功能未启用', originalMessage, type)
return { status: 'SUCCESS' }
}
if (!taskId) {
await platform.send(replyTarget, '❌ 请指定任务 ID:tasks disable <id>', originalMessage, type)
return { status: 'SUCCESS' }
}
try {
this.scheduler.taskManager.disableTask(taskId)
await platform.send(replyTarget, `✅ 任务已禁用: ${taskId}`, originalMessage, type)
} catch (error) {
await platform.send(replyTarget, `❌ 禁用失败: ${error.message}`, originalMessage, type)
}
return { status: 'SUCCESS' }
}
async _handleTasksOn(conversationId, replyTarget, platform, originalMessage, type) {
if (!this.scheduler) {
await platform.send(replyTarget, '⚠️ 定时任务管理器未初始化', originalMessage, type)
return { status: 'SUCCESS' }
}
try {
const result = await this.scheduler.taskManager.setEnabled(true)
await platform.send(replyTarget,
`✅ 定时任务功能已启用\n已调度 ${result.scheduledJobs} 个任务`, originalMessage, type
)
} catch (error) {
await platform.send(replyTarget, `❌ 启用失败: ${error.message}`, originalMessage, type)
}
return { status: 'SUCCESS' }
}