@goodandready/dsh-messenger-gateway 0.4.18 → 0.4.20
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 +128 -126
- package/lib/gateway-commands.js +20 -2
- package/lib/gateway.js +4 -1
- package/lib/http.js +132 -28
- package/lib/index.js +13 -7
- package/lib/locales/en.js +4 -0
- package/lib/locales/zh.js +4 -0
- package/lib/updater.js +0 -1
- 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,128 @@
|
|
|
1
|
-
export const DEFAULT_TELEGRAM_COMMANDS = [
|
|
2
|
-
{ command: 'start', description: 'Connect and show greeting' },
|
|
3
|
-
{ command: 'help', description: 'Show commands help' },
|
|
4
|
-
{ command: 'new', description: 'Start a new agent session' },
|
|
5
|
-
{ command: 'whoami', description: 'Show your messenger user ID' },
|
|
6
|
-
{ command: 'stop', description: 'Interrupt current turn' },
|
|
7
|
-
{ command: 'pair', description: 'Approve pairing code: /pair CODE' },
|
|
8
|
-
{ command: 'sethome', description: 'Set home: /sethome [name]' },
|
|
9
|
-
{ command: 'home', description: 'List registered home channels' },
|
|
10
|
-
{ command: 'model', description: 'Interactive model selector' },
|
|
11
|
-
{ command: 'top', description: 'System resources: CPU, RAM, uptime' },
|
|
12
|
-
{ command: 'topic', description: 'Create forum topic: /topic <name>' },
|
|
13
|
-
{ command: 'status', description: 'Gateway and bot status' },
|
|
14
|
-
{ command: 'setalert', description: 'Designate channel for alerts' },
|
|
15
|
-
{ command: 'alert', description: 'Alert channel status: /alert [test]' },
|
|
16
|
-
{ command: 'keyboard', description: 'Toggle quick actions: /keyboard on|off' },
|
|
17
|
-
{ command: 'role', description: 'Switch persona: /role [name]' },
|
|
18
|
-
{ command: 'bind', description: 'Bind preset/persona to forum topic: /bind <name>' },
|
|
19
|
-
{ command: 'preset', description: 'Show or switch agent preset: /preset [name]' },
|
|
20
|
-
{ command: 'cron', description: 'Manage recurring reports: /cron' },
|
|
21
|
-
{ command: 'skills', description: 'List active tools & skills' },
|
|
22
|
-
{ command: 'tools', description: 'List active tools' },
|
|
23
|
-
{ command: 'fork', description: 'Fork session into new branch' },
|
|
24
|
-
{ command: 'export', description: 'Export history to Markdown' },
|
|
25
|
-
{ command: 'rewind', description: 'Rewind turns: /rewind [N]' },
|
|
26
|
-
{ command: '
|
|
27
|
-
{ command: '
|
|
28
|
-
{ command: '
|
|
29
|
-
{ command: '
|
|
30
|
-
{ command: '
|
|
31
|
-
{ command: '
|
|
32
|
-
{ command: '
|
|
33
|
-
{ command: '
|
|
34
|
-
]
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
command
|
|
46
|
-
|
|
47
|
-
seen.
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if (
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
description =
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
[{ text: '
|
|
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
|
-
|
|
1
|
+
export const DEFAULT_TELEGRAM_COMMANDS = [
|
|
2
|
+
{ command: 'start', description: 'Connect and show greeting' },
|
|
3
|
+
{ command: 'help', description: 'Show commands help' },
|
|
4
|
+
{ command: 'new', description: 'Start a new agent session' },
|
|
5
|
+
{ command: 'whoami', description: 'Show your messenger user ID' },
|
|
6
|
+
{ command: 'stop', description: 'Interrupt current turn' },
|
|
7
|
+
{ command: 'pair', description: 'Approve pairing code: /pair CODE' },
|
|
8
|
+
{ command: 'sethome', description: 'Set home: /sethome [name]' },
|
|
9
|
+
{ command: 'home', description: 'List registered home channels' },
|
|
10
|
+
{ command: 'model', description: 'Interactive model selector' },
|
|
11
|
+
{ command: 'top', description: 'System resources: CPU, RAM, uptime' },
|
|
12
|
+
{ command: 'topic', description: 'Create forum topic: /topic <name>' },
|
|
13
|
+
{ command: 'status', description: 'Gateway and bot status' },
|
|
14
|
+
{ command: 'setalert', description: 'Designate channel for alerts' },
|
|
15
|
+
{ command: 'alert', description: 'Alert channel status: /alert [test]' },
|
|
16
|
+
{ command: 'keyboard', description: 'Toggle quick actions: /keyboard on|off' },
|
|
17
|
+
{ command: 'role', description: 'Switch persona: /role [name]' },
|
|
18
|
+
{ command: 'bind', description: 'Bind preset/persona to forum topic: /bind <name>' },
|
|
19
|
+
{ command: 'preset', description: 'Show or switch agent preset: /preset [name]' },
|
|
20
|
+
{ command: 'cron', description: 'Manage recurring reports: /cron' },
|
|
21
|
+
{ command: 'skills', description: 'List active tools & skills' },
|
|
22
|
+
{ command: 'tools', description: 'List active tools' },
|
|
23
|
+
{ command: 'fork', description: 'Fork session into new branch' },
|
|
24
|
+
{ command: 'export', description: 'Export history to Markdown' },
|
|
25
|
+
{ command: 'rewind', description: 'Rewind turns: /rewind [N]' },
|
|
26
|
+
{ command: 'cwd', description: 'Show working directory: /cwd' },
|
|
27
|
+
{ command: 'files', description: 'Workspace file explorer: /files [dir]' },
|
|
28
|
+
{ command: 'get', description: 'Download file to messenger: /get <path>' },
|
|
29
|
+
{ command: 'remind', description: 'Set reminder: /remind <time> <text>' },
|
|
30
|
+
{ command: 'voice', description: 'Voice reply mode: /voice on|off|status' },
|
|
31
|
+
{ command: 'tts', description: 'Speech in this chat: /tts on|off|status' },
|
|
32
|
+
{ command: 'mute', description: 'Mute notifications in this chat' },
|
|
33
|
+
{ command: 'unmute', description: 'Unmute notifications in this chat' },
|
|
34
|
+
{ command: 'update', description: 'Check or install plugin update: /update [now]' },
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
export function normalizeTelegramCommands(commands) {
|
|
38
|
+
const source = Array.isArray(commands) && commands.length ? commands : DEFAULT_TELEGRAM_COMMANDS
|
|
39
|
+
const out = []
|
|
40
|
+
const seen = new Set()
|
|
41
|
+
for (const raw of source) {
|
|
42
|
+
if (!raw || typeof raw !== 'object') continue
|
|
43
|
+
let command = String(raw.command || '').trim().replace(/^\//, '')
|
|
44
|
+
const description = String(raw.description || '').trim()
|
|
45
|
+
if (!command || !description) continue
|
|
46
|
+
command = command.slice(0, 32).toLowerCase()
|
|
47
|
+
if (seen.has(command)) continue
|
|
48
|
+
seen.add(command)
|
|
49
|
+
out.push({ command, description: description.slice(0, 256) })
|
|
50
|
+
}
|
|
51
|
+
return out.length ? out : [...DEFAULT_TELEGRAM_COMMANDS]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function mergeDynamicCommands(baseCommands = DEFAULT_TELEGRAM_COMMANDS, dynamicCommands = [], maxTotal = 100) {
|
|
55
|
+
const normalizedBase = normalizeTelegramCommands(baseCommands)
|
|
56
|
+
const out = [...normalizedBase]
|
|
57
|
+
const seen = new Set(out.map((c) => c.command))
|
|
58
|
+
|
|
59
|
+
for (const item of dynamicCommands || []) {
|
|
60
|
+
if (out.length >= maxTotal) break
|
|
61
|
+
if (!item || typeof item !== 'object') continue
|
|
62
|
+
let command = String(item.command || item.name || '').trim().replace(/^\//, '').toLowerCase()
|
|
63
|
+
// Telegram format: lowercase alphanumeric and underscore only, 1-32 chars
|
|
64
|
+
command = command.replace(/[^a-z0-9_]/g, '_').slice(0, 32)
|
|
65
|
+
if (!command || seen.has(command)) continue
|
|
66
|
+
let description = String(item.description || item.title || `Skill ${command}`).trim()
|
|
67
|
+
if (!description) description = `Skill ${command}`
|
|
68
|
+
description = description.slice(0, 256)
|
|
69
|
+
seen.add(command)
|
|
70
|
+
out.push({ command, description })
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return out.slice(0, maxTotal)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function buildQuickActionsKeyboard() {
|
|
77
|
+
return {
|
|
78
|
+
keyboard: [
|
|
79
|
+
[{ text: '🔄 /new' }, { text: '🛑 /stop' }],
|
|
80
|
+
[{ text: '🎙️ /voice' }, { text: '📊 /status' }],
|
|
81
|
+
],
|
|
82
|
+
resize_keyboard: true,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export const REMOVE_REPLY_KEYBOARD = { remove_keyboard: true }
|
|
87
|
+
|
|
88
|
+
export const HELP_TEXT = [
|
|
89
|
+
'📖 <b>Messenger Gateway Help:</b>',
|
|
90
|
+
'',
|
|
91
|
+
'💬 <b>Session & Chat:</b>',
|
|
92
|
+
'• /help — show this command reference',
|
|
93
|
+
'• /new — start fresh session',
|
|
94
|
+
'• /stop — interrupt current response',
|
|
95
|
+
'• /model — interactive model selector (/model list)',
|
|
96
|
+
'• /role [name] — switch persona or role (/role list)',
|
|
97
|
+
'• /bind [role] — bind persona to topic / chat',
|
|
98
|
+
'• /preset [name] — bind preset to topic / chat',
|
|
99
|
+
'• /lang [en|zh] — switch user language',
|
|
100
|
+
'• /rewind [N] — rewind last N turns',
|
|
101
|
+
'• /fork — fork session into new branch',
|
|
102
|
+
'• /export — export history to Markdown',
|
|
103
|
+
'',
|
|
104
|
+
'🛠️ <b>Tools, Files & Cron:</b>',
|
|
105
|
+
'• /skills / /tools — list active tools & skills',
|
|
106
|
+
'• /cwd — show current working directory',
|
|
107
|
+
'• /files [dir] — workspace file explorer',
|
|
108
|
+
'• /get <path> — download file from workspace',
|
|
109
|
+
'• /remind <time> <text> — set reminder (/remind 10m check deploy)',
|
|
110
|
+
'• /cron <interval> <prompt> — recurring autonomous task',
|
|
111
|
+
'',
|
|
112
|
+
'⚙️ <b>Settings & Stats:</b>',
|
|
113
|
+
'• /status — gateway and active model status',
|
|
114
|
+
'• /top — system resource usage (RAM, uptime)',
|
|
115
|
+
'• /keyboard on|off — quick action keyboard',
|
|
116
|
+
'• /voice on|off|status — voice replies preference',
|
|
117
|
+
'• /tts on|off|status — speech synthesis in this chat',
|
|
118
|
+
'• /mute / /unmute — mute notifications in this chat',
|
|
119
|
+
'',
|
|
120
|
+
'🔒 <b>Access & Channels:</b>',
|
|
121
|
+
'• /whoami — your messenger user ID',
|
|
122
|
+
'• /pair CODE — approve pairing code',
|
|
123
|
+
'• /sethome [name] — set home notification channel',
|
|
124
|
+
'• /setalert — set alert channel',
|
|
125
|
+
].join('\n')
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
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)
|
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
|
|
|
@@ -510,7 +512,7 @@ export class Gateway {
|
|
|
510
512
|
async createChat(key, input, existingSessionId) {
|
|
511
513
|
const { provider, model } = this.resolveAgentModel()
|
|
512
514
|
const agentCfg = this.config.agent || {}
|
|
513
|
-
const cwd = agentCfg.cwd
|
|
515
|
+
const cwd = resolveEffectiveCwd(agentCfg.cwd, this.ctx.logger)
|
|
514
516
|
const self = this
|
|
515
517
|
const agents = this.ctx.get?.('agents') || this.ctx.agents
|
|
516
518
|
const targetSessionId = existingSessionId ? SessionId(existingSessionId) : SessionId(`msgw-${randomUUID()}`)
|
|
@@ -526,6 +528,7 @@ export class Gateway {
|
|
|
526
528
|
},
|
|
527
529
|
})
|
|
528
530
|
await handle.agent.whenIdle()
|
|
531
|
+
await registerSessionInWorkspace(this.ctx, targetSessionId, cwd, this.ctx.logger).catch(() => {})
|
|
529
532
|
const chat = {
|
|
530
533
|
key, agent: handle.agent, dispose: handle.dispose, busy: Promise.resolve(),
|
|
531
534
|
lastUsed: Date.now(), abort: undefined, pendingMedia: [], turnActive: false,
|
package/lib/http.js
CHANGED
|
@@ -74,14 +74,30 @@ export function isPrivateAddress(value) {
|
|
|
74
74
|
|
|
75
75
|
export const isLoopbackOrLan = isPrivateAddress
|
|
76
76
|
|
|
77
|
-
export function
|
|
77
|
+
export function getConnection(ctx) {
|
|
78
|
+
try {
|
|
79
|
+
const fromCtx = ctx?.reflect?.get
|
|
80
|
+
? (ctx.reflect.get('connection') || ctx?.connection)
|
|
81
|
+
: (ctx?.get ? (ctx.get('connection') || ctx?.connection) : Reflect.get(ctx || {}, 'connection'))
|
|
82
|
+
if (fromCtx) return fromCtx
|
|
83
|
+
if (ctx?.root) {
|
|
84
|
+
return getConnection(ctx.root)
|
|
85
|
+
}
|
|
86
|
+
return undefined
|
|
87
|
+
} catch {
|
|
88
|
+
return undefined
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function isTrustedSettingsRequest(req, expectedSecret, ctx = null) {
|
|
78
93
|
const remote = req?.socket?.remoteAddress
|
|
79
|
-
const host = String(req?.headers?.host || '')
|
|
94
|
+
const host = String(req?.headers?.host || req?.headers?.['x-forwarded-host'] || '')
|
|
80
95
|
if (!host) return false
|
|
81
96
|
|
|
82
97
|
const site = String(req?.headers?.['sec-fetch-site'] || '').toLowerCase()
|
|
83
98
|
if (site === 'cross-site') return false
|
|
84
99
|
|
|
100
|
+
// 1. Explicit secret authentication (Bearer token or x-webhook-secret header)
|
|
85
101
|
const secret = String(expectedSecret || '').trim()
|
|
86
102
|
if (secret) {
|
|
87
103
|
const authHeader = req?.headers?.authorization || ''
|
|
@@ -93,49 +109,108 @@ export function isTrustedSettingsRequest(req, expectedSecret) {
|
|
|
93
109
|
}
|
|
94
110
|
}
|
|
95
111
|
|
|
96
|
-
|
|
97
|
-
if (remote !== undefined && !isPrivateAddress(remote)) {
|
|
98
|
-
return false
|
|
99
|
-
}
|
|
112
|
+
const hostName = host.split(':')[0].toLowerCase().replace(/^\[|\]$/g, '')
|
|
100
113
|
|
|
101
114
|
// If host is loopback (localhost/127.0.0.1/::1), remote address must also be loopback
|
|
102
|
-
const hostName = host.split(':')[0].toLowerCase().replace(/^\[|\]$/g, '')
|
|
103
115
|
if (isLoopback(hostName) && remote !== undefined && !isLoopback(remote)) {
|
|
104
116
|
return false
|
|
105
117
|
}
|
|
106
118
|
|
|
107
|
-
|
|
108
|
-
if (
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
119
|
+
// 2. Local loopback remote address (CLI, tests, local host processes)
|
|
120
|
+
if (remote !== undefined && isLoopback(remote)) {
|
|
121
|
+
const origin = String(req?.headers?.origin || '')
|
|
122
|
+
if (origin) {
|
|
123
|
+
try {
|
|
124
|
+
const url = new URL(origin)
|
|
125
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
126
|
+
if (url.host.toLowerCase() !== host.toLowerCase() && !isLoopback(url.hostname)) return false
|
|
127
|
+
} catch {
|
|
128
|
+
return false
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const referer = String(req?.headers?.referer || '')
|
|
132
|
+
if (referer) {
|
|
133
|
+
try {
|
|
134
|
+
const url = new URL(referer)
|
|
135
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
136
|
+
if (url.host.toLowerCase() !== host.toLowerCase() && !isLoopback(url.hostname)) return false
|
|
137
|
+
} catch {
|
|
138
|
+
return false
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return true
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// 3. Mock/unit-test requests without socket where host is loopback and browser origin/referer/site is verified
|
|
145
|
+
if (remote === undefined && isLoopback(hostName)) {
|
|
146
|
+
const origin = String(req?.headers?.origin || '')
|
|
147
|
+
if (origin) {
|
|
148
|
+
try {
|
|
149
|
+
const url = new URL(origin)
|
|
150
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
151
|
+
return url.host.toLowerCase() === host.toLowerCase() || isLoopback(url.hostname)
|
|
152
|
+
} catch {
|
|
153
|
+
return false
|
|
154
|
+
}
|
|
115
155
|
}
|
|
156
|
+
const referer = String(req?.headers?.referer || '')
|
|
157
|
+
if (referer) {
|
|
158
|
+
try {
|
|
159
|
+
const url = new URL(referer)
|
|
160
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
161
|
+
return url.host.toLowerCase() === host.toLowerCase() || isLoopback(url.hostname)
|
|
162
|
+
} catch {
|
|
163
|
+
return false
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (site === 'same-origin') {
|
|
167
|
+
return true
|
|
168
|
+
}
|
|
169
|
+
return false
|
|
116
170
|
}
|
|
117
171
|
|
|
118
|
-
|
|
119
|
-
|
|
172
|
+
// 4. DSH Connection Service session authentication (DSH Web UI browser session) (#157)
|
|
173
|
+
const conn = getConnection(ctx) || req?.connectionService || req?.connection
|
|
174
|
+
if (conn && typeof conn.requestRejection === 'function') {
|
|
175
|
+
let rejection
|
|
120
176
|
try {
|
|
121
|
-
|
|
122
|
-
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
123
|
-
return url.host.toLowerCase() === host.toLowerCase()
|
|
177
|
+
rejection = conn.requestRejection(req)
|
|
124
178
|
} catch {
|
|
125
179
|
return false
|
|
126
180
|
}
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
181
|
+
if (rejection === undefined) {
|
|
182
|
+
// DSH peer session is authenticated! Enforce same-origin CSRF protection
|
|
183
|
+
const origin = String(req?.headers?.origin || '')
|
|
184
|
+
if (origin) {
|
|
185
|
+
try {
|
|
186
|
+
const url = new URL(origin)
|
|
187
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
188
|
+
if (url.host.toLowerCase() !== host.toLowerCase()) return false
|
|
189
|
+
} catch {
|
|
190
|
+
return false
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const referer = String(req?.headers?.referer || '')
|
|
194
|
+
if (referer) {
|
|
195
|
+
try {
|
|
196
|
+
const url = new URL(referer)
|
|
197
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
|
|
198
|
+
if (url.host.toLowerCase() !== host.toLowerCase()) return false
|
|
199
|
+
} catch {
|
|
200
|
+
return false
|
|
201
|
+
}
|
|
202
|
+
}
|
|
131
203
|
return true
|
|
132
204
|
}
|
|
205
|
+
return false
|
|
133
206
|
}
|
|
134
207
|
|
|
135
|
-
|
|
208
|
+
// 5. Remote caller (LAN RFC 1918 or WAN) without secret and without DSH connection session:
|
|
209
|
+
// LAN is NOT authentication! Fail-closed (#157).
|
|
210
|
+
return false
|
|
136
211
|
}
|
|
137
212
|
|
|
138
|
-
export function isAuthorizedMessengerRequest(req, webhooksConfig) {
|
|
213
|
+
export function isAuthorizedMessengerRequest(req, webhooksConfig, ctx = null) {
|
|
139
214
|
const site = String(req?.headers?.['sec-fetch-site'] || '').toLowerCase()
|
|
140
215
|
if (site === 'cross-site') return false
|
|
141
216
|
|
|
@@ -150,12 +225,41 @@ export function isAuthorizedMessengerRequest(req, webhooksConfig) {
|
|
|
150
225
|
}
|
|
151
226
|
}
|
|
152
227
|
|
|
228
|
+
const host = String(req?.headers?.host || req?.headers?.['x-forwarded-host'] || '')
|
|
229
|
+
const hostName = host.split(':')[0].toLowerCase().replace(/^\[|\]$/g, '')
|
|
153
230
|
const remote = req?.socket?.remoteAddress
|
|
154
|
-
|
|
231
|
+
|
|
232
|
+
if (isLoopback(hostName) && remote !== undefined && !isLoopback(remote)) {
|
|
155
233
|
return false
|
|
156
234
|
}
|
|
157
235
|
|
|
158
|
-
|
|
236
|
+
if (remote !== undefined && isLoopback(remote)) {
|
|
237
|
+
return true
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (remote === undefined && isLoopback(hostName)) {
|
|
241
|
+
const origin = String(req?.headers?.origin || '')
|
|
242
|
+
if (origin) {
|
|
243
|
+
try {
|
|
244
|
+
const url = new URL(origin)
|
|
245
|
+
return url.host.toLowerCase() === host.toLowerCase() || isLoopback(url.hostname)
|
|
246
|
+
} catch {
|
|
247
|
+
return false
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return false
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const conn = getConnection(ctx) || req?.connectionService || req?.connection
|
|
254
|
+
if (conn && typeof conn.requestRejection === 'function') {
|
|
255
|
+
try {
|
|
256
|
+
if (conn.requestRejection(req) === undefined) return true
|
|
257
|
+
} catch {
|
|
258
|
+
return false
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return false
|
|
159
263
|
}
|
|
160
264
|
|
|
161
265
|
export function timingSafeCompare(a, b) {
|
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,
|
|
@@ -124,7 +130,7 @@ function registerMessengerRoute(ctx, getGw, path, action, source) {
|
|
|
124
130
|
kind: 'exact', path,
|
|
125
131
|
handler: async (req, res) => {
|
|
126
132
|
if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
|
|
127
|
-
if (!isAuthorizedMessengerRequest(req, source?.()?.webhooks)) {
|
|
133
|
+
if (!isAuthorizedMessengerRequest(req, source?.()?.webhooks, ctx)) {
|
|
128
134
|
return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
129
135
|
}
|
|
130
136
|
let payload
|
|
@@ -458,7 +464,7 @@ export function apply(ctx, config) {
|
|
|
458
464
|
kind: 'exact', path: '/dsh-messenger-gateway/status',
|
|
459
465
|
handler: async (req, res) => {
|
|
460
466
|
if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
|
|
461
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
467
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
462
468
|
const gw = getGw()
|
|
463
469
|
const botInfo = gw?.getBotInfo?.() || {}
|
|
464
470
|
const uptimeSec = gw?.stats?.startedAt ? Math.max(0, Math.round((Date.now() - gw.stats.startedAt) / 1000)) : 0
|
|
@@ -497,7 +503,7 @@ export function apply(ctx, config) {
|
|
|
497
503
|
kind: 'exact', path: '/dsh-messenger-gateway/smoke',
|
|
498
504
|
handler: async (req, res) => {
|
|
499
505
|
if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
|
|
500
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
506
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
501
507
|
const gw = getGw()
|
|
502
508
|
if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
|
|
503
509
|
const parsed = await readJsonSafe(req, res, 65536)
|
|
@@ -573,7 +579,7 @@ export function apply(ctx, config) {
|
|
|
573
579
|
kind: 'exact', path: '/dsh-messenger-gateway/config',
|
|
574
580
|
handler: async (req, res) => {
|
|
575
581
|
if (req.method !== 'GET' && req.method !== 'PUT') return writeJson(res, 405, { ok: false, error: 'GET or PUT' })
|
|
576
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
582
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
577
583
|
if (req.method === 'GET') return writeJson(res, 200, { ok: true, config: publicConfig(source(), getGw(), ctx) })
|
|
578
584
|
if (!settingsApi?.isReady?.()) return writeJson(res, 503, { ok: false, error: 'settings not ready' })
|
|
579
585
|
const parsedConfig = await readJsonSafe(req, res, 1_048_576)
|
|
@@ -616,7 +622,7 @@ export function apply(ctx, config) {
|
|
|
616
622
|
kind: 'exact', path: '/dsh-messenger-gateway/pairing',
|
|
617
623
|
handler: async (req, res) => {
|
|
618
624
|
if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
|
|
619
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
625
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
620
626
|
const gw = getGw()
|
|
621
627
|
if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
|
|
622
628
|
writeJson(res, 200, {
|
|
@@ -631,7 +637,7 @@ export function apply(ctx, config) {
|
|
|
631
637
|
kind: 'exact', path: '/dsh-messenger-gateway/pairing/approve',
|
|
632
638
|
handler: async (req, res) => {
|
|
633
639
|
if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
|
|
634
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
640
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
635
641
|
const gw = getGw()
|
|
636
642
|
if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
|
|
637
643
|
const parsed = await readJsonSafe(req, res, 65536)
|
|
@@ -645,7 +651,7 @@ export function apply(ctx, config) {
|
|
|
645
651
|
kind: 'exact', path: '/dsh-messenger-gateway/pairing/reject',
|
|
646
652
|
handler: async (req, res) => {
|
|
647
653
|
if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
|
|
648
|
-
if (!isTrustedSettingsRequest(req, source().webhooks?.secret)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
654
|
+
if (!isTrustedSettingsRequest(req, source().webhooks?.secret, ctx)) return writeJson(res, 403, { ok: false, error: 'forbidden' })
|
|
649
655
|
const gw = getGw()
|
|
650
656
|
if (!gw) return writeJson(res, 503, { ok: false, error: 'gateway not running' })
|
|
651
657
|
const parsed = await readJsonSafe(req, res, 65536)
|
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/updater.js
CHANGED
|
@@ -4,7 +4,6 @@ import { spawn } from 'node:child_process'
|
|
|
4
4
|
import { homedir } from 'node:os'
|
|
5
5
|
import { basename, dirname, isAbsolute, resolve } from 'node:path'
|
|
6
6
|
import { fileURLToPath } from 'node:url'
|
|
7
|
-
import { isTrustedSettingsRequest } from './http.js'
|
|
8
7
|
|
|
9
8
|
const UPDATE_HEADER = 'x-dsh-plugin-update'
|
|
10
9
|
const UPDATE_TIMEOUT_MS = 180_000
|
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.20",
|
|
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",
|