@goodandready/dsh-messenger-gateway 0.4.19 → 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 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: 'files', description: 'Workspace file explorer: /files [dir]' },
27
- { command: 'get', description: 'Download file to messenger: /get <path>' },
28
- { command: 'remind', description: 'Set reminder: /remind <time> <text>' },
29
- { command: 'voice', description: 'Voice reply mode: /voice on|off|status' },
30
- { command: 'tts', description: 'Speech in this chat: /tts on|off|status' },
31
- { command: 'mute', description: 'Mute notifications in this chat' },
32
- { command: 'unmute', description: 'Unmute notifications in this chat' },
33
- { command: 'update', description: 'Check or install plugin update: /update [now]' },
34
- ]
35
-
36
- export function normalizeTelegramCommands(commands) {
37
- const source = Array.isArray(commands) && commands.length ? commands : DEFAULT_TELEGRAM_COMMANDS
38
- const out = []
39
- const seen = new Set()
40
- for (const raw of source) {
41
- if (!raw || typeof raw !== 'object') continue
42
- let command = String(raw.command || '').trim().replace(/^\//, '')
43
- const description = String(raw.description || '').trim()
44
- if (!command || !description) continue
45
- command = command.slice(0, 32).toLowerCase()
46
- if (seen.has(command)) continue
47
- seen.add(command)
48
- out.push({ command, description: description.slice(0, 256) })
49
- }
50
- return out.length ? out : [...DEFAULT_TELEGRAM_COMMANDS]
51
- }
52
-
53
- export function mergeDynamicCommands(baseCommands = DEFAULT_TELEGRAM_COMMANDS, dynamicCommands = [], maxTotal = 100) {
54
- const normalizedBase = normalizeTelegramCommands(baseCommands)
55
- const out = [...normalizedBase]
56
- const seen = new Set(out.map((c) => c.command))
57
-
58
- for (const item of dynamicCommands || []) {
59
- if (out.length >= maxTotal) break
60
- if (!item || typeof item !== 'object') continue
61
- let command = String(item.command || item.name || '').trim().replace(/^\//, '').toLowerCase()
62
- // Telegram format: lowercase alphanumeric and underscore only, 1-32 chars
63
- command = command.replace(/[^a-z0-9_]/g, '_').slice(0, 32)
64
- if (!command || seen.has(command)) continue
65
- let description = String(item.description || item.title || `Skill ${command}`).trim()
66
- if (!description) description = `Skill ${command}`
67
- description = description.slice(0, 256)
68
- seen.add(command)
69
- out.push({ command, description })
70
- }
71
-
72
- return out.slice(0, maxTotal)
73
- }
74
-
75
- export function buildQuickActionsKeyboard() {
76
- return {
77
- keyboard: [
78
- [{ text: '🔄 /new' }, { text: '🛑 /stop' }],
79
- [{ text: '🎙️ /voice' }, { text: '📊 /status' }],
80
- ],
81
- resize_keyboard: true,
82
- }
83
- }
84
-
85
- export const REMOVE_REPLY_KEYBOARD = { remove_keyboard: true }
86
-
87
- export const HELP_TEXT = [
88
- '📖 <b>Messenger Gateway Help:</b>',
89
- '',
90
- '💬 <b>Session & Chat:</b>',
91
- '• /help — show this command reference',
92
- '• /new — start fresh session',
93
- '• /stop — interrupt current response',
94
- '• /model — interactive model selector (/model list)',
95
- '• /role [name] — switch persona or role (/role list)',
96
- '• /bind [role] — bind persona to topic / chat',
97
- '• /preset [name] — bind preset to topic / chat',
98
- '• /lang [en|zh] — switch user language',
99
- '• /rewind [N] — rewind last N turns',
100
- '• /fork — fork session into new branch',
101
- '• /export — export history to Markdown',
102
- '',
103
- '🛠️ <b>Tools, Files & Cron:</b>',
104
- '• /skills / /tools — list active tools & skills',
105
- '• /files [dir] — workspace file explorer',
106
- '• /get <path> — download file from workspace',
107
- '• /remind <time> <text> — set reminder (/remind 10m check deploy)',
108
- '• /cron <interval> <prompt> — recurring autonomous task',
109
- '',
110
- '⚙️ <b>Settings & Stats:</b>',
111
- '• /status — gateway and active model status',
112
- '• /top — system resource usage (RAM, uptime)',
113
- '• /keyboard on|off — quick action keyboard',
114
- '• /voice on|off|status — voice replies preference',
115
- '• /tts on|off|status — speech synthesis in this chat',
116
- '• /mute / /unmute — mute notifications in this chat',
117
- '',
118
- '🔒 <b>Access & Channels:</b>',
119
- '• /whoami — your messenger user ID',
120
- '• /pair CODE — approve pairing code',
121
- '• /sethome [name] — set home notification channel',
122
- '• /setalert — set alert channel',
123
- ].join('\n')
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
+
@@ -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 || process.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 || process.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 || process.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/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': '设置提醒或定时器',
@@ -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.19",
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",