@goodandready/dsh-messenger-gateway 0.4.25 → 0.4.27
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/commands.js +10 -0
- package/lib/config.js +11 -0
- package/lib/cost-tracker.js +228 -0
- package/lib/gateway-commands.js +203 -6
- package/lib/gateway-turn.js +63 -1
- package/lib/gateway.js +57 -2
- package/lib/memory-brain.js +273 -0
- package/lib/outbox.js +262 -0
- package/lib/workspace.js +112 -1
- package/package.json +1 -1
package/lib/commands.js
CHANGED
|
@@ -24,6 +24,11 @@ export const DEFAULT_TELEGRAM_COMMANDS = [
|
|
|
24
24
|
{ command: 'fork', description: 'Fork session into new branch' },
|
|
25
25
|
{ command: 'export', description: 'Export history to Markdown' },
|
|
26
26
|
{ command: 'rewind', description: 'Rewind turns: /rewind [N]' },
|
|
27
|
+
{ command: 'project', description: 'Bind or show topic workspace: /project' },
|
|
28
|
+
{ command: 'memory', description: 'User memory facts: /memory [add <fact>]' },
|
|
29
|
+
{ command: 'forget', description: 'Forget user memory: /forget <id|all>' },
|
|
30
|
+
{ command: 'outbox', description: 'Outbox queue & DLQ: /outbox [retry|clear]' },
|
|
31
|
+
{ command: 'cost', description: 'Session token usage and estimated cost' },
|
|
27
32
|
{ command: 'cwd', description: 'Show working directory: /cwd' },
|
|
28
33
|
{ command: 'files', description: 'Workspace file explorer: /files [dir]' },
|
|
29
34
|
{ command: 'get', description: 'Download file to messenger: /get <path>' },
|
|
@@ -104,6 +109,11 @@ export const HELP_TEXT = [
|
|
|
104
109
|
'',
|
|
105
110
|
'🛠️ <b>Tools, Files & Cron:</b>',
|
|
106
111
|
'• /skills / /tools — list active tools & skills',
|
|
112
|
+
'• /project — topic workspace binding (/project bind <path>)',
|
|
113
|
+
'• /memory — show remembered facts about you (/memory add <fact>)',
|
|
114
|
+
'• /forget <id|all> — delete stored user facts',
|
|
115
|
+
'• /outbox — transactional queue & DLQ (/outbox [retry|clear])',
|
|
116
|
+
'• /cost — session token usage, breakdown & estimated cost',
|
|
107
117
|
'• /cwd — show current working directory',
|
|
108
118
|
'• /files [dir] — workspace file explorer',
|
|
109
119
|
'• /get <path> — download file from workspace',
|
package/lib/config.js
CHANGED
|
@@ -58,6 +58,8 @@ export const PluginConfig = z.object({
|
|
|
58
58
|
.description('mirror: TTS when inbound was voice; always/off override (per-user /voice wins)'),
|
|
59
59
|
quickActions: z.boolean().default(false).description('Show quick actions keyboard in Telegram (/new, /stop, /voice, /status)'),
|
|
60
60
|
artifactPreviews: z.boolean().default(true).description('Render diagrams and formatted tables as previews'),
|
|
61
|
+
costFooter: z.boolean().default(false).description('Append compact execution & cost footer to bot replies (e.g. ⏱️ 2.4s · 1.8k tokens · deepseek-chat)'),
|
|
62
|
+
budgetAlertThresholdUsd: z.number().default(0).description('Session budget warning threshold in USD (0 = disabled)'),
|
|
61
63
|
notifyBridge: z.object({
|
|
62
64
|
enabled: z.boolean().default(false),
|
|
63
65
|
events: z.array(z.string()).default(['task_done', 'error']),
|
|
@@ -103,6 +105,15 @@ export const PluginConfig = z.object({
|
|
|
103
105
|
maxChars: z.number().default(4000),
|
|
104
106
|
voiceSummary: z.boolean().default(false).description('Speak concise TL;DR summary while full text is sent to chat'),
|
|
105
107
|
}).volatile(),
|
|
108
|
+
memory: z.object({
|
|
109
|
+
enabled: z.boolean().default(true),
|
|
110
|
+
baseUrl: z.string().default('').description('Base URL for dsh-memory-brain service (default http://127.0.0.1:28080)'),
|
|
111
|
+
tokenEnv: z.string().default('MEMORY_BRAIN_TOKEN').description('Environment variable name containing the bearer token'),
|
|
112
|
+
token: z.string().role('secret').default('').description('Explicit bearer token if not using tokenEnv'),
|
|
113
|
+
autoInject: z.boolean().default(true).description('Automatically retrieve and inject user memories into agent turn context'),
|
|
114
|
+
budget: z.number().default(2000).description('Character budget for injected memories'),
|
|
115
|
+
timeoutMs: z.number().default(3500).description('HTTP request timeout in ms for memory-brain calls'),
|
|
116
|
+
}).default({ enabled: true }).volatile(),
|
|
106
117
|
agent: z.object({
|
|
107
118
|
provider: z.string().default(''),
|
|
108
119
|
model: z.string().default(''),
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token usage and cost tracker in messenger sessions (dsh-cost-meter bridge, #156).
|
|
3
|
+
*
|
|
4
|
+
* Provides:
|
|
5
|
+
* - Accurate token extraction from turn events and DSH session projections.
|
|
6
|
+
* - Model cost estimation using standard rate cards and dsh-cost-meter tariffs.
|
|
7
|
+
* - Compact response footer (e.g. ⏱️ 2.4s · 1.8k tokens (~$0.004) · deepseek-chat).
|
|
8
|
+
* - Detailed `/cost` command with session breakdown and daily budget tracking.
|
|
9
|
+
* - Budget threshold alerts when nearing session limits.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { escapeHtml } from './telegram-format.js'
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_MODEL_RATES = {
|
|
15
|
+
'deepseek-chat': { input: 0.44, output: 1.32, cacheRead: 0.014, cacheWrite: 0.44 },
|
|
16
|
+
'deepseek-v3': { input: 0.44, output: 1.32, cacheRead: 0.014, cacheWrite: 0.44 },
|
|
17
|
+
'deepseek-reasoner': { input: 1.32, output: 3.96, cacheRead: 0.044, cacheWrite: 1.32 },
|
|
18
|
+
'deepseek-r1': { input: 1.32, output: 3.96, cacheRead: 0.044, cacheWrite: 1.32 },
|
|
19
|
+
'gpt-4o': { input: 2.50, output: 10.00, cacheRead: 1.25, cacheWrite: 2.50 },
|
|
20
|
+
'gpt-4o-mini': { input: 0.15, output: 0.60, cacheRead: 0.075, cacheWrite: 0.15 },
|
|
21
|
+
'claude-3-5-sonnet': { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
|
|
22
|
+
'fallback': { input: 0.50, output: 1.50, cacheRead: 0.05, cacheWrite: 0.50 },
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function resolveModelRates(modelId) {
|
|
26
|
+
if (!modelId || typeof modelId !== 'string') return DEFAULT_MODEL_RATES.fallback
|
|
27
|
+
const clean = modelId.toLowerCase().split('/').pop()
|
|
28
|
+
for (const [key, rates] of Object.entries(DEFAULT_MODEL_RATES)) {
|
|
29
|
+
if (clean.includes(key)) return rates
|
|
30
|
+
}
|
|
31
|
+
return DEFAULT_MODEL_RATES.fallback
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function normalizeUsage(rawUsage) {
|
|
35
|
+
if (!rawUsage || typeof rawUsage !== 'object') {
|
|
36
|
+
return {
|
|
37
|
+
inputTokens: 0,
|
|
38
|
+
outputTokens: 0,
|
|
39
|
+
cacheReadTokens: 0,
|
|
40
|
+
cacheWriteTokens: 0,
|
|
41
|
+
totalTokens: 0,
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const inputTokens = Number(rawUsage.inputTokens || rawUsage.prompt_tokens || rawUsage.promptTokens || rawUsage.input || 0)
|
|
46
|
+
const outputTokens = Number(rawUsage.outputTokens || rawUsage.completion_tokens || rawUsage.completionTokens || rawUsage.output || 0)
|
|
47
|
+
const cacheReadTokens = Number(rawUsage.cacheReadTokens || rawUsage.cache_read_tokens || rawUsage.cached_tokens || 0)
|
|
48
|
+
const cacheWriteTokens = Number(rawUsage.cacheWriteTokens || rawUsage.cache_creation_input_tokens || 0)
|
|
49
|
+
const totalTokens = Number(rawUsage.totalTokens || rawUsage.total_tokens || (inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens))
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
inputTokens,
|
|
53
|
+
outputTokens,
|
|
54
|
+
cacheReadTokens,
|
|
55
|
+
cacheWriteTokens,
|
|
56
|
+
totalTokens,
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function calculateEstimatedCostUsd(usage, modelId) {
|
|
61
|
+
const norm = normalizeUsage(usage)
|
|
62
|
+
const rates = resolveModelRates(modelId)
|
|
63
|
+
|
|
64
|
+
const inputCost = (norm.inputTokens * rates.input) / 1_000_000
|
|
65
|
+
const outputCost = (norm.outputTokens * rates.output) / 1_000_000
|
|
66
|
+
const cacheReadCost = (norm.cacheReadTokens * rates.cacheRead) / 1_000_000
|
|
67
|
+
const cacheWriteCost = (norm.cacheWriteTokens * rates.cacheWrite) / 1_000_000
|
|
68
|
+
|
|
69
|
+
return inputCost + outputCost + cacheReadCost + cacheWriteCost
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function formatTokenCount(n) {
|
|
73
|
+
const count = Number(n) || 0
|
|
74
|
+
if (count < 1000) return String(count)
|
|
75
|
+
const k = count / 1000
|
|
76
|
+
return (k >= 10 ? k.toFixed(0) : k.toFixed(1)) + 'k'
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function formatDurationSeconds(ms) {
|
|
80
|
+
const sec = Math.max(0.1, (Number(ms) || 0) / 1000)
|
|
81
|
+
return sec >= 10 ? `${sec.toFixed(0)}s` : `${sec.toFixed(1)}s`
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function formatCostUsd(usd) {
|
|
85
|
+
const val = Number(usd) || 0
|
|
86
|
+
if (val <= 0) return '$0.00'
|
|
87
|
+
if (val < 0.001) return '<$0.001'
|
|
88
|
+
return `~$${val.toFixed(4)}`
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function formatCostFooter({ durationMs, usage, model }) {
|
|
92
|
+
const norm = normalizeUsage(usage)
|
|
93
|
+
if (!norm.totalTokens && !durationMs) return ''
|
|
94
|
+
|
|
95
|
+
const durStr = formatDurationSeconds(durationMs)
|
|
96
|
+
const tokenStr = formatTokenCount(norm.totalTokens)
|
|
97
|
+
const cost = calculateEstimatedCostUsd(norm, model)
|
|
98
|
+
const costStr = formatCostUsd(cost)
|
|
99
|
+
const modelName = (model || 'model').split('/').pop()
|
|
100
|
+
|
|
101
|
+
return `\n\n<i>⏱️ ${durStr} · ${tokenStr} tokens (${costStr}) · ${escapeHtml(modelName)}</i>`
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function extractSessionStats(chat) {
|
|
105
|
+
let promptTokens = 0
|
|
106
|
+
let completionTokens = 0
|
|
107
|
+
let cachedTokens = 0
|
|
108
|
+
let totalTokens = 0
|
|
109
|
+
let turnsCount = 0
|
|
110
|
+
|
|
111
|
+
// 1. Try DSH session projections if available
|
|
112
|
+
const session = chat?.agent?.session
|
|
113
|
+
let projection = null
|
|
114
|
+
try {
|
|
115
|
+
if (typeof session?.projection === 'function') {
|
|
116
|
+
projection = session.projection('costByModel')
|
|
117
|
+
}
|
|
118
|
+
} catch {
|
|
119
|
+
/* projection not registered or session closed */
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (projection?.models && Array.isArray(projection.models)) {
|
|
123
|
+
for (const m of projection.models) {
|
|
124
|
+
if (m.slots && typeof m.slots === 'object') {
|
|
125
|
+
for (const slot of Object.values(m.slots)) {
|
|
126
|
+
promptTokens += Number(slot.uncachedInputTokens || 0)
|
|
127
|
+
completionTokens += Number(slot.outputTokens || 0)
|
|
128
|
+
cachedTokens += Number(slot.cacheReadTokens || 0)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (Array.isArray(projection.turns)) {
|
|
133
|
+
turnsCount = projection.turns.length
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// 2. Accumulate chat turn metrics if projection empty
|
|
138
|
+
if (!promptTokens && !completionTokens && chat?.turnStats) {
|
|
139
|
+
promptTokens = chat.turnStats.inputTokens || 0
|
|
140
|
+
completionTokens = chat.turnStats.outputTokens || 0
|
|
141
|
+
cachedTokens = chat.turnStats.cacheReadTokens || 0
|
|
142
|
+
turnsCount = chat.turnStats.turnsCount || 0
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// 3. Fallback to last turn usage if available
|
|
146
|
+
if (!promptTokens && !completionTokens && chat?.lastTurnUsage) {
|
|
147
|
+
const lastNorm = normalizeUsage(chat.lastTurnUsage)
|
|
148
|
+
promptTokens = lastNorm.inputTokens
|
|
149
|
+
completionTokens = lastNorm.outputTokens
|
|
150
|
+
cachedTokens = lastNorm.cacheReadTokens
|
|
151
|
+
turnsCount = 1
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
totalTokens = promptTokens + completionTokens + cachedTokens
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
promptTokens,
|
|
158
|
+
completionTokens,
|
|
159
|
+
cachedTokens,
|
|
160
|
+
totalTokens,
|
|
161
|
+
turnsCount,
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function formatSessionCostReport({ chat, config, model }) {
|
|
166
|
+
const stats = extractSessionStats(chat)
|
|
167
|
+
const activeModel = model || config?.agent?.model || 'deepseek-chat'
|
|
168
|
+
const costUsd = calculateEstimatedCostUsd({
|
|
169
|
+
inputTokens: stats.promptTokens,
|
|
170
|
+
outputTokens: stats.completionTokens,
|
|
171
|
+
cacheReadTokens: stats.cachedTokens,
|
|
172
|
+
}, activeModel)
|
|
173
|
+
|
|
174
|
+
const budgetThreshold = Number(config?.telegram?.budgetAlertThresholdUsd || 0)
|
|
175
|
+
|
|
176
|
+
const lines = [
|
|
177
|
+
'📊 <b>Session Token & Cost Meter:</b>',
|
|
178
|
+
`• Active Model: <code>${escapeHtml(activeModel)}</code>`,
|
|
179
|
+
`• Total Tokens: <b>${formatTokenCount(stats.totalTokens)}</b> (${stats.totalTokens.toLocaleString()})`,
|
|
180
|
+
` ├─ Prompt (input): ${formatTokenCount(stats.promptTokens)}`,
|
|
181
|
+
` ├─ Completion (output): ${formatTokenCount(stats.completionTokens)}`,
|
|
182
|
+
` └─ Cached read: ${formatTokenCount(stats.cachedTokens)}`,
|
|
183
|
+
`• Completed Turns: <b>${stats.turnsCount}</b>`,
|
|
184
|
+
`• Estimated Cost: <b>${formatCostUsd(costUsd)}</b> USD`,
|
|
185
|
+
]
|
|
186
|
+
|
|
187
|
+
if (budgetThreshold > 0) {
|
|
188
|
+
const remaining = Math.max(0, budgetThreshold - costUsd)
|
|
189
|
+
const pct = Math.min(100, (costUsd / budgetThreshold) * 100).toFixed(1)
|
|
190
|
+
lines.push(
|
|
191
|
+
'',
|
|
192
|
+
'🎯 <b>Budget Tracking:</b>',
|
|
193
|
+
`• Budget Threshold: <b>$${budgetThreshold.toFixed(2)}</b>`,
|
|
194
|
+
`• Consumed: <b>${pct}%</b>`,
|
|
195
|
+
`• Remaining: <b>$${remaining.toFixed(4)}</b>`,
|
|
196
|
+
)
|
|
197
|
+
if (costUsd >= budgetThreshold) {
|
|
198
|
+
lines.push('⚠️ <b>Budget threshold reached!</b> Consider using `/new` to reset context.')
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
lines.push('', '<i>Run <code>/cost</code> anytime to check current session spend.</i>')
|
|
203
|
+
return lines.join('\n')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function checkBudgetThreshold({ currentSpendUsd, thresholdUsd }) {
|
|
207
|
+
const threshold = Number(thresholdUsd) || 0
|
|
208
|
+
if (threshold <= 0) return null
|
|
209
|
+
const spend = Number(currentSpendUsd) || 0
|
|
210
|
+
|
|
211
|
+
if (spend >= threshold) {
|
|
212
|
+
return {
|
|
213
|
+
alert: true,
|
|
214
|
+
level: 'limit',
|
|
215
|
+
message: `Session cost ($${spend.toFixed(4)}) has exceeded the configured budget ($${threshold.toFixed(2)}).`,
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (spend >= threshold * 0.8) {
|
|
220
|
+
return {
|
|
221
|
+
alert: true,
|
|
222
|
+
level: 'warning',
|
|
223
|
+
message: `Session cost ($${spend.toFixed(4)}) has reached 80% of budget limit ($${threshold.toFixed(2)}).`,
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return null
|
|
228
|
+
}
|
package/lib/gateway-commands.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { resolve, dirname } from 'node:path'
|
|
1
|
+
import { resolve, dirname, basename } from 'node:path'
|
|
2
|
+
import { realpathSync } from 'node:fs'
|
|
2
3
|
import { fileURLToPath } from 'node:url'
|
|
3
4
|
import { ensureContentArray } from './content-guard.js'
|
|
4
5
|
import { t } from './locales/index.js'
|
|
@@ -12,8 +13,10 @@ import { listModelCatalog, buildProvidersKeyboard } from './models.js'
|
|
|
12
13
|
import { normalizeHomeName, upsertHome, listHomes } from './homes.js'
|
|
13
14
|
import { handleSetAlertCommand, handleAlertCommand } from './alerts.js'
|
|
14
15
|
import { HELP_TEXT } from './commands.js'
|
|
15
|
-
import { resolveEffectiveCwd } from './workspace.js'
|
|
16
|
+
import { resolveEffectiveCwd, getCwdWarning, inspectGitWorkspace, registerSessionInWorkspace } from './workspace.js'
|
|
16
17
|
import { escapeHtml } from './telegram-format.js'
|
|
18
|
+
import { rememberUserFact, listUserMemories, forgetUserMemory } from './memory-brain.js'
|
|
19
|
+
import { formatSessionCostReport } from './cost-tracker.js'
|
|
17
20
|
|
|
18
21
|
|
|
19
22
|
export function releaseChatTurn(chat) {
|
|
@@ -252,14 +255,208 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
252
255
|
}
|
|
253
256
|
}
|
|
254
257
|
|
|
258
|
+
if (cmd === '/project') {
|
|
259
|
+
const sub = parts[1]?.toLowerCase()
|
|
260
|
+
if (sub === 'bind') {
|
|
261
|
+
const targetPath = parts[2]
|
|
262
|
+
if (!targetPath) {
|
|
263
|
+
return reply('Usage: <code>/project bind <path> [role]</code>\nExample: <code>/project bind /home/vadim/my-app coder</code>')
|
|
264
|
+
}
|
|
265
|
+
const warning = getCwdWarning(targetPath)
|
|
266
|
+
if (warning) {
|
|
267
|
+
return reply(`❌ <b>Invalid workspace directory:</b>\n${escapeHtml(warning)}`)
|
|
268
|
+
}
|
|
269
|
+
let realCwd = targetPath
|
|
270
|
+
try { realCwd = realpathSync(resolve(targetPath)) } catch { realCwd = resolve(targetPath) }
|
|
271
|
+
const gitInfo = inspectGitWorkspace(realCwd)
|
|
272
|
+
const roleArg = parts[3]?.toLowerCase()
|
|
273
|
+
const validRole = roleArg && getPersona(roleArg) ? roleArg : null
|
|
274
|
+
|
|
275
|
+
gw.topicWorkspaces?.set(chatId, threadId, {
|
|
276
|
+
path: realCwd,
|
|
277
|
+
name: basename(realCwd),
|
|
278
|
+
role: validRole,
|
|
279
|
+
worktree: gitInfo.isWorktree,
|
|
280
|
+
})
|
|
281
|
+
|
|
282
|
+
if (validRole) {
|
|
283
|
+
gw.personas?.set(chatId, validRole, threadId)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const chat = gw.chats.get(key)
|
|
287
|
+
if (chat?.agent?.session?.id) {
|
|
288
|
+
registerSessionInWorkspace(gw.ctx, chat.agent.session.id, realCwd, gw.ctx?.logger).catch(() => {})
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const lines = [
|
|
292
|
+
`✅ <b>Workspace bound to topic:</b>`,
|
|
293
|
+
`📁 Directory: <code>${escapeHtml(realCwd)}</code>`,
|
|
294
|
+
]
|
|
295
|
+
if (gitInfo.isWorktree) lines.push(`🌿 Git Worktree: <code>detected</code>`)
|
|
296
|
+
else if (gitInfo.isGit) lines.push(`📦 Git Repository: <code>main repo</code>`)
|
|
297
|
+
if (validRole) lines.push(`🎭 Persona role: <b>${validRole}</b>`)
|
|
298
|
+
return reply(lines.join('\n'))
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (sub === 'unbind' || sub === 'reset' || sub === 'clear') {
|
|
302
|
+
const removed = gw.topicWorkspaces?.delete(chatId, threadId)
|
|
303
|
+
if (removed) {
|
|
304
|
+
return reply('✅ <b>Workspace unbind:</b> topic reverted to default workspace.')
|
|
305
|
+
}
|
|
306
|
+
return reply('ℹ️ No custom workspace was bound to this topic.')
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
if (sub === 'list') {
|
|
310
|
+
const list = gw.topicWorkspaces?.list(chatId) || []
|
|
311
|
+
if (!list.length) {
|
|
312
|
+
return reply('ℹ️ No topics in this chat have bound workspaces.')
|
|
313
|
+
}
|
|
314
|
+
const lines = ['📁 <b>Bound Topic Workspaces:</b>\n']
|
|
315
|
+
for (const item of list) {
|
|
316
|
+
const tLabel = item.threadId ? `Topic #${item.threadId}` : 'Main Chat'
|
|
317
|
+
const roleLabel = item.role ? ` (role: ${item.role})` : ''
|
|
318
|
+
lines.push(`• <b>${tLabel}</b>: <code>${escapeHtml(item.path)}</code>${roleLabel}`)
|
|
319
|
+
}
|
|
320
|
+
return reply(lines.join('\n'))
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const bound = gw.topicWorkspaces?.get(chatId, threadId)
|
|
324
|
+
const effective = gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
|
|
325
|
+
const lines = [
|
|
326
|
+
`📁 <b>Project Workspace Status:</b>`,
|
|
327
|
+
]
|
|
328
|
+
if (bound) {
|
|
329
|
+
lines.push(`• Bound path: <code>${escapeHtml(bound.path)}</code>`)
|
|
330
|
+
if (bound.worktree) lines.push(`• Mode: 🌿 Git Worktree`)
|
|
331
|
+
if (bound.role) lines.push(`• Bound role: <b>${bound.role}</b>`)
|
|
332
|
+
lines.push(`• Bound since: <code>${bound.boundAt}</code>`)
|
|
333
|
+
} else {
|
|
334
|
+
lines.push(`• Current workspace: <code>${escapeHtml(effective)}</code> (default)`)
|
|
335
|
+
lines.push(`• Status: <i>Not bound to dedicated project</i>`)
|
|
336
|
+
}
|
|
337
|
+
lines.push('\n<b>Commands:</b>')
|
|
338
|
+
lines.push('• <code>/project bind <path> [role]</code> — bind topic to directory or worktree')
|
|
339
|
+
lines.push('• <code>/project unbind</code> — reset topic to default workspace')
|
|
340
|
+
lines.push('• <code>/project list</code> — view all topic bindings')
|
|
341
|
+
return reply(lines.join('\n'))
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (cmd === '/memory') {
|
|
345
|
+
const sub = parts[1]?.toLowerCase()
|
|
346
|
+
if (sub === 'add') {
|
|
347
|
+
const factText = parts.slice(2).join(' ').trim()
|
|
348
|
+
if (!factText) {
|
|
349
|
+
return reply('Usage: <code>/memory add <fact></code>\nExample: <code>/memory add I prefer concise answers in Python</code>')
|
|
350
|
+
}
|
|
351
|
+
const res = await rememberUserFact({
|
|
352
|
+
config: gw.config?.memory,
|
|
353
|
+
userId,
|
|
354
|
+
content: factText,
|
|
355
|
+
})
|
|
356
|
+
if (!res.ok) {
|
|
357
|
+
return reply(`❌ Failed to store memory: ${escapeHtml(res.error || 'unknown error')}`)
|
|
358
|
+
}
|
|
359
|
+
return reply(`🧠 <b>Memory remembered:</b>\n<i>${escapeHtml(factText)}</i>`)
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const listRes = await listUserMemories({
|
|
363
|
+
config: gw.config?.memory,
|
|
364
|
+
userId,
|
|
365
|
+
limit: 25,
|
|
366
|
+
})
|
|
367
|
+
if (!listRes.ok) {
|
|
368
|
+
return reply(`⚠️ Memory service unavailable: ${escapeHtml(listRes.error || 'could not connect')}`)
|
|
369
|
+
}
|
|
370
|
+
if (!listRes.items || !listRes.items.length) {
|
|
371
|
+
return reply(`🧠 <b>User Memory (ID: <code>${escapeHtml(String(userId))}</code>):</b>\n<i>No stored facts found.</i>\n\nAdd one: <code>/memory add <fact></code>`)
|
|
372
|
+
}
|
|
373
|
+
const lines = [
|
|
374
|
+
`🧠 <b>User Memory Profile (ID: <code>${escapeHtml(String(userId))}</code>):</b>`,
|
|
375
|
+
'',
|
|
376
|
+
...listRes.items.map((it, idx) => `${idx + 1}. [<code>${escapeHtml(it.id.slice(0, 8))}</code>] ${escapeHtml(it.content)}`),
|
|
377
|
+
'',
|
|
378
|
+
'• Add fact: <code>/memory add <fact></code>',
|
|
379
|
+
'• Forget fact: <code>/forget <id></code>',
|
|
380
|
+
'• Clear all: <code>/forget all</code>',
|
|
381
|
+
]
|
|
382
|
+
return reply(lines.join('\n'))
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (cmd === '/forget') {
|
|
386
|
+
const targetId = parts[1]?.trim()
|
|
387
|
+
if (!targetId) {
|
|
388
|
+
return reply('Usage: <code>/forget <id|all></code>\nExample: <code>/forget 95b82eb8</code> or <code>/forget all</code>\nRun <code>/memory</code> to view memory IDs.')
|
|
389
|
+
}
|
|
390
|
+
const forgetRes = await forgetUserMemory({
|
|
391
|
+
config: gw.config?.memory,
|
|
392
|
+
userId,
|
|
393
|
+
memoryId: targetId,
|
|
394
|
+
})
|
|
395
|
+
if (!forgetRes.ok) {
|
|
396
|
+
return reply(`❌ Failed to forget: ${escapeHtml(forgetRes.error || 'unknown error')}`)
|
|
397
|
+
}
|
|
398
|
+
if (targetId.toLowerCase() === 'all') {
|
|
399
|
+
return reply(`🗑️ Forgotten ${forgetRes.count || 0} user memor${forgetRes.count === 1 ? 'y' : 'ies'}.`)
|
|
400
|
+
}
|
|
401
|
+
return reply(`🗑️ Forgotten memory <code>${escapeHtml(targetId)}</code>.`)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (cmd === '/outbox') {
|
|
405
|
+
const sub = parts[1]?.toLowerCase()
|
|
406
|
+
if (!gw.outbox) {
|
|
407
|
+
return reply('ℹ️ Outbox queue is not initialized.')
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (sub === 'retry') {
|
|
411
|
+
const count = await gw.outbox.retryDlq()
|
|
412
|
+
return reply(`🔄 Moved <b>${count}</b> DLQ items back to outbox queue for retry.`)
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
if (sub === 'clear') {
|
|
416
|
+
const count = await gw.outbox.clearDlq()
|
|
417
|
+
return reply(`🗑️ Cleared <b>${count}</b> items from Dead Letter Queue.`)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const st = gw.outbox.status()
|
|
421
|
+
const lines = [
|
|
422
|
+
'📬 <b>Outbox Transactional Queue:</b>',
|
|
423
|
+
`• Pending messages: <b>${st.pendingCount}</b>`,
|
|
424
|
+
`• Dead Letter Queue (DLQ): <b>${st.dlqCount}</b>`,
|
|
425
|
+
]
|
|
426
|
+
if (st.dlqCount > 0) {
|
|
427
|
+
lines.push('', '<b>Recent DLQ Failures:</b>')
|
|
428
|
+
const sample = st.dlq.slice(0, 5)
|
|
429
|
+
for (const item of sample) {
|
|
430
|
+
lines.push(`- [<code>${escapeHtml(item.id.slice(0, 8))}</code>] to ${escapeHtml(String(item.target?.chatId))}: ${escapeHtml(item.error || 'unknown error')}`)
|
|
431
|
+
}
|
|
432
|
+
lines.push('', 'Commands:', '• Retry all: <code>/outbox retry</code>', '• Clear DLQ: <code>/outbox clear</code>')
|
|
433
|
+
} else {
|
|
434
|
+
lines.push('', '<i>All outbound messages successfully delivered.</i>')
|
|
435
|
+
}
|
|
436
|
+
return reply(lines.join('\n'))
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
if (cmd === '/cost') {
|
|
440
|
+
const chat = gw.chats.get(key)
|
|
441
|
+
const report = formatSessionCostReport({
|
|
442
|
+
chat,
|
|
443
|
+
config: gw.config,
|
|
444
|
+
model: gw.config.agent?.model || 'deepseek-chat',
|
|
445
|
+
})
|
|
446
|
+
return reply(report)
|
|
447
|
+
}
|
|
448
|
+
|
|
255
449
|
if (cmd === '/cwd') {
|
|
256
450
|
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)
|
|
451
|
+
const sessionCwd = chat?.agent?.meta?.cwd || chat?.agent?.session?.meta?.cwd || (gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger))
|
|
452
|
+
const bound = gw.topicWorkspaces?.get(chatId, threadId)
|
|
258
453
|
const configuredCwd = gw.config.agent?.cwd || ''
|
|
259
454
|
const lines = [
|
|
260
455
|
`📁 <b>Working Directory:</b> <code>${escapeHtml(sessionCwd)}</code>`,
|
|
261
456
|
]
|
|
262
|
-
if (
|
|
457
|
+
if (bound) {
|
|
458
|
+
lines.push(`🌿 Topic binding: <code>${escapeHtml(bound.path)}</code>${bound.worktree ? ' (worktree)' : ''}`)
|
|
459
|
+
} else if (configuredCwd) {
|
|
263
460
|
lines.push(`⚙️ Configured: <code>${escapeHtml(configuredCwd)}</code>`)
|
|
264
461
|
} else {
|
|
265
462
|
lines.push(`ℹ️ Default: host launch directory`)
|
|
@@ -269,14 +466,14 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
269
466
|
|
|
270
467
|
if (cmd === '/files') {
|
|
271
468
|
const subPath = parts.slice(1).join(' ').trim() || '.'
|
|
272
|
-
const agentCwd = resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
|
|
469
|
+
const agentCwd = (gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger))
|
|
273
470
|
const res = await handleFilesCommand(agentCwd, subPath)
|
|
274
471
|
return reply(res.text)
|
|
275
472
|
}
|
|
276
473
|
|
|
277
474
|
if (cmd === '/get') {
|
|
278
475
|
const targetRel = parts.slice(1).join(' ').trim()
|
|
279
|
-
const agentCwd = resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger)
|
|
476
|
+
const agentCwd = (gw.resolveEffectiveCwdFor ? gw.resolveEffectiveCwdFor(chatId, threadId) : resolveEffectiveCwd(gw.config.agent?.cwd, gw.ctx?.logger))
|
|
280
477
|
const maxDocBytes = Number(gw.config.media?.maxDocBytes) || 50 * 1024 * 1024
|
|
281
478
|
const res = await handleGetCommand(agentCwd, targetRel, maxDocBytes)
|
|
282
479
|
return reply(res.files ? { text: res.text, files: res.files } : res.text)
|
package/lib/gateway-turn.js
CHANGED
|
@@ -15,6 +15,8 @@ import {
|
|
|
15
15
|
buildStreamPreview, formatProgressLine, createEditScheduler, startTypingHeartbeat, parseReasoningStream
|
|
16
16
|
} from './stream.js'
|
|
17
17
|
import { escapeHtml } from './telegram-format.js'
|
|
18
|
+
import { formatCostFooter, normalizeUsage, extractSessionStats, calculateEstimatedCostUsd, checkBudgetThreshold } from './cost-tracker.js'
|
|
19
|
+
import { recallUserMemories, recordTurnMemory } from './memory-brain.js'
|
|
18
20
|
|
|
19
21
|
const PLUGIN = 'dsh-messenger-gateway'
|
|
20
22
|
|
|
@@ -135,9 +137,23 @@ export async function answerApproval(gw, chatKeyValue, req, next) {
|
|
|
135
137
|
}
|
|
136
138
|
|
|
137
139
|
export async function buildUserContent(gw, input, signal) {
|
|
138
|
-
const { text, attachments = [], replyText, steer, personaOverride } = input
|
|
140
|
+
const { text, attachments = [], replyText, steer, personaOverride, userId } = input
|
|
139
141
|
const parts = []
|
|
140
142
|
parts.push(String(gw.config.agent?.instructionPrefix || MESSENGER_RELAY_INSTRUCTION))
|
|
143
|
+
if (gw.config?.memory?.enabled !== false && gw.config?.memory?.autoInject !== false && userId) {
|
|
144
|
+
try {
|
|
145
|
+
const recalled = await recallUserMemories({
|
|
146
|
+
config: gw.config.memory,
|
|
147
|
+
userId,
|
|
148
|
+
query: text || replyText || '',
|
|
149
|
+
budget: gw.config.memory?.budget,
|
|
150
|
+
signal,
|
|
151
|
+
})
|
|
152
|
+
if (recalled) parts.push(recalled)
|
|
153
|
+
} catch (memErr) {
|
|
154
|
+
gw.ctx?.logger?.debug?.(`[memory-brain] recall error: ${memErr?.message || memErr}`)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
141
157
|
const activePersonaId = personaOverride || gw.personas.getPersonaForChat(input.chatId, input.threadId)
|
|
142
158
|
const activePersona = getPersona(activePersonaId)
|
|
143
159
|
if (activePersona?.instruction) {
|
|
@@ -200,6 +216,7 @@ export async function buildUserContent(gw, input, signal) {
|
|
|
200
216
|
|
|
201
217
|
export async function runGatewayTurn(gw, chat, input, signal) {
|
|
202
218
|
const { reply, typing, startStream, startProgress, react, inboundWasVoice, userId } = input
|
|
219
|
+
const turnStartTime = Date.now()
|
|
203
220
|
chat.turnActive = true
|
|
204
221
|
const sessionId = chat.agent.session.id
|
|
205
222
|
const tg = gw.tg()
|
|
@@ -315,6 +332,23 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
315
332
|
else await reply(noResp)
|
|
316
333
|
return
|
|
317
334
|
}
|
|
335
|
+
if (collector.usage) {
|
|
336
|
+
chat.lastTurnUsage = collector.usage
|
|
337
|
+
if (!chat.turnStats) chat.turnStats = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, turnsCount: 0 }
|
|
338
|
+
chat.turnStats.turnsCount++
|
|
339
|
+
const norm = normalizeUsage(collector.usage)
|
|
340
|
+
chat.turnStats.inputTokens += norm.inputTokens
|
|
341
|
+
chat.turnStats.outputTokens += norm.outputTokens
|
|
342
|
+
chat.turnStats.cacheReadTokens += norm.cacheReadTokens
|
|
343
|
+
}
|
|
344
|
+
if (tg.costFooter && answer) {
|
|
345
|
+
const footer = formatCostFooter({
|
|
346
|
+
durationMs: Date.now() - turnStartTime,
|
|
347
|
+
usage: collector.usage,
|
|
348
|
+
model: gw.config?.agent?.model,
|
|
349
|
+
})
|
|
350
|
+
if (footer) answer += footer
|
|
351
|
+
}
|
|
318
352
|
const maxLen = Number(gw.config.agent?.maxMessageLength) || 4000
|
|
319
353
|
const chunks = answer ? splitText(answer, maxLen) : ['']
|
|
320
354
|
if (stream) {
|
|
@@ -348,6 +382,34 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
348
382
|
}
|
|
349
383
|
}
|
|
350
384
|
}
|
|
385
|
+
const budgetThreshold = Number(tg.budgetAlertThresholdUsd || 0)
|
|
386
|
+
if (budgetThreshold > 0) {
|
|
387
|
+
const stats = extractSessionStats(chat)
|
|
388
|
+
const cost = calculateEstimatedCostUsd({
|
|
389
|
+
inputTokens: stats.promptTokens,
|
|
390
|
+
outputTokens: stats.completionTokens,
|
|
391
|
+
cacheReadTokens: stats.cachedTokens,
|
|
392
|
+
}, gw.config?.agent?.model)
|
|
393
|
+
const warning = checkBudgetThreshold({ currentSpendUsd: cost, thresholdUsd: budgetThreshold })
|
|
394
|
+
if (warning && !chat.budgetWarned) {
|
|
395
|
+
chat.budgetWarned = true
|
|
396
|
+
gw.sendAlert('status', {
|
|
397
|
+
title: 'Budget Alert',
|
|
398
|
+
details: `${warning.message} (Chat: ${input.chatId})`,
|
|
399
|
+
}).catch(() => {})
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
if (gw.config?.memory?.enabled !== false && userId && answer && input.text) {
|
|
403
|
+
recordTurnMemory({
|
|
404
|
+
config: gw.config.memory,
|
|
405
|
+
userId,
|
|
406
|
+
userText: input.text,
|
|
407
|
+
assistantText: answer,
|
|
408
|
+
logger: gw.ctx?.logger,
|
|
409
|
+
}).catch?.((recErr) => {
|
|
410
|
+
gw.ctx?.logger?.debug?.(`[memory-brain] recordTurnMemory error: ${recErr?.message || recErr}`)
|
|
411
|
+
})
|
|
412
|
+
}
|
|
351
413
|
} catch (err) {
|
|
352
414
|
if (!signal?.aborted) {
|
|
353
415
|
gw.sendAlert('error', {
|