@goodandready/dsh-messenger-gateway 0.4.19 → 0.4.21
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/alerts.js +105 -105
- package/lib/api-health.js +38 -38
- package/lib/client.js +23 -0
- package/lib/commands.js +129 -126
- package/lib/forum-mirror.js +21 -18
- package/lib/gateway-commands.js +22 -3
- package/lib/gateway.js +11 -4
- package/lib/index.js +6 -0
- package/lib/locales/en.js +4 -0
- package/lib/locales/zh.js +4 -0
- package/lib/text.js +18 -0
- package/lib/workspace.js +149 -0
- package/package.json +1 -1
package/lib/alerts.js
CHANGED
|
@@ -1,105 +1,105 @@
|
|
|
1
|
-
import { escapeHtml } from './telegram-format.js'
|
|
2
|
-
import { normalizeThreadId } from './topics.js'
|
|
3
|
-
import { t } from './locales/index.js'
|
|
4
|
-
|
|
5
|
-
export function formatAlertMessage(type, payload = {}) {
|
|
6
|
-
const timestamp = new Date().toLocaleTimeString()
|
|
7
|
-
|
|
8
|
-
if (type === 'pairing') {
|
|
9
|
-
const { userId, username, code } = payload
|
|
10
|
-
const userStr = username ? `@${username} (id: <code>${userId}</code>)` : `id: <code>${userId}</code>`
|
|
11
|
-
return [
|
|
12
|
-
`🔐 <b>[Pairing Request]</b> <i>(${timestamp})</i>`,
|
|
13
|
-
'',
|
|
14
|
-
`User: ${userStr}`,
|
|
15
|
-
`Pairing Code: <code>${code}</code>`,
|
|
16
|
-
'',
|
|
17
|
-
`To approve, send to bot:`,
|
|
18
|
-
`<code>/pair ${code}</code>`,
|
|
19
|
-
].join('\n')
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
if (type === 'error') {
|
|
23
|
-
const { message, code, sessionId, chatId, threadId } = payload
|
|
24
|
-
const location = chatId ? `Chat: <code>${chatId}</code>${threadId ? ` / thread <code>${threadId}</code>` : ''}` : ''
|
|
25
|
-
const sess = sessionId ? `Session: <code>${sessionId}</code>` : ''
|
|
26
|
-
const meta = [location, sess].filter(Boolean).join('\n')
|
|
27
|
-
|
|
28
|
-
return [
|
|
29
|
-
`🚨 <b>[Gateway Error]</b> <i>(${timestamp})</i>`,
|
|
30
|
-
meta ? `\n${meta}` : '',
|
|
31
|
-
`Error code: <b>${escapeHtml(String(code || 'error'))}</b>`,
|
|
32
|
-
`<code>${escapeHtml(String(message || 'unknown error'))}</code>`,
|
|
33
|
-
].filter(Boolean).join('\n')
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
if (type === 'status') {
|
|
37
|
-
const { title, details } = payload
|
|
38
|
-
return [
|
|
39
|
-
`⚡ <b>[Gateway: ${escapeHtml(title || 'Status')}]</b> <i>(${timestamp})</i>`,
|
|
40
|
-
details ? `\n${escapeHtml(details)}` : '',
|
|
41
|
-
].filter(Boolean).join('\n')
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
return `🔔 <b>[Alert: ${type}]</b> <i>(${timestamp})</i>\n${escapeHtml(JSON.stringify(payload))}`
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export function resolveAlertTarget(gateway) {
|
|
48
|
-
const alertsCfg = gateway?.config?.telegram?.alerts
|
|
49
|
-
if (!alertsCfg || alertsCfg.enabled === false) return null
|
|
50
|
-
|
|
51
|
-
// If a named home is specified
|
|
52
|
-
if (alertsCfg.home) {
|
|
53
|
-
const home = gateway.resolveHomeTarget('telegram', alertsCfg.home)
|
|
54
|
-
if (home) return home
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const chatId = alertsCfg.chatId
|
|
58
|
-
if (!chatId) return null
|
|
59
|
-
|
|
60
|
-
return {
|
|
61
|
-
platform: 'telegram',
|
|
62
|
-
chatId,
|
|
63
|
-
threadId: normalizeThreadId(alertsCfg.threadId),
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export async function handleSetAlertCommand(gw, input, locale) {
|
|
68
|
-
const { reply, userId, chatId, threadId = 0 } = input
|
|
69
|
-
if (!gw.isUserAllowed(userId)) return reply(t('msg.not_allowed', {}, locale))
|
|
70
|
-
const nextTg = {
|
|
71
|
-
...gw.tg(),
|
|
72
|
-
alerts: {
|
|
73
|
-
...(gw.tg().alerts || {}),
|
|
74
|
-
enabled: true,
|
|
75
|
-
chatId,
|
|
76
|
-
threadId: threadId || 0,
|
|
77
|
-
},
|
|
78
|
-
}
|
|
79
|
-
gw.config.telegram = nextTg
|
|
80
|
-
try { await gw.hooks?.persistHomes?.(nextTg) } catch (err) { gw.logger?.warn?.('persistHomes error:', err?.message || err) }
|
|
81
|
-
return reply(`🔔 This chat assigned as alert channel (chat: ${chatId}${threadId ? `, topic: ${threadId}` : ''}).`)
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export async function handleAlertCommand(gw, input, parts) {
|
|
85
|
-
const { reply, userId } = input
|
|
86
|
-
const sub = parts[1]?.toLowerCase()
|
|
87
|
-
if (sub === 'test') {
|
|
88
|
-
const target = resolveAlertTarget(gw)
|
|
89
|
-
if (!target) return reply('Alert channel not configured. Configure: /setalert')
|
|
90
|
-
await gw.sendAlert('status', { title: 'Test Alert', details: `Sent by user ID ${userId}` })
|
|
91
|
-
return reply('Test alert sent to alert channel.')
|
|
92
|
-
}
|
|
93
|
-
const target = resolveAlertTarget(gw)
|
|
94
|
-
const alertsCfg = gw.tg().alerts || {}
|
|
95
|
-
return reply([
|
|
96
|
-
'🔔 <b>Alert Channel:</b>',
|
|
97
|
-
`Status: ${alertsCfg.enabled ? 'enabled' : 'disabled'}`,
|
|
98
|
-
`Chat: ${target ? `${target.chatId}${target.threadId ? ` (topic: ${target.threadId})` : ''}` : '(not assigned)'}`,
|
|
99
|
-
`Events: ${(alertsCfg.events || ['error', 'pairing']).join(', ')}`,
|
|
100
|
-
'',
|
|
101
|
-
'Commands:',
|
|
102
|
-
'/setalert — assign current chat as alert channel',
|
|
103
|
-
'/alert test — send test alert',
|
|
104
|
-
].join('\n'))
|
|
105
|
-
}
|
|
1
|
+
import { escapeHtml } from './telegram-format.js'
|
|
2
|
+
import { normalizeThreadId } from './topics.js'
|
|
3
|
+
import { t } from './locales/index.js'
|
|
4
|
+
|
|
5
|
+
export function formatAlertMessage(type, payload = {}) {
|
|
6
|
+
const timestamp = new Date().toLocaleTimeString()
|
|
7
|
+
|
|
8
|
+
if (type === 'pairing') {
|
|
9
|
+
const { userId, username, code } = payload
|
|
10
|
+
const userStr = username ? `@${username} (id: <code>${userId}</code>)` : `id: <code>${userId}</code>`
|
|
11
|
+
return [
|
|
12
|
+
`🔐 <b>[Pairing Request]</b> <i>(${timestamp})</i>`,
|
|
13
|
+
'',
|
|
14
|
+
`User: ${userStr}`,
|
|
15
|
+
`Pairing Code: <code>${code}</code>`,
|
|
16
|
+
'',
|
|
17
|
+
`To approve, send to bot:`,
|
|
18
|
+
`<code>/pair ${code}</code>`,
|
|
19
|
+
].join('\n')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (type === 'error') {
|
|
23
|
+
const { message, code, sessionId, chatId, threadId } = payload
|
|
24
|
+
const location = chatId ? `Chat: <code>${chatId}</code>${threadId ? ` / thread <code>${threadId}</code>` : ''}` : ''
|
|
25
|
+
const sess = sessionId ? `Session: <code>${sessionId}</code>` : ''
|
|
26
|
+
const meta = [location, sess].filter(Boolean).join('\n')
|
|
27
|
+
|
|
28
|
+
return [
|
|
29
|
+
`🚨 <b>[Gateway Error]</b> <i>(${timestamp})</i>`,
|
|
30
|
+
meta ? `\n${meta}` : '',
|
|
31
|
+
`Error code: <b>${escapeHtml(String(code || 'error'))}</b>`,
|
|
32
|
+
`<code>${escapeHtml(String(message || 'unknown error'))}</code>`,
|
|
33
|
+
].filter(Boolean).join('\n')
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (type === 'status') {
|
|
37
|
+
const { title, details } = payload
|
|
38
|
+
return [
|
|
39
|
+
`⚡ <b>[Gateway: ${escapeHtml(title || 'Status')}]</b> <i>(${timestamp})</i>`,
|
|
40
|
+
details ? `\n${escapeHtml(details)}` : '',
|
|
41
|
+
].filter(Boolean).join('\n')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return `🔔 <b>[Alert: ${type}]</b> <i>(${timestamp})</i>\n${escapeHtml(JSON.stringify(payload))}`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function resolveAlertTarget(gateway) {
|
|
48
|
+
const alertsCfg = gateway?.config?.telegram?.alerts
|
|
49
|
+
if (!alertsCfg || alertsCfg.enabled === false) return null
|
|
50
|
+
|
|
51
|
+
// If a named home is specified
|
|
52
|
+
if (alertsCfg.home) {
|
|
53
|
+
const home = gateway.resolveHomeTarget('telegram', alertsCfg.home)
|
|
54
|
+
if (home) return home
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const chatId = alertsCfg.chatId
|
|
58
|
+
if (!chatId) return null
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
platform: 'telegram',
|
|
62
|
+
chatId,
|
|
63
|
+
threadId: normalizeThreadId(alertsCfg.threadId),
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function handleSetAlertCommand(gw, input, locale) {
|
|
68
|
+
const { reply, userId, chatId, threadId = 0 } = input
|
|
69
|
+
if (!gw.isUserAllowed(userId)) return reply(t('msg.not_allowed', {}, locale))
|
|
70
|
+
const nextTg = {
|
|
71
|
+
...gw.tg(),
|
|
72
|
+
alerts: {
|
|
73
|
+
...(gw.tg().alerts || {}),
|
|
74
|
+
enabled: true,
|
|
75
|
+
chatId,
|
|
76
|
+
threadId: threadId || 0,
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
gw.config.telegram = nextTg
|
|
80
|
+
try { await gw.hooks?.persistHomes?.(nextTg) } catch (err) { gw.logger?.warn?.('persistHomes error:', err?.message || err) }
|
|
81
|
+
return reply(`🔔 This chat assigned as alert channel (chat: ${chatId}${threadId ? `, topic: ${threadId}` : ''}).`)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function handleAlertCommand(gw, input, parts) {
|
|
85
|
+
const { reply, userId } = input
|
|
86
|
+
const sub = parts[1]?.toLowerCase()
|
|
87
|
+
if (sub === 'test') {
|
|
88
|
+
const target = resolveAlertTarget(gw)
|
|
89
|
+
if (!target) return reply('Alert channel not configured. Configure: /setalert')
|
|
90
|
+
await gw.sendAlert('status', { title: 'Test Alert', details: `Sent by user ID ${userId}` })
|
|
91
|
+
return reply('Test alert sent to alert channel.')
|
|
92
|
+
}
|
|
93
|
+
const target = resolveAlertTarget(gw)
|
|
94
|
+
const alertsCfg = gw.tg().alerts || {}
|
|
95
|
+
return reply([
|
|
96
|
+
'🔔 <b>Alert Channel:</b>',
|
|
97
|
+
`Status: ${alertsCfg.enabled ? 'enabled' : 'disabled'}`,
|
|
98
|
+
`Chat: ${target ? `${target.chatId}${target.threadId ? ` (topic: ${target.threadId})` : ''}` : '(not assigned)'}`,
|
|
99
|
+
`Events: ${(alertsCfg.events || ['error', 'pairing']).join(', ')}`,
|
|
100
|
+
'',
|
|
101
|
+
'Commands:',
|
|
102
|
+
'/setalert — assign current chat as alert channel',
|
|
103
|
+
'/alert test — send test alert',
|
|
104
|
+
].join('\n'))
|
|
105
|
+
}
|
package/lib/api-health.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
export class ApiHealthTracker {
|
|
2
|
-
constructor(options = {}) {
|
|
3
|
-
this.logger = options.logger || console
|
|
4
|
-
this.degradedThreshold = Number(options.degradedThreshold) || 3
|
|
5
|
-
this.warnThreshold = Number(options.warnThreshold) || 5
|
|
6
|
-
this.consecutiveFailures = 0
|
|
7
|
-
this.lastError = null
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
recordFailure(op, err) {
|
|
11
|
-
this.consecutiveFailures++
|
|
12
|
-
this.lastError = {
|
|
13
|
-
op,
|
|
14
|
-
message: err?.message || String(err),
|
|
15
|
-
time: Date.now(),
|
|
16
|
-
}
|
|
17
|
-
this.logger?.debug?.(`dsh-messenger-gateway: Telegram API ${op} failed (${this.consecutiveFailures} consecutive):`, err?.message || err)
|
|
18
|
-
if (this.consecutiveFailures >= this.warnThreshold && this.consecutiveFailures % this.warnThreshold === 0) {
|
|
19
|
-
this.logger?.warn?.(`dsh-messenger-gateway: Telegram API experiencing repeated failures (${this.consecutiveFailures} in a row). Last op: ${op}, error: ${err?.message || err}`)
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
recordSuccess() {
|
|
24
|
-
this.consecutiveFailures = 0
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
isDegraded() {
|
|
28
|
-
return this.consecutiveFailures >= this.degradedThreshold
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
getSnapshot() {
|
|
32
|
-
return {
|
|
33
|
-
degraded: this.isDegraded(),
|
|
34
|
-
consecutiveFailures: this.consecutiveFailures,
|
|
35
|
-
lastError: this.lastError,
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
}
|
|
1
|
+
export class ApiHealthTracker {
|
|
2
|
+
constructor(options = {}) {
|
|
3
|
+
this.logger = options.logger || console
|
|
4
|
+
this.degradedThreshold = Number(options.degradedThreshold) || 3
|
|
5
|
+
this.warnThreshold = Number(options.warnThreshold) || 5
|
|
6
|
+
this.consecutiveFailures = 0
|
|
7
|
+
this.lastError = null
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
recordFailure(op, err) {
|
|
11
|
+
this.consecutiveFailures++
|
|
12
|
+
this.lastError = {
|
|
13
|
+
op,
|
|
14
|
+
message: err?.message || String(err),
|
|
15
|
+
time: Date.now(),
|
|
16
|
+
}
|
|
17
|
+
this.logger?.debug?.(`dsh-messenger-gateway: Telegram API ${op} failed (${this.consecutiveFailures} consecutive):`, err?.message || err)
|
|
18
|
+
if (this.consecutiveFailures >= this.warnThreshold && this.consecutiveFailures % this.warnThreshold === 0) {
|
|
19
|
+
this.logger?.warn?.(`dsh-messenger-gateway: Telegram API experiencing repeated failures (${this.consecutiveFailures} in a row). Last op: ${op}, error: ${err?.message || err}`)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
recordSuccess() {
|
|
24
|
+
this.consecutiveFailures = 0
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
isDegraded() {
|
|
28
|
+
return this.consecutiveFailures >= this.degradedThreshold
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
getSnapshot() {
|
|
32
|
+
return {
|
|
33
|
+
degraded: this.isDegraded(),
|
|
34
|
+
consecutiveFailures: this.consecutiveFailures,
|
|
35
|
+
lastError: this.lastError,
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
package/lib/client.js
CHANGED
|
@@ -109,6 +109,8 @@ window.__ModuleLoader__.load({
|
|
|
109
109
|
proxyUrlHint: 'Optional proxy for Telegram API requests (e.g. socks5://127.0.0.1:1080 or http://127.0.0.1:8080).',
|
|
110
110
|
apiRoot: 'Custom Telegram Bot API Base URL',
|
|
111
111
|
apiRootHint: 'Custom API root for reverse proxies or local Bot API servers. Default: https://api.telegram.org',
|
|
112
|
+
workingDir: 'Working directory (agent.cwd)',
|
|
113
|
+
workingDirHint: 'Default workspace root for agent turns and file explorer (/files, /get). Empty = host launch directory ({effective}).',
|
|
112
114
|
sessionScope: 'Group Session Scope',
|
|
113
115
|
sessionScopeChat: 'Shared per chat/topic',
|
|
114
116
|
sessionScopeUser: 'Per-user session (recommended)',
|
|
@@ -256,6 +258,8 @@ window.__ModuleLoader__.load({
|
|
|
256
258
|
proxyUrlHint: 'Telegram API 请求的可选代理(例如 socks5://127.0.0.1:1080 或 http://127.0.0.1:8080)。',
|
|
257
259
|
apiRoot: '自定义 Telegram Bot API 地址',
|
|
258
260
|
apiRootHint: '用于反向代理或本地 Bot API 服务器的自定义根地址。默认:https://api.telegram.org',
|
|
261
|
+
workingDir: '工作目录 (agent.cwd)',
|
|
262
|
+
workingDirHint: 'Agent 执行与文件管理器 (/files, /get) 的根目录。留空则跟随宿主启动目录 ({effective})。',
|
|
259
263
|
sessionScope: '群组会话范围',
|
|
260
264
|
sessionScopeChat: '每个聊天/话题共享',
|
|
261
265
|
sessionScopeUser: '每用户独立会话 (推荐)',
|
|
@@ -536,6 +540,7 @@ window.__ModuleLoader__.load({
|
|
|
536
540
|
agent: {
|
|
537
541
|
provider: a.provider || '',
|
|
538
542
|
model: a.model || '',
|
|
543
|
+
cwd: typeof a.cwd === 'string' ? a.cwd : '',
|
|
539
544
|
instructionPrefix: a.instructionPrefix || '',
|
|
540
545
|
maxMessageLength: Number(a.maxMessageLength) || 4000,
|
|
541
546
|
turnTimeoutMs: Number(a.turnTimeoutMs) || 600000,
|
|
@@ -1093,6 +1098,24 @@ window.__ModuleLoader__.load({
|
|
|
1093
1098
|
onChange: (e) => setCfg({ ...cfg, agent: { ...cfg.agent, model: e.target.value } }),
|
|
1094
1099
|
})
|
|
1095
1100
|
),
|
|
1101
|
+
React.createElement(Field, {
|
|
1102
|
+
label: t('workingDir'),
|
|
1103
|
+
hint: t('workingDirHint', {
|
|
1104
|
+
effective: status?.config?.agent?.effectiveCwd || status?.config?.agent?.defaultCwd || 'process.cwd()',
|
|
1105
|
+
}),
|
|
1106
|
+
},
|
|
1107
|
+
React.createElement('input', {
|
|
1108
|
+
className: 'msgw-input',
|
|
1109
|
+
value: cfg.agent?.cwd || '',
|
|
1110
|
+
placeholder: status?.config?.agent?.defaultCwd || '',
|
|
1111
|
+
onChange: (e) => setCfg({ ...cfg, agent: { ...cfg.agent, cwd: e.target.value } }),
|
|
1112
|
+
}),
|
|
1113
|
+
status?.config?.agent?.cwdWarning ? React.createElement(
|
|
1114
|
+
'span',
|
|
1115
|
+
{ className: 'msgw-badge msgw-badge-bad', style: { marginTop: '6px' } },
|
|
1116
|
+
`⚠️ ${status.config.agent.cwdWarning}`
|
|
1117
|
+
) : null
|
|
1118
|
+
),
|
|
1096
1119
|
React.createElement(Field, { label: t('photoOnly') },
|
|
1097
1120
|
React.createElement(
|
|
1098
1121
|
'select',
|
package/lib/commands.js
CHANGED
|
@@ -1,126 +1,129 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
{ command: '
|
|
4
|
-
{ command: '
|
|
5
|
-
{ command: '
|
|
6
|
-
{ command: '
|
|
7
|
-
{ command: '
|
|
8
|
-
{ command: '
|
|
9
|
-
{ command: '
|
|
10
|
-
{ command: '
|
|
11
|
-
{ command: '
|
|
12
|
-
{ command: '
|
|
13
|
-
{ command: '
|
|
14
|
-
{ command: '
|
|
15
|
-
{ command: '
|
|
16
|
-
{ command: '
|
|
17
|
-
{ command: '
|
|
18
|
-
{ command: '
|
|
19
|
-
{ command: '
|
|
20
|
-
{ command: '
|
|
21
|
-
{ command: '
|
|
22
|
-
{ command: '
|
|
23
|
-
{ command: '
|
|
24
|
-
{ command: '
|
|
25
|
-
{ command: '
|
|
26
|
-
{ command: '
|
|
27
|
-
{ command: '
|
|
28
|
-
{ command: '
|
|
29
|
-
{ command: '
|
|
30
|
-
{ command: '
|
|
31
|
-
{ command: '
|
|
32
|
-
{ command: '
|
|
33
|
-
{ command: '
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
command = command.replace(
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (!
|
|
67
|
-
description = description.
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
export const
|
|
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
|
-
|
|
1
|
+
import { truncateSafe } from "./text.js"
|
|
2
|
+
export const DEFAULT_TELEGRAM_COMMANDS = [
|
|
3
|
+
{ command: 'start', description: 'Connect and show greeting' },
|
|
4
|
+
{ command: 'help', description: 'Show commands help' },
|
|
5
|
+
{ command: 'new', description: 'Start a new agent session' },
|
|
6
|
+
{ command: 'whoami', description: 'Show your messenger user ID' },
|
|
7
|
+
{ command: 'stop', description: 'Interrupt current turn' },
|
|
8
|
+
{ command: 'pair', description: 'Approve pairing code: /pair CODE' },
|
|
9
|
+
{ command: 'sethome', description: 'Set home: /sethome [name]' },
|
|
10
|
+
{ command: 'home', description: 'List registered home channels' },
|
|
11
|
+
{ command: 'model', description: 'Interactive model selector' },
|
|
12
|
+
{ command: 'top', description: 'System resources: CPU, RAM, uptime' },
|
|
13
|
+
{ command: 'topic', description: 'Create forum topic: /topic <name>' },
|
|
14
|
+
{ command: 'status', description: 'Gateway and bot status' },
|
|
15
|
+
{ command: 'setalert', description: 'Designate channel for alerts' },
|
|
16
|
+
{ command: 'alert', description: 'Alert channel status: /alert [test]' },
|
|
17
|
+
{ command: 'keyboard', description: 'Toggle quick actions: /keyboard on|off' },
|
|
18
|
+
{ command: 'role', description: 'Switch persona: /role [name]' },
|
|
19
|
+
{ command: 'bind', description: 'Bind preset/persona to forum topic: /bind <name>' },
|
|
20
|
+
{ command: 'preset', description: 'Show or switch agent preset: /preset [name]' },
|
|
21
|
+
{ command: 'cron', description: 'Manage recurring reports: /cron' },
|
|
22
|
+
{ command: 'skills', description: 'List active tools & skills' },
|
|
23
|
+
{ command: 'tools', description: 'List active tools' },
|
|
24
|
+
{ command: 'fork', description: 'Fork session into new branch' },
|
|
25
|
+
{ command: 'export', description: 'Export history to Markdown' },
|
|
26
|
+
{ command: 'rewind', description: 'Rewind turns: /rewind [N]' },
|
|
27
|
+
{ command: 'cwd', description: 'Show working directory: /cwd' },
|
|
28
|
+
{ command: 'files', description: 'Workspace file explorer: /files [dir]' },
|
|
29
|
+
{ command: 'get', description: 'Download file to messenger: /get <path>' },
|
|
30
|
+
{ command: 'remind', description: 'Set reminder: /remind <time> <text>' },
|
|
31
|
+
{ command: 'voice', description: 'Voice reply mode: /voice on|off|status' },
|
|
32
|
+
{ command: 'tts', description: 'Speech in this chat: /tts on|off|status' },
|
|
33
|
+
{ command: 'mute', description: 'Mute notifications in this chat' },
|
|
34
|
+
{ command: 'unmute', description: 'Unmute notifications in this chat' },
|
|
35
|
+
{ command: 'update', description: 'Check or install plugin update: /update [now]' },
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
export function normalizeTelegramCommands(commands) {
|
|
39
|
+
const source = Array.isArray(commands) && commands.length ? commands : DEFAULT_TELEGRAM_COMMANDS
|
|
40
|
+
const out = []
|
|
41
|
+
const seen = new Set()
|
|
42
|
+
for (const raw of source) {
|
|
43
|
+
if (!raw || typeof raw !== 'object') continue
|
|
44
|
+
let command = String(raw.command || '').trim().replace(/^\//, '')
|
|
45
|
+
const description = String(raw.description || '').trim()
|
|
46
|
+
if (!command || !description) continue
|
|
47
|
+
command = command.slice(0, 32).toLowerCase()
|
|
48
|
+
if (seen.has(command)) continue
|
|
49
|
+
seen.add(command)
|
|
50
|
+
out.push({ command, description: truncateSafe(description, 256) })
|
|
51
|
+
}
|
|
52
|
+
return out.length ? out : [...DEFAULT_TELEGRAM_COMMANDS]
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function mergeDynamicCommands(baseCommands = DEFAULT_TELEGRAM_COMMANDS, dynamicCommands = [], maxTotal = 100) {
|
|
56
|
+
const normalizedBase = normalizeTelegramCommands(baseCommands)
|
|
57
|
+
const out = [...normalizedBase]
|
|
58
|
+
const seen = new Set(out.map((c) => c.command))
|
|
59
|
+
|
|
60
|
+
for (const item of dynamicCommands || []) {
|
|
61
|
+
if (out.length >= maxTotal) break
|
|
62
|
+
if (!item || typeof item !== 'object') continue
|
|
63
|
+
let command = String(item.command || item.name || '').trim().replace(/^\//, '').toLowerCase()
|
|
64
|
+
// Telegram format: lowercase alphanumeric and underscore only, 1-32 chars
|
|
65
|
+
command = command.replace(/[^a-z0-9_]/g, '_').slice(0, 32)
|
|
66
|
+
if (!command || seen.has(command)) continue
|
|
67
|
+
let description = String(item.description || item.title || `Skill ${command}`).trim()
|
|
68
|
+
if (!description) description = `Skill ${command}`
|
|
69
|
+
description = truncateSafe(description, 256)
|
|
70
|
+
seen.add(command)
|
|
71
|
+
out.push({ command, description })
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return out.slice(0, maxTotal)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function buildQuickActionsKeyboard() {
|
|
78
|
+
return {
|
|
79
|
+
keyboard: [
|
|
80
|
+
[{ text: '🔄 /new' }, { text: '🛑 /stop' }],
|
|
81
|
+
[{ text: '🎙️ /voice' }, { text: '📊 /status' }],
|
|
82
|
+
],
|
|
83
|
+
resize_keyboard: true,
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const REMOVE_REPLY_KEYBOARD = { remove_keyboard: true }
|
|
88
|
+
|
|
89
|
+
export const HELP_TEXT = [
|
|
90
|
+
'📖 <b>Messenger Gateway Help:</b>',
|
|
91
|
+
'',
|
|
92
|
+
'💬 <b>Session & Chat:</b>',
|
|
93
|
+
'• /help — show this command reference',
|
|
94
|
+
'• /new — start fresh session',
|
|
95
|
+
'• /stop — interrupt current response',
|
|
96
|
+
'• /model — interactive model selector (/model list)',
|
|
97
|
+
'• /role [name] — switch persona or role (/role list)',
|
|
98
|
+
'• /bind [role] — bind persona to topic / chat',
|
|
99
|
+
'• /preset [name] — bind preset to topic / chat',
|
|
100
|
+
'• /lang [en|zh] — switch user language',
|
|
101
|
+
'• /rewind [N] — rewind last N turns',
|
|
102
|
+
'• /fork — fork session into new branch',
|
|
103
|
+
'• /export — export history to Markdown',
|
|
104
|
+
'',
|
|
105
|
+
'🛠️ <b>Tools, Files & Cron:</b>',
|
|
106
|
+
'• /skills / /tools — list active tools & skills',
|
|
107
|
+
'• /cwd — show current working directory',
|
|
108
|
+
'• /files [dir] — workspace file explorer',
|
|
109
|
+
'• /get <path> — download file from workspace',
|
|
110
|
+
'• /remind <time> <text> — set reminder (/remind 10m check deploy)',
|
|
111
|
+
'• /cron <interval> <prompt> — recurring autonomous task',
|
|
112
|
+
'',
|
|
113
|
+
'⚙️ <b>Settings & Stats:</b>',
|
|
114
|
+
'• /status — gateway and active model status',
|
|
115
|
+
'• /top — system resource usage (RAM, uptime)',
|
|
116
|
+
'• /keyboard on|off — quick action keyboard',
|
|
117
|
+
'• /voice on|off|status — voice replies preference',
|
|
118
|
+
'• /tts on|off|status — speech synthesis in this chat',
|
|
119
|
+
'• /mute / /unmute — mute notifications in this chat',
|
|
120
|
+
'',
|
|
121
|
+
'🔒 <b>Access & Channels:</b>',
|
|
122
|
+
'• /whoami — your messenger user ID',
|
|
123
|
+
'• /pair CODE — approve pairing code',
|
|
124
|
+
'• /sethome [name] — set home notification channel',
|
|
125
|
+
'• /setalert — set alert channel',
|
|
126
|
+
].join('\n')
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
|
package/lib/forum-mirror.js
CHANGED
|
@@ -1,31 +1,34 @@
|
|
|
1
1
|
import { mergeDynamicCommands } from './commands.js'
|
|
2
2
|
import { t } from './locales/index.js'
|
|
3
|
-
import { stripReasoningPreamble, splitText } from './text.js'
|
|
3
|
+
import { stripReasoningPreamble, splitText, truncateSafe } from './text.js'
|
|
4
4
|
import { stripImageUrls } from './outbound.js'
|
|
5
5
|
|
|
6
|
-
export function collectDynamicSkills(ctx) {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
6
|
+
export async function collectDynamicSkills(ctx) {
|
|
7
|
+
const skills = []
|
|
8
|
+
try {
|
|
9
|
+
const skillsService = ctx?.get ? ctx.get("skills") : ctx?.skills
|
|
10
|
+
if (!skillsService) return skills
|
|
11
|
+
const rawSkills = typeof skillsService.list === "function" ? skillsService.list() : []
|
|
12
|
+
const allSkills = (rawSkills && typeof rawSkills.then === "function") ? await rawSkills : (rawSkills || [])
|
|
13
|
+
for (const s of allSkills) {
|
|
14
|
+
if (!s || !s.name) continue
|
|
15
|
+
if (s.invocation?.userInvocable === false || s.userInvocable === false) continue
|
|
16
|
+
const rawDesc = String(s.description || s.title || `Skill ${s.name}`).trim()
|
|
17
|
+
skills.push({
|
|
18
|
+
name: String(s.name),
|
|
19
|
+
description: truncateSafe(rawDesc || `Skill ${s.name}`, 80),
|
|
20
|
+
})
|
|
21
21
|
}
|
|
22
|
-
|
|
22
|
+
} catch (err) {
|
|
23
|
+
ctx?.logger?.debug?.(`Failed to collect dynamic skills: ${err?.message || err}`)
|
|
23
24
|
}
|
|
25
|
+
return skills
|
|
26
|
+
}
|
|
24
27
|
export async function syncTelegramCommands(gw) {
|
|
25
28
|
const tgAdapter = gw.adapters.get('telegram')
|
|
26
29
|
if (!tgAdapter || typeof tgAdapter.registerCommands !== 'function') return
|
|
27
30
|
const baseCommands = gw.config.telegram?.commands || []
|
|
28
|
-
const dynamicSkills = collectDynamicSkills(gw.ctx)
|
|
31
|
+
const dynamicSkills = await collectDynamicSkills(gw.ctx)
|
|
29
32
|
const merged = mergeDynamicCommands(baseCommands, dynamicSkills, 100)
|
|
30
33
|
try {
|
|
31
34
|
await tgAdapter.registerCommands(merged)
|
package/lib/gateway-commands.js
CHANGED
|
@@ -12,6 +12,9 @@ import { listModelCatalog, buildProvidersKeyboard } from './models.js'
|
|
|
12
12
|
import { normalizeHomeName, upsertHome, listHomes } from './homes.js'
|
|
13
13
|
import { handleSetAlertCommand, handleAlertCommand } from './alerts.js'
|
|
14
14
|
import { HELP_TEXT } from './commands.js'
|
|
15
|
+
import { resolveEffectiveCwd } from './workspace.js'
|
|
16
|
+
import { escapeHtml } from './telegram-format.js'
|
|
17
|
+
|
|
15
18
|
|
|
16
19
|
export function releaseChatTurn(chat) {
|
|
17
20
|
chat.busy = Promise.resolve()
|
|
@@ -249,16 +252,31 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
249
252
|
}
|
|
250
253
|
}
|
|
251
254
|
|
|
255
|
+
if (cmd === '/cwd') {
|
|
256
|
+
const chat = gw.chats.get(key)
|
|
257
|
+
const sessionCwd = chat?.agent?.meta?.cwd || chat?.agent?.session?.meta?.cwd || resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
|
|
258
|
+
const configuredCwd = gw.config.agent?.cwd || ''
|
|
259
|
+
const lines = [
|
|
260
|
+
`📁 <b>Working Directory:</b> <code>${escapeHtml(sessionCwd)}</code>`,
|
|
261
|
+
]
|
|
262
|
+
if (configuredCwd) {
|
|
263
|
+
lines.push(`⚙️ Configured: <code>${escapeHtml(configuredCwd)}</code>`)
|
|
264
|
+
} else {
|
|
265
|
+
lines.push(`ℹ️ Default: host launch directory`)
|
|
266
|
+
}
|
|
267
|
+
return reply(lines.join('\n'))
|
|
268
|
+
}
|
|
269
|
+
|
|
252
270
|
if (cmd === '/files') {
|
|
253
271
|
const subPath = parts.slice(1).join(' ').trim() || '.'
|
|
254
|
-
const agentCwd = gw.config.agent?.cwd
|
|
272
|
+
const agentCwd = resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
|
|
255
273
|
const res = await handleFilesCommand(agentCwd, subPath)
|
|
256
274
|
return reply(res.text)
|
|
257
275
|
}
|
|
258
276
|
|
|
259
277
|
if (cmd === '/get') {
|
|
260
278
|
const targetRel = parts.slice(1).join(' ').trim()
|
|
261
|
-
const agentCwd = gw.config.agent?.cwd
|
|
279
|
+
const agentCwd = resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
|
|
262
280
|
const maxDocBytes = Number(gw.config.media?.maxDocBytes) || 50 * 1024 * 1024
|
|
263
281
|
const res = await handleGetCommand(agentCwd, targetRel, maxDocBytes)
|
|
264
282
|
return reply(res.files ? { text: res.text, files: res.files } : res.text)
|
|
@@ -583,5 +601,6 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
583
601
|
return reply(t('msg.muted_off', {}, locale))
|
|
584
602
|
}
|
|
585
603
|
|
|
586
|
-
|
|
604
|
+
// Unrecognized slash command: let it pass through to the underlying DSH agent (runtime commands, skills)
|
|
605
|
+
return { forwardToAgent: true }
|
|
587
606
|
}
|
package/lib/gateway.js
CHANGED
|
@@ -28,6 +28,8 @@ import {
|
|
|
28
28
|
mirrorSessionToForumTopic, relayTurnToForumMirror,
|
|
29
29
|
} from './forum-mirror.js'
|
|
30
30
|
import { resolveInternalBaseUrl } from './config.js'
|
|
31
|
+
import { resolveEffectiveCwd, registerSessionInWorkspace } from './workspace.js'
|
|
32
|
+
|
|
31
33
|
|
|
32
34
|
const PLUGIN = 'dsh-messenger-gateway'
|
|
33
35
|
|
|
@@ -388,7 +390,10 @@ export class Gateway {
|
|
|
388
390
|
let attachments = [...(input.attachments || [])]
|
|
389
391
|
const hasMedia = attachments.length > 0
|
|
390
392
|
if (!body && !hasMedia) return
|
|
391
|
-
if (body.startsWith('/')) {
|
|
393
|
+
if (body.startsWith('/')) {
|
|
394
|
+
const cmdResult = await this.handleCommand(key, body, input)
|
|
395
|
+
if (!cmdResult?.forwardToAgent) return
|
|
396
|
+
}
|
|
392
397
|
try {
|
|
393
398
|
const chat = await this.getOrCreateChat(key, input)
|
|
394
399
|
const photoOnlyMode = this.config.agent?.photoOnlyMode ?? 'prompt'
|
|
@@ -416,7 +421,8 @@ export class Gateway {
|
|
|
416
421
|
break
|
|
417
422
|
}
|
|
418
423
|
}
|
|
419
|
-
const
|
|
424
|
+
const cleanBody = body.replace(/^(\/[a-zA-Z0-9_]+)@[a-zA-Z0-9_]+(?=\s|$)/, '$1')
|
|
425
|
+
const turnInput = { ...input, text: cleanBody, attachments, inboundWasVoice, personaOverride }
|
|
420
426
|
|
|
421
427
|
// Hermes-like steer: while a turn is running, inject followup instead of abort+restart
|
|
422
428
|
if (this.isChatBusy(chat)) {
|
|
@@ -466,7 +472,7 @@ export class Gateway {
|
|
|
466
472
|
return handleGatewayCommand(this, key, text, input)
|
|
467
473
|
}
|
|
468
474
|
|
|
469
|
-
collectDynamicSkills() {
|
|
475
|
+
async collectDynamicSkills() {
|
|
470
476
|
return collectDynamicSkills(this.ctx)
|
|
471
477
|
}
|
|
472
478
|
|
|
@@ -510,7 +516,7 @@ export class Gateway {
|
|
|
510
516
|
async createChat(key, input, existingSessionId) {
|
|
511
517
|
const { provider, model } = this.resolveAgentModel()
|
|
512
518
|
const agentCfg = this.config.agent || {}
|
|
513
|
-
const cwd = agentCfg.cwd
|
|
519
|
+
const cwd = resolveEffectiveCwd(agentCfg.cwd, this.ctx.logger)
|
|
514
520
|
const self = this
|
|
515
521
|
const agents = this.ctx.get?.('agents') || this.ctx.agents
|
|
516
522
|
const targetSessionId = existingSessionId ? SessionId(existingSessionId) : SessionId(`msgw-${randomUUID()}`)
|
|
@@ -526,6 +532,7 @@ export class Gateway {
|
|
|
526
532
|
},
|
|
527
533
|
})
|
|
528
534
|
await handle.agent.whenIdle()
|
|
535
|
+
await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch(() => {})
|
|
529
536
|
const chat = {
|
|
530
537
|
key, agent: handle.agent, dispose: handle.dispose, busy: Promise.resolve(),
|
|
531
538
|
lastUsed: Date.now(), abort: undefined, pendingMedia: [], turnActive: false,
|
package/lib/index.js
CHANGED
|
@@ -15,6 +15,8 @@ import { Config, plainConfig, resolveInternalBaseUrl } from './config.js'
|
|
|
15
15
|
import { describeProxy } from './proxy.js'
|
|
16
16
|
import { readSecrets, restoreSecrets } from './secret-guard.js'
|
|
17
17
|
import { setupSettings } from './settings-bridge.js'
|
|
18
|
+
import { resolveEffectiveCwd, getCwdWarning } from './workspace.js'
|
|
19
|
+
|
|
18
20
|
|
|
19
21
|
export const name = '@goodandready/dsh-messenger-gateway'
|
|
20
22
|
export const inject = ['agentDefaultModel', 'agents', 'sessions', 'loader', 'settings', 'webServer', 'attachments', 'tools']
|
|
@@ -94,6 +96,10 @@ function publicConfig(cfg, gw, ctx) {
|
|
|
94
96
|
agent: {
|
|
95
97
|
provider: cfg.agent.provider,
|
|
96
98
|
model: cfg.agent.model,
|
|
99
|
+
cwd: cfg.agent.cwd || '',
|
|
100
|
+
effectiveCwd: resolveEffectiveCwd(cfg.agent.cwd, ctx?.logger),
|
|
101
|
+
defaultCwd: process.cwd(),
|
|
102
|
+
cwdWarning: getCwdWarning(cfg.agent.cwd),
|
|
97
103
|
photoOnlyMode: cfg.agent.photoOnlyMode,
|
|
98
104
|
maxMessageLength: cfg.agent.maxMessageLength,
|
|
99
105
|
turnTimeoutMs: cfg.agent.turnTimeoutMs,
|
package/lib/locales/en.js
CHANGED
|
@@ -10,6 +10,10 @@ export const en = {
|
|
|
10
10
|
'cmd.fork': 'Fork session into new branch',
|
|
11
11
|
'cmd.export': 'Export history to Markdown',
|
|
12
12
|
'cmd.skills': 'List active tools & skills',
|
|
13
|
+
'cmd.cwd': 'Show current working directory',
|
|
14
|
+
'cwd.title': '📁 <b>Working Directory:</b> <code>{sessionCwd}</code>',
|
|
15
|
+
'cwd.configured': '⚙️ Configured: <code>{configuredCwd}</code>',
|
|
16
|
+
'cwd.default': 'ℹ️ Default: host launch directory',
|
|
13
17
|
'cmd.files': 'Workspace file explorer',
|
|
14
18
|
'cmd.get': 'Download file from workspace',
|
|
15
19
|
'cmd.remind': 'Set a timer or reminder',
|
package/lib/locales/zh.js
CHANGED
|
@@ -10,6 +10,10 @@ export const zh = {
|
|
|
10
10
|
'cmd.fork': '将会话派生到新分支',
|
|
11
11
|
'cmd.export': '导出历史记录为Markdown',
|
|
12
12
|
'cmd.skills': '列出当前可用工具与技能',
|
|
13
|
+
'cmd.cwd': '显示当前会话工作目录',
|
|
14
|
+
'cwd.title': '📁 <b>工作目录:</b> <code>{sessionCwd}</code>',
|
|
15
|
+
'cwd.configured': '⚙️ 已配置: <code>{configuredCwd}</code>',
|
|
16
|
+
'cwd.default': 'ℹ️ 默认: 宿主启动目录',
|
|
13
17
|
'cmd.files': '工作区文件浏览器',
|
|
14
18
|
'cmd.get': '从工作区下载文件',
|
|
15
19
|
'cmd.remind': '设置提醒或定时器',
|
package/lib/text.js
CHANGED
|
@@ -37,3 +37,21 @@ export function stripReasoningPreamble(text) {
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
export const MESSENGER_RELAY_INSTRUCTION = 'Channel: Messenger. Reply concisely and directly to the user. Do not leak internal reasoning or planning traces.'
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Truncate string to maxLen without splitting UTF-16 surrogate pairs.
|
|
43
|
+
* If the cut falls on a high surrogate, drops the high surrogate so the string is well-formed.
|
|
44
|
+
*/
|
|
45
|
+
export function truncateSafe(str, maxLen = 80) {
|
|
46
|
+
const raw = String(str ?? '')
|
|
47
|
+
if (raw.length <= maxLen) return raw
|
|
48
|
+
let sliced = raw.slice(0, maxLen)
|
|
49
|
+
const lastCode = sliced.charCodeAt(sliced.length - 1)
|
|
50
|
+
if (lastCode >= 0xD800 && lastCode <= 0xDBFF) {
|
|
51
|
+
sliced = sliced.slice(0, -1)
|
|
52
|
+
}
|
|
53
|
+
if (typeof sliced.isWellFormed === 'function' && !sliced.isWellFormed()) {
|
|
54
|
+
sliced = sliced.replace(/[\uD800-\uDFFF]+$/, '')
|
|
55
|
+
}
|
|
56
|
+
return sliced
|
|
57
|
+
}
|
package/lib/workspace.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { resolve, normalize, basename } from 'node:path'
|
|
2
|
+
import { statSync, realpathSync, existsSync } from 'node:fs'
|
|
3
|
+
import { readFile } from 'node:fs/promises'
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
import os from 'node:os'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { writeJsonAtomic } from './storage-atomic.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Validates configured cwd path and returns an error description if invalid.
|
|
11
|
+
* Empty or unconfigured cwd returns null (defaults to host launch dir).
|
|
12
|
+
*/
|
|
13
|
+
export function getCwdWarning(configuredCwd) {
|
|
14
|
+
const trimmed = typeof configuredCwd === 'string' ? configuredCwd.trim() : ''
|
|
15
|
+
if (!trimmed) return null
|
|
16
|
+
try {
|
|
17
|
+
const resolved = resolve(trimmed)
|
|
18
|
+
const st = statSync(resolved)
|
|
19
|
+
if (!st.isDirectory()) {
|
|
20
|
+
return `Path "${trimmed}" is not a directory`
|
|
21
|
+
}
|
|
22
|
+
return null
|
|
23
|
+
} catch (err) {
|
|
24
|
+
const code = err?.code || err?.message || String(err)
|
|
25
|
+
return `Directory "${trimmed}" does not exist or is not accessible (${code})`
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Resolves effective working directory for agent sessions and file operations.
|
|
31
|
+
* Falls back to process.cwd() if configured cwd is empty or invalid.
|
|
32
|
+
*/
|
|
33
|
+
export function resolveEffectiveCwd(configuredCwd, logger) {
|
|
34
|
+
const trimmed = typeof configuredCwd === 'string' ? configuredCwd.trim() : ''
|
|
35
|
+
if (!trimmed) return process.cwd()
|
|
36
|
+
const warning = getCwdWarning(trimmed)
|
|
37
|
+
if (warning) {
|
|
38
|
+
logger?.warn?.(`[dsh-messenger-gateway] ${warning}, falling back to process.cwd()`)
|
|
39
|
+
return process.cwd()
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
return realpathSync(resolve(trimmed))
|
|
43
|
+
} catch {
|
|
44
|
+
return resolve(trimmed)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Registers an agent session in the corresponding DSH workspace so it appears
|
|
50
|
+
* in the sidebar under its project instead of "Ungrouped" (未分组).
|
|
51
|
+
*/
|
|
52
|
+
export async function registerSessionInWorkspace(ctx, sessionId, cwd, logger) {
|
|
53
|
+
if (!sessionId || !cwd) return false
|
|
54
|
+
const targetSessionId = String(sessionId)
|
|
55
|
+
let realCwd = cwd
|
|
56
|
+
try {
|
|
57
|
+
realCwd = realpathSync(resolve(cwd))
|
|
58
|
+
} catch {
|
|
59
|
+
realCwd = resolve(cwd)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 1. Try Cordis service ctx.workspaceRegistry first
|
|
63
|
+
const registry = ctx?.get?.('workspaceRegistry') || ctx?.workspaceRegistry
|
|
64
|
+
if (registry) {
|
|
65
|
+
try {
|
|
66
|
+
let ws = null
|
|
67
|
+
if (typeof registry.resolveByPath === 'function') {
|
|
68
|
+
ws = await registry.resolveByPath(realCwd).catch(() => null)
|
|
69
|
+
if (!ws && realCwd !== cwd) {
|
|
70
|
+
ws = await registry.resolveByPath(cwd).catch(() => null)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (!ws && typeof registry.create === 'function') {
|
|
74
|
+
ws = await registry.create(realCwd).catch((err) => {
|
|
75
|
+
logger?.debug?.(`[dsh-messenger-gateway] workspaceRegistry.create('${realCwd}') failed: ${err?.message || err}`)
|
|
76
|
+
return null
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
if (ws && typeof ws.attachSession === 'function') {
|
|
80
|
+
await ws.attachSession(targetSessionId)
|
|
81
|
+
logger?.debug?.(`[dsh-messenger-gateway] attached session '${targetSessionId}' to workspace '${ws.path || realCwd}' via workspaceRegistry`)
|
|
82
|
+
return true
|
|
83
|
+
}
|
|
84
|
+
} catch (err) {
|
|
85
|
+
logger?.debug?.(`[dsh-messenger-gateway] workspaceRegistry attach error: ${err?.message || err}`)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 2. Fallback to atomic file write in ~/.dsh/storages/workspace.json
|
|
90
|
+
try {
|
|
91
|
+
const dshHome = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
92
|
+
const wsFile = path.join(dshHome, 'storages', 'workspace.json')
|
|
93
|
+
if (existsSync(wsFile)) {
|
|
94
|
+
const raw = await readFile(wsFile, 'utf8')
|
|
95
|
+
const data = JSON.parse(raw)
|
|
96
|
+
if (data && data.tables && data.tables.workspaces) {
|
|
97
|
+
let matchedId = null
|
|
98
|
+
for (const [id, w] of Object.entries(data.tables.workspaces)) {
|
|
99
|
+
if (!w || !w.path) continue
|
|
100
|
+
try {
|
|
101
|
+
if (realpathSync(resolve(w.path)) === realCwd) {
|
|
102
|
+
matchedId = id
|
|
103
|
+
break
|
|
104
|
+
}
|
|
105
|
+
} catch {
|
|
106
|
+
if (w.path === realCwd || w.path === cwd) {
|
|
107
|
+
matchedId = id
|
|
108
|
+
break
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const now = new Date().toISOString()
|
|
114
|
+
if (matchedId) {
|
|
115
|
+
const w = data.tables.workspaces[matchedId]
|
|
116
|
+
if (!Array.isArray(w.sessionIds)) w.sessionIds = []
|
|
117
|
+
if (!w.sessionIds.includes(targetSessionId)) {
|
|
118
|
+
w.sessionIds.push(targetSessionId)
|
|
119
|
+
w.updatedAt = now
|
|
120
|
+
await writeJsonAtomic(wsFile, data)
|
|
121
|
+
logger?.debug?.(`[dsh-messenger-gateway] registered session '${targetSessionId}' in workspace '${matchedId}' (${w.path}) via storage file`)
|
|
122
|
+
return true
|
|
123
|
+
}
|
|
124
|
+
return true
|
|
125
|
+
} else {
|
|
126
|
+
const newId = randomUUID()
|
|
127
|
+
const title = basename(realCwd) || realCwd
|
|
128
|
+
data.tables.workspaces[newId] = {
|
|
129
|
+
path: realCwd,
|
|
130
|
+
title,
|
|
131
|
+
sessionIds: [targetSessionId],
|
|
132
|
+
createdAt: now,
|
|
133
|
+
updatedAt: now,
|
|
134
|
+
}
|
|
135
|
+
if (data.global && Array.isArray(data.global.workspaceIds)) {
|
|
136
|
+
data.global.workspaceIds.push(newId)
|
|
137
|
+
}
|
|
138
|
+
await writeJsonAtomic(wsFile, data)
|
|
139
|
+
logger?.debug?.(`[dsh-messenger-gateway] created workspace '${newId}' (${realCwd}) and registered session '${targetSessionId}'`)
|
|
140
|
+
return true
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
} catch (err) {
|
|
145
|
+
logger?.debug?.(`[dsh-messenger-gateway] fallback workspace registration error: ${err?.message || err}`)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return false
|
|
149
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-messenger-gateway",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.21",
|
|
4
4
|
"description": "Telegram messenger bridge for DeepSeek Harness: sessions, steer, homes, inline asks, notify bridge, and optional TTS voice notes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|