@soffits/dsh-matrix-bot 0.0.0-stage → 0.2.0
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/CHANGELOG.md +11 -0
- package/LICENSE +21 -0
- package/README.md +129 -2
- package/bin/dsh-matrix.js +132 -0
- package/cordis.patch.yml +9 -0
- package/icon.svg +6 -0
- package/index.js +4 -0
- package/locale/en.json +6 -0
- package/package.json +68 -4
- package/src/app.js +446 -0
- package/src/commands.js +459 -0
- package/src/config.js +67 -0
- package/src/constants.js +70 -0
- package/src/controls.js +214 -0
- package/src/events.js +251 -0
- package/src/helpers.js +179 -0
- package/src/inbound.js +150 -0
- package/src/matrix.js +507 -0
- package/src/models.js +191 -0
- package/src/operations.js +150 -0
- package/src/outbound.js +141 -0
- package/src/prompts.js +244 -0
- package/src/reactions.js +127 -0
- package/src/sender.js +165 -0
- package/src/sessions.js +390 -0
- package/src/spaces.js +278 -0
- package/src/spool.js +172 -0
- package/src/state.js +203 -0
- package/src/text.js +125 -0
- package/src/titles.js +174 -0
- package/src/turns.js +331 -0
- package/src/voice.js +126 -0
- package/tools.js +60 -0
package/src/commands.js
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Room commands. They follow the Telegram bot's commands; where Telegram
|
|
3
|
+
* shows buttons, a command lists numbered choices and the same command with
|
|
4
|
+
* the number picks one (`!model` lists providers, `!model 2` its models,
|
|
5
|
+
* `!model 2 5` selects). `!` works in every Matrix client; `/` works where the
|
|
6
|
+
* client sends unknown slash commands as text.
|
|
7
|
+
*/
|
|
8
|
+
import { basename } from 'node:path'
|
|
9
|
+
import { COMMAND_PREFIXES, MSC4332_COMMAND, MSC4391_COMMAND } from './constants.js'
|
|
10
|
+
import { CONTROL_HANDLERS, liveAgent, pick, sessionOf } from './controls.js'
|
|
11
|
+
import { clearRoomInbox, controllerOf, listWorkspaces, recentAssistantTexts, sessionTitle, sessionsInWorkspace } from './sessions.js'
|
|
12
|
+
import { clip } from './text.js'
|
|
13
|
+
import { roomTitle } from './titles.js'
|
|
14
|
+
|
|
15
|
+
/** Prefix help shows. */
|
|
16
|
+
export const SIGIL = COMMAND_PREFIXES[0]
|
|
17
|
+
|
|
18
|
+
/** Commands, their help lines and argument hints, in the order help shows them. */
|
|
19
|
+
export const COMMANDS = [
|
|
20
|
+
['help', 'List commands'],
|
|
21
|
+
['new', 'Open a new room with a new session', 'room name'],
|
|
22
|
+
['reset', 'Start a new session in this room'],
|
|
23
|
+
['stop', 'Stop the running turn'],
|
|
24
|
+
['clear', 'Drop messages still waiting for the session'],
|
|
25
|
+
['status', 'Bot and session status'],
|
|
26
|
+
['current', "Show this room's session"],
|
|
27
|
+
['last', 'Show the latest answers', '1 to 5'],
|
|
28
|
+
['agents', "List this session's helpers and their last reports"],
|
|
29
|
+
['sessions', 'Browse workspaces and sessions, continue one here', 'numbers'],
|
|
30
|
+
['workspace', 'Start a new session in another workspace', 'number'],
|
|
31
|
+
['fork', 'Fork this session into a new room', 'room name'],
|
|
32
|
+
['rename', "Rename this room's session", 'new name'],
|
|
33
|
+
['goal', 'Set or change the goal', 'objective, edit, pause, resume or clear'],
|
|
34
|
+
['menu', 'Model, effort, access mode and context'],
|
|
35
|
+
['model', 'Choose the model', 'numbers'],
|
|
36
|
+
['effort', 'Choose the reasoning effort', 'number'],
|
|
37
|
+
['mode', 'Choose the access mode', 'number'],
|
|
38
|
+
['context', 'Context use of the session'],
|
|
39
|
+
['allow', 'Allow the waiting tool request'],
|
|
40
|
+
['deny', 'Deny the waiting tool request'],
|
|
41
|
+
['id', 'Show room, session and device ids'],
|
|
42
|
+
['ping', 'Check that the bot answers'],
|
|
43
|
+
['restart', 'Reconnect to the homeserver'],
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
const NAMES = new Set([...COMMANDS.map(([command]) => command), 'start'])
|
|
47
|
+
|
|
48
|
+
/** Workspaces and sessions listed at most. */
|
|
49
|
+
const LIST_LIMIT = 15
|
|
50
|
+
|
|
51
|
+
/** @returns `{ name, args }` for a known command name, or undefined. */
|
|
52
|
+
function known(name, args) {
|
|
53
|
+
const lower = String(name ?? '').toLowerCase()
|
|
54
|
+
if (!NAMES.has(lower)) return undefined
|
|
55
|
+
return { name: lower === 'start' ? 'help' : lower, args: String(args ?? '').trim() }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Read a command from a message: the invocation block of a client that
|
|
60
|
+
* offers the command list (MSC4391, MSC4332), else `!name args` or
|
|
61
|
+
* `/name args` in the text.
|
|
62
|
+
* @param content - message content.
|
|
63
|
+
* @returns `{ name, args }`, or undefined when the message is not a known
|
|
64
|
+
* command (a path such as `/home/...` stays an ordinary message).
|
|
65
|
+
*/
|
|
66
|
+
export function parseCommand(content) {
|
|
67
|
+
const invoked = content?.[MSC4391_COMMAND]
|
|
68
|
+
if (typeof invoked?.command === 'string') return known(invoked.command, invoked.arguments?.args)
|
|
69
|
+
const legacy = content?.[MSC4332_COMMAND]
|
|
70
|
+
if (typeof legacy?.syntax === 'string') return known(legacy.syntax.split(/\s+/u)[0], legacy.arguments?.args)
|
|
71
|
+
if (content?.msgtype !== 'm.text' || typeof content.body !== 'string') return undefined
|
|
72
|
+
const match = content.body.trim().match(/^([!/])([A-Za-z]+)(?:@\S+)?(?:\s+([\s\S]*))?$/u)
|
|
73
|
+
if (match === null) return undefined
|
|
74
|
+
return known(match[2], match[3])
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** @returns the help text. */
|
|
78
|
+
export function helpText() {
|
|
79
|
+
return [
|
|
80
|
+
'Write here and the session answers. Commands start with !, which works in every Matrix app (/ works too where your app sends it):',
|
|
81
|
+
'',
|
|
82
|
+
...COMMANDS.map(([command, line, usage]) => `${SIGIL}${command}${usage ? ` <${usage}>` : ''} — ${line}`),
|
|
83
|
+
'',
|
|
84
|
+
`Each room is its own session; ${SIGIL}new opens another one in your Space.`,
|
|
85
|
+
].join('\n')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** @returns a relative age, such as "5 min ago". */
|
|
89
|
+
function age(timestamp) {
|
|
90
|
+
if (typeof timestamp !== 'number') return ''
|
|
91
|
+
const minutes = Math.round((Date.now() - timestamp) / 60_000)
|
|
92
|
+
if (minutes < 60) return `${Math.max(0, minutes)} min ago`
|
|
93
|
+
const hours = Math.round(minutes / 60)
|
|
94
|
+
if (hours < 48) return `${hours} h ago`
|
|
95
|
+
return `${Math.round(hours / 24)} d ago`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Run one command.
|
|
100
|
+
* @param bridge - runtime handles from app.js.
|
|
101
|
+
* @param from - `{ roomId, sender, eventId }`; `sender` is `{ userId, name }`.
|
|
102
|
+
* @param command - `{ name, args }`.
|
|
103
|
+
*/
|
|
104
|
+
export async function runCommand(bridge, from, command) {
|
|
105
|
+
const handler = HANDLERS[command.name]
|
|
106
|
+
await handler(bridge, from, command.args)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function isRunning(agent) {
|
|
110
|
+
return agent !== undefined && agent.status !== undefined && agent.status !== 'idle'
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Refuse a command while the room's session runs a turn. */
|
|
114
|
+
async function refuseWhileRunning(bridge, roomId, what) {
|
|
115
|
+
if (!isRunning(liveAgent(bridge, roomId))) return false
|
|
116
|
+
await bridge.notice(roomId, `Stop the running turn first (!stop), then ${what}.`)
|
|
117
|
+
return true
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Start the room's next session in a directory, keeping the old one in DSH. */
|
|
121
|
+
async function startFresh(bridge, roomId, cwd) {
|
|
122
|
+
const store = bridge.store()
|
|
123
|
+
const previous = await store.release(roomId)
|
|
124
|
+
const record = store.data.rooms[roomId] ?? {}
|
|
125
|
+
store.data.rooms[roomId] = { ...record, cwd }
|
|
126
|
+
await store.save()
|
|
127
|
+
const title = previous === undefined ? undefined : await sessionTitle(bridge.ctx, previous)
|
|
128
|
+
return title
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Text of a goal's state. */
|
|
132
|
+
function goalStatus(view) {
|
|
133
|
+
if (view === undefined) return '🎯 No goal is set.\n\n!goal <objective> sets one.'
|
|
134
|
+
const phase = view.activation === 'armed' || view.phase !== 'active' ? view.phase : `${view.phase}, not armed`
|
|
135
|
+
return `🎯 Goal (${phase}, round ${view.roundsStarted}/${view.maxGoalRounds}):\n${view.objective}\n\n!goal edit <objective> · !goal pause · !goal resume · !goal clear`
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const HANDLERS = {
|
|
139
|
+
async help(bridge, { roomId }) {
|
|
140
|
+
await bridge.notice(roomId, helpText())
|
|
141
|
+
},
|
|
142
|
+
|
|
143
|
+
async ping(bridge, { roomId }) {
|
|
144
|
+
await bridge.notice(roomId, 'pong')
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
async id(bridge, { roomId, sender }) {
|
|
148
|
+
const facts = bridge.describe()
|
|
149
|
+
await bridge.notice(roomId, [
|
|
150
|
+
`Room: ${roomId}`,
|
|
151
|
+
`You: ${sender.userId}`,
|
|
152
|
+
`Bot: ${facts.userId ?? '?'} (device ${facts.deviceId ?? '?'})`,
|
|
153
|
+
`Session: ${sessionOf(bridge, roomId) ?? 'none yet'}`,
|
|
154
|
+
].join('\n'))
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
async status(bridge, { roomId }) {
|
|
158
|
+
const facts = bridge.describe()
|
|
159
|
+
const agent = liveAgent(bridge, roomId)
|
|
160
|
+
const sessionId = sessionOf(bridge, roomId)
|
|
161
|
+
const lines = [
|
|
162
|
+
`Matrix bot: ${facts.running ? 'running' : facts.state}`,
|
|
163
|
+
...(facts.running ? [
|
|
164
|
+
`Account: ${facts.userId} on ${facts.homeserver}`,
|
|
165
|
+
`Encryption: ${facts.encryption.verified ? 'device verified' : 'device NOT verified'}, key backup ${facts.encryption.backup ? 'on' : 'off'}`,
|
|
166
|
+
`Uptime: ${Math.round(facts.uptimeSeconds / 60)} min`,
|
|
167
|
+
`Allowed people: ${facts.allowedUsers}${facts.pending.length > 0 ? `, ${facts.pending.length} ignored sender(s)` : ''}`,
|
|
168
|
+
] : []),
|
|
169
|
+
`Session: ${sessionId ?? 'none yet'}`,
|
|
170
|
+
...(sessionId === undefined ? [] : [`Title: ${await sessionTitle(bridge.ctx, sessionId)}`]),
|
|
171
|
+
`Agent: ${isRunning(agent) ? 'running' : 'idle'}`,
|
|
172
|
+
]
|
|
173
|
+
const asked = bridge.prompts.pending(roomId)
|
|
174
|
+
if (asked.question) lines.push('A question is waiting for your answer.')
|
|
175
|
+
if (asked.approvals > 0) lines.push(`${asked.approvals} tool request(s) wait for !allow or !deny.`)
|
|
176
|
+
await bridge.notice(roomId, lines.join('\n'))
|
|
177
|
+
},
|
|
178
|
+
|
|
179
|
+
async current(bridge, { roomId }) {
|
|
180
|
+
const sessionId = sessionOf(bridge, roomId)
|
|
181
|
+
if (sessionId === undefined) {
|
|
182
|
+
await bridge.notice(roomId, 'This room has no session yet; your next message starts one.')
|
|
183
|
+
return
|
|
184
|
+
}
|
|
185
|
+
const record = bridge.store().room(roomId)
|
|
186
|
+
await bridge.notice(roomId, `${await sessionTitle(bridge.ctx, sessionId)}\nSession: ${sessionId}\nWorkspace: ${record?.cwd ?? '?'}`)
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
async new(bridge, { sender }, args) {
|
|
190
|
+
const name = clip(args.replace(/^["']|["']$/gu, '').trim() || 'New room', 100)
|
|
191
|
+
await bridge.spaces.createRoom(sender.userId, name)
|
|
192
|
+
},
|
|
193
|
+
|
|
194
|
+
async reset(bridge, { roomId }) {
|
|
195
|
+
if (await refuseWhileRunning(bridge, roomId, 'start a new session')) return
|
|
196
|
+
const record = bridge.store().room(roomId)
|
|
197
|
+
const previous = await startFresh(bridge, roomId, record?.cwd ?? bridge.setting('cwd', process.cwd()))
|
|
198
|
+
await bridge.notice(roomId, `🆕 New session: your next message starts it.${previous === undefined ? '' : `\nThe previous session stays in DSH: ${previous}`}`)
|
|
199
|
+
},
|
|
200
|
+
|
|
201
|
+
async stop(bridge, { roomId }) {
|
|
202
|
+
const agent = liveAgent(bridge, roomId)
|
|
203
|
+
bridge.prompts.cancelRoom(roomId)
|
|
204
|
+
if (!isRunning(agent)) {
|
|
205
|
+
await bridge.notice(roomId, 'Nothing is running.')
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
const turn = bridge.currentTurn(agent.session?.id ?? agent.id)
|
|
209
|
+
if (turn !== undefined) turn.stopped = true
|
|
210
|
+
try {
|
|
211
|
+
agent.inbox?.clear?.()
|
|
212
|
+
} catch {
|
|
213
|
+
// Inbox unavailable.
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
agent.cancel({ kind: 'user' })
|
|
217
|
+
} catch {
|
|
218
|
+
// Already idle.
|
|
219
|
+
}
|
|
220
|
+
await bridge.notice(roomId, '⏹ Stopped.')
|
|
221
|
+
},
|
|
222
|
+
|
|
223
|
+
async clear(bridge, { roomId }) {
|
|
224
|
+
const removed = clearRoomInbox(liveAgent(bridge, roomId), roomId)
|
|
225
|
+
await bridge.reactions.sweep(roomId)
|
|
226
|
+
await bridge.notice(roomId, removed === 0 ? '🧹 Nothing is waiting.' : `🧹 Dropped ${removed} waiting message(s).`)
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
async last(bridge, { roomId }, args) {
|
|
230
|
+
const sessionId = sessionOf(bridge, roomId)
|
|
231
|
+
if (sessionId === undefined) {
|
|
232
|
+
await bridge.notice(roomId, 'This room has no session yet.')
|
|
233
|
+
return
|
|
234
|
+
}
|
|
235
|
+
const requested = Number.parseInt(args || '1', 10)
|
|
236
|
+
const limit = Number.isFinite(requested) ? Math.min(5, Math.max(1, requested)) : 1
|
|
237
|
+
const texts = await recentAssistantTexts(bridge.ctx, sessionId, limit)
|
|
238
|
+
if (texts.length === 0) {
|
|
239
|
+
await bridge.notice(roomId, 'This session has no answers yet.')
|
|
240
|
+
return
|
|
241
|
+
}
|
|
242
|
+
for (const [index, text] of [...texts].reverse().entries()) {
|
|
243
|
+
const label = texts.length === 1 ? 'Latest answer' : `Answer ${index + 1}/${texts.length}`
|
|
244
|
+
await bridge.say(roomId, `${label}:\n\n${text}`)
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
|
|
248
|
+
async agents(bridge, { roomId }) {
|
|
249
|
+
const sessionId = sessionOf(bridge, roomId)
|
|
250
|
+
if (sessionId === undefined) {
|
|
251
|
+
await bridge.notice(roomId, 'This room has no session yet.')
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
const helpers = await bridge.helpers.list(sessionId)
|
|
255
|
+
if (helpers === undefined) {
|
|
256
|
+
await bridge.notice(roomId, 'Helpers are not available in this DSH.')
|
|
257
|
+
return
|
|
258
|
+
}
|
|
259
|
+
if (helpers.length === 0) {
|
|
260
|
+
await bridge.notice(roomId, 'This session has started no helpers.')
|
|
261
|
+
return
|
|
262
|
+
}
|
|
263
|
+
const lines = ['Helpers of this session:']
|
|
264
|
+
for (const [index, helper] of helpers.entries()) {
|
|
265
|
+
lines.push('', `${index + 1}. ${helper.running ? '⏳' : '✓'} ${helper.label} · ${age(helper.createdAt)}`)
|
|
266
|
+
lines.push(helper.report ? clip(helper.report, 400) : helper.running ? '(working)' : '(no report)')
|
|
267
|
+
}
|
|
268
|
+
await bridge.notice(roomId, lines.join('\n'))
|
|
269
|
+
},
|
|
270
|
+
|
|
271
|
+
async sessions(bridge, { roomId }, args) {
|
|
272
|
+
const workspaces = listWorkspaces(bridge.ctx).slice(0, LIST_LIMIT)
|
|
273
|
+
const [first, second] = args.split(/\s+/u).filter(Boolean)
|
|
274
|
+
if (first === undefined) {
|
|
275
|
+
if (workspaces.length === 0) {
|
|
276
|
+
await bridge.notice(roomId, 'No workspaces are registered.')
|
|
277
|
+
return
|
|
278
|
+
}
|
|
279
|
+
const here = bridge.store().room(roomId)?.cwd
|
|
280
|
+
await bridge.notice(roomId, [
|
|
281
|
+
'Workspaces:',
|
|
282
|
+
...workspaces.map((workspace, index) => `${index + 1}. ${workspace.title || basename(workspace.path)} (${workspace.path})${workspace.path === here ? ' ✅' : ''}`),
|
|
283
|
+
'',
|
|
284
|
+
'!sessions <n> lists the sessions of workspace n.',
|
|
285
|
+
].join('\n'))
|
|
286
|
+
return
|
|
287
|
+
}
|
|
288
|
+
const workspace = pick(workspaces, first)
|
|
289
|
+
if (workspace === undefined) {
|
|
290
|
+
await bridge.notice(roomId, `No workspace ${first}; !sessions lists them.`)
|
|
291
|
+
return
|
|
292
|
+
}
|
|
293
|
+
const records = await sessionsInWorkspace(bridge.ctx, workspace, LIST_LIMIT, bridge.signal)
|
|
294
|
+
if (second === undefined) {
|
|
295
|
+
const store = bridge.store()
|
|
296
|
+
const lines = [`Sessions in ${workspace.title || basename(workspace.path)}:`, '0. New session']
|
|
297
|
+
for (const [index, record] of records.entries()) {
|
|
298
|
+
const id = record.header.id
|
|
299
|
+
const boundTo = store.roomOfSession(id)
|
|
300
|
+
const mark = boundTo === roomId ? ' ✅' : boundTo !== undefined ? ' 🔗' : ''
|
|
301
|
+
lines.push(`${index + 1}. ${clip(await sessionTitle(bridge.ctx, id, record.header), 60)} · ${age(record.header.createdAt)}${mark}`)
|
|
302
|
+
}
|
|
303
|
+
lines.push('', `!sessions ${first} <n> continues session n in this room (0 starts a new one). 🔗 means another room shows it now; it moves here.`)
|
|
304
|
+
await bridge.notice(roomId, lines.join('\n'))
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
if (await refuseWhileRunning(bridge, roomId, 'switch sessions')) return
|
|
308
|
+
if (second === '0' || second === 'new') {
|
|
309
|
+
await startFresh(bridge, roomId, workspace.path)
|
|
310
|
+
await bridge.notice(roomId, `🆕 Your next message starts a new session in ${workspace.title || basename(workspace.path)}.`)
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
const record = pick(records, second)
|
|
314
|
+
if (record === undefined) {
|
|
315
|
+
await bridge.notice(roomId, `No session ${second}; !sessions ${first} lists them.`)
|
|
316
|
+
return
|
|
317
|
+
}
|
|
318
|
+
const sessionId = record.header.id
|
|
319
|
+
await bridge.store().bind(roomId, { sessionId, cwd: record.header.cwd ?? workspace.path })
|
|
320
|
+
await bridge.ensureAgent(roomId)
|
|
321
|
+
await bridge.notice(roomId, `✅ This room now continues: ${await sessionTitle(bridge.ctx, sessionId, record.header)}`)
|
|
322
|
+
},
|
|
323
|
+
|
|
324
|
+
async workspace(bridge, from, args) {
|
|
325
|
+
if (args.length === 0) {
|
|
326
|
+
await HANDLERS.sessions(bridge, from, '')
|
|
327
|
+
await bridge.notice(from.roomId, '!workspace <n> starts a new session in workspace n.')
|
|
328
|
+
return
|
|
329
|
+
}
|
|
330
|
+
await HANDLERS.sessions(bridge, from, `${args.split(/\s+/u)[0]} new`)
|
|
331
|
+
},
|
|
332
|
+
|
|
333
|
+
async fork(bridge, { roomId, sender }, args) {
|
|
334
|
+
const sessionId = sessionOf(bridge, roomId)
|
|
335
|
+
if (sessionId === undefined) {
|
|
336
|
+
await bridge.notice(roomId, 'This room has no session to fork yet.')
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
if (await refuseWhileRunning(bridge, roomId, 'fork')) return
|
|
340
|
+
const controller = controllerOf(bridge.ctx)
|
|
341
|
+
if (typeof controller?.fork !== 'function') {
|
|
342
|
+
await bridge.notice(roomId, 'Forking is not available in this DSH.')
|
|
343
|
+
return
|
|
344
|
+
}
|
|
345
|
+
const result = await controller.fork({ sessionId })
|
|
346
|
+
const forkId = typeof result === 'string' ? result : result?.sessionId
|
|
347
|
+
if (typeof forkId !== 'string') throw new Error('The fork returned no session id.')
|
|
348
|
+
const title = clip(args.replace(/^["']|["']$/gu, '').trim() || `Fork of ${await sessionTitle(bridge.ctx, sessionId)}`, 100)
|
|
349
|
+
const record = bridge.store().room(roomId)
|
|
350
|
+
const forkRoom = await bridge.spaces.createRoom(sender.userId, title)
|
|
351
|
+
await bridge.store().bind(forkRoom, { sessionId: forkId, cwd: record?.cwd })
|
|
352
|
+
await bridge.store().describeRoom(forkRoom, { person: record?.person, roomName: title })
|
|
353
|
+
await bridge.ensureAgent(forkRoom)
|
|
354
|
+
await bridge.applyTitle(forkId)
|
|
355
|
+
await bridge.notice(forkRoom, `🔀 This room continues a fork of "${await sessionTitle(bridge.ctx, sessionId)}". The original stays where it was.`)
|
|
356
|
+
await bridge.notice(roomId, `🔀 Forked into the new room "${title}".`)
|
|
357
|
+
},
|
|
358
|
+
|
|
359
|
+
async rename(bridge, { roomId }, args) {
|
|
360
|
+
const sessionId = sessionOf(bridge, roomId)
|
|
361
|
+
const name = args.trim()
|
|
362
|
+
if (name.length === 0 || name.length > 120) {
|
|
363
|
+
await bridge.notice(roomId, 'Usage: !rename <new name> (at most 120 characters)')
|
|
364
|
+
return
|
|
365
|
+
}
|
|
366
|
+
// The room is renamed where the bot may, and the session's title follows.
|
|
367
|
+
await bridge.matrix().sendState(roomId, 'm.room.name', '', { name }).catch(() => {})
|
|
368
|
+
await bridge.store().describeRoom(roomId, { roomName: name })
|
|
369
|
+
if (sessionId === undefined) {
|
|
370
|
+
await bridge.notice(roomId, `✏️ Room renamed to "${name}".`)
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
const record = bridge.store().room(roomId)
|
|
374
|
+
const title = roomTitle(record?.person ?? name, name)
|
|
375
|
+
const service = bridge.ctx.get('sessionTitle')
|
|
376
|
+
const session = (await bridge.ensureAgent(roomId)).session
|
|
377
|
+
if (service !== undefined) service.rename(session, title)
|
|
378
|
+
else await controllerOf(bridge.ctx)?.rename?.({ sessionId, title })
|
|
379
|
+
await bridge.store().describeRoom(roomId, { placeholderTitle: title })
|
|
380
|
+
await bridge.notice(roomId, `✏️ Session renamed to "${title}".`)
|
|
381
|
+
},
|
|
382
|
+
|
|
383
|
+
async goal(bridge, { roomId }, args) {
|
|
384
|
+
const goals = bridge.ctx.get('goals')
|
|
385
|
+
if (goals === undefined) {
|
|
386
|
+
await bridge.notice(roomId, 'Goals are not available in this DSH.')
|
|
387
|
+
return
|
|
388
|
+
}
|
|
389
|
+
const agent = await bridge.ensureAgent(roomId, { claim: true })
|
|
390
|
+
const [action = ''] = args.split(/\s+/u)
|
|
391
|
+
const verb = action.toLowerCase()
|
|
392
|
+
let view = goals.get(agent)
|
|
393
|
+
if (args.length === 0) {
|
|
394
|
+
await bridge.notice(roomId, goalStatus(view))
|
|
395
|
+
return
|
|
396
|
+
}
|
|
397
|
+
if (verb === 'clear' || verb === 'delete') {
|
|
398
|
+
if (view !== undefined) goals.clear(agent, { id: view.id, revision: view.revision })
|
|
399
|
+
await bridge.notice(roomId, view === undefined ? '🎯 No goal to clear.' : '🎯 Goal cleared.')
|
|
400
|
+
return
|
|
401
|
+
}
|
|
402
|
+
if (verb === 'pause') {
|
|
403
|
+
if (view === undefined) {
|
|
404
|
+
await bridge.notice(roomId, '🎯 No goal to pause.')
|
|
405
|
+
return
|
|
406
|
+
}
|
|
407
|
+
view = goals.pause(agent, { id: view.id, revision: view.revision })
|
|
408
|
+
await bridge.notice(roomId, goalStatus(view))
|
|
409
|
+
return
|
|
410
|
+
}
|
|
411
|
+
if (verb === 'resume') {
|
|
412
|
+
if (view === undefined || view.phase === 'complete') {
|
|
413
|
+
await bridge.notice(roomId, view === undefined ? '🎯 No goal is set.' : '🎯 The goal is already complete.')
|
|
414
|
+
return
|
|
415
|
+
}
|
|
416
|
+
if (!(view.phase === 'active' && view.activation === 'armed')) view = goals.resume(agent, { id: view.id, revision: view.revision })
|
|
417
|
+
await bridge.notice(roomId, goalStatus(view))
|
|
418
|
+
return
|
|
419
|
+
}
|
|
420
|
+
const objective = verb === 'edit' || verb === 'set' ? args.slice(action.length).trim() : args
|
|
421
|
+
if (objective.length === 0) {
|
|
422
|
+
await bridge.notice(roomId, 'Usage: !goal <objective>')
|
|
423
|
+
return
|
|
424
|
+
}
|
|
425
|
+
if (view !== undefined && view.phase !== 'complete') {
|
|
426
|
+
view = goals.edit(agent, { id: view.id, revision: view.revision }, { objective })
|
|
427
|
+
if (view.phase !== 'active' || view.activation !== 'armed') {
|
|
428
|
+
try {
|
|
429
|
+
view = goals.resume(agent, { id: view.id, revision: view.revision })
|
|
430
|
+
} catch (error) {
|
|
431
|
+
bridge.warn(`goal resume after edit failed: ${error?.message ?? error}`)
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
} else {
|
|
435
|
+
if (view !== undefined) goals.clear(agent, { id: view.id, revision: view.revision })
|
|
436
|
+
view = goals.create(agent, { objective })
|
|
437
|
+
}
|
|
438
|
+
bridge.roomState(roomId).goalPhase = view.phase
|
|
439
|
+
await bridge.notice(roomId, goalStatus(view))
|
|
440
|
+
},
|
|
441
|
+
|
|
442
|
+
...CONTROL_HANDLERS,
|
|
443
|
+
|
|
444
|
+
async allow(bridge, { roomId }) {
|
|
445
|
+
const tool = bridge.prompts.settleApproval(roomId, true)
|
|
446
|
+
await bridge.notice(roomId, tool === undefined ? 'No tool request is waiting.' : `✅ Allowed ${tool}.`)
|
|
447
|
+
},
|
|
448
|
+
|
|
449
|
+
async deny(bridge, { roomId }) {
|
|
450
|
+
const tool = bridge.prompts.settleApproval(roomId, false)
|
|
451
|
+
await bridge.notice(roomId, tool === undefined ? 'No tool request is waiting.' : `❌ Denied ${tool}.`)
|
|
452
|
+
},
|
|
453
|
+
|
|
454
|
+
async restart(bridge, { roomId }) {
|
|
455
|
+
await bridge.notice(roomId, '♻️ Reconnecting to the homeserver…')
|
|
456
|
+
bridge.restart('command')
|
|
457
|
+
},
|
|
458
|
+
}
|
|
459
|
+
|
package/src/config.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** Editable plugin configuration. Every field is volatile: it is read live. */
|
|
2
|
+
import z from '@deepseek-ai/schemastery'
|
|
3
|
+
|
|
4
|
+
export const Config = z.object({
|
|
5
|
+
/** Whether the bot runs while this profile runs. */
|
|
6
|
+
enabled: z.boolean().default(true).volatile(),
|
|
7
|
+
/** Homeserver base URL, such as https://matrix.example.org. */
|
|
8
|
+
homeserver: z.string().default('').volatile(),
|
|
9
|
+
/** The bot's own Matrix user id, such as @bot:example.org. */
|
|
10
|
+
userId: z.string().default('').volatile(),
|
|
11
|
+
/** File holding the bot account's password (mode 0600), read only to log in. */
|
|
12
|
+
passwordFile: z.string().default('').volatile(),
|
|
13
|
+
/**
|
|
14
|
+
* File the recovery key is written to when the bot sets up encryption for
|
|
15
|
+
* the account, and read from when a new device of the bot joins it. Empty
|
|
16
|
+
* uses `recovery-key` in the bot's data directory.
|
|
17
|
+
*/
|
|
18
|
+
recoveryKeyFile: z.string().default('').volatile(),
|
|
19
|
+
/** Name of the bot's device in people's device lists. */
|
|
20
|
+
deviceName: z.string().default('DSH').volatile(),
|
|
21
|
+
/** Display name of the bot account; empty keeps the current one. */
|
|
22
|
+
displayName: z.string().default('').volatile(),
|
|
23
|
+
/** Absolute path of a picture used as the bot's avatar; empty keeps the current one. */
|
|
24
|
+
avatar: z.string().default('').volatile(),
|
|
25
|
+
/** Name of each person's Space; empty uses the bot's display name. */
|
|
26
|
+
spaceName: z.string().default('').volatile(),
|
|
27
|
+
/**
|
|
28
|
+
* People who may talk to the bot, by Matrix user id. `name` is how their
|
|
29
|
+
* messages are labelled for the agent and in session titles. An entry
|
|
30
|
+
* without a user id is skipped. Everyone else is ignored.
|
|
31
|
+
*/
|
|
32
|
+
allowedUsers: z.array(z.object({
|
|
33
|
+
userId: z.string().default(''),
|
|
34
|
+
name: z.string().default(''),
|
|
35
|
+
})).default([]).volatile(),
|
|
36
|
+
/** Working directory of sessions the bot creates. */
|
|
37
|
+
cwd: z.string().default(process.cwd()).volatile(),
|
|
38
|
+
/** Agent preset of sessions the bot creates; empty uses the Host default. */
|
|
39
|
+
agentPreset: z.string().default('').volatile(),
|
|
40
|
+
/**
|
|
41
|
+
* Also show turns started elsewhere (Web UI, scheduled tasks, other plugins)
|
|
42
|
+
* in the room bound to their session.
|
|
43
|
+
*/
|
|
44
|
+
mirrorTurns: z.boolean().default(true).volatile(),
|
|
45
|
+
/**
|
|
46
|
+
* Messages sent while the session's turn runs: `steer` sends them into that
|
|
47
|
+
* turn (as the Web UI does); `queue` holds them until the turn ends.
|
|
48
|
+
*/
|
|
49
|
+
busyMessages: z.union(['steer', 'queue']).default('steer').volatile(),
|
|
50
|
+
/** Show answers while they are written, by editing the message in place. */
|
|
51
|
+
streaming: z.boolean().default(true).volatile(),
|
|
52
|
+
/**
|
|
53
|
+
* How voice messages and audio files become text: `dsh` uses the DSH
|
|
54
|
+
* speech-to-text service (decoded with ffmpeg), `command` runs
|
|
55
|
+
* `transcribeCommand`, `off` passes only the file.
|
|
56
|
+
*/
|
|
57
|
+
transcriber: z.union(['dsh', 'command', 'off']).default('dsh').volatile(),
|
|
58
|
+
/** Language hint for the DSH speech-to-text service; empty uses its setting. */
|
|
59
|
+
transcribeLanguage: z.string().default('').volatile(),
|
|
60
|
+
/**
|
|
61
|
+
* Program and arguments for `transcriber: command`, run without a shell.
|
|
62
|
+
* `{file}` is replaced by the recording's path (appended when absent).
|
|
63
|
+
*/
|
|
64
|
+
transcribeCommand: z.array(z.string()).default([]).volatile(),
|
|
65
|
+
/** ffmpeg program used to decode recordings for the DSH service. */
|
|
66
|
+
ffmpegPath: z.string().default('ffmpeg').volatile(),
|
|
67
|
+
})
|
package/src/constants.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** Shared constants and on-disk locations. */
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
/** Loader row id and settings namespace; the npm package is @soffits/dsh-matrix-bot. */
|
|
6
|
+
export const name = 'matrix-bot'
|
|
7
|
+
|
|
8
|
+
/** Name of the Host service other plugins send through. */
|
|
9
|
+
export const SERVICE_NAME = 'matrixRooms'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Directory holding everything the bot keeps: the login, the crypto store,
|
|
13
|
+
* the sync token, the room → session map, the spool and diagnostics. Read at
|
|
14
|
+
* call time, so tests and throwaway homes can move it with DSH_HOME.
|
|
15
|
+
* @returns absolute path.
|
|
16
|
+
*/
|
|
17
|
+
export function dataDir() {
|
|
18
|
+
return join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'matrix')
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @returns the request spool used by the `dsh-matrix` command. */
|
|
22
|
+
export function spoolDir() {
|
|
23
|
+
return join(dataDir(), 'spool')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A final answer ending in exactly this text posts nothing more in the room. */
|
|
27
|
+
export const SILENT_REPLY = '[SILENT]'
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Longest text sent as one Matrix message. Events are limited to 64 KiB
|
|
31
|
+
* after encryption, and the HTML copy of the text travels in the same event.
|
|
32
|
+
*/
|
|
33
|
+
export const MAX_MESSAGE_TEXT = 12_000
|
|
34
|
+
|
|
35
|
+
/** Reaction that tells the sender a message is being worked on. */
|
|
36
|
+
export const WORKING_REACTION = '⏳'
|
|
37
|
+
|
|
38
|
+
/** Reaction that tells the sender a message reached the running turn. */
|
|
39
|
+
export const STEER_REACTION = '👀'
|
|
40
|
+
|
|
41
|
+
/** Reactions that answer an approval request. */
|
|
42
|
+
export const ALLOW_REACTION = '👍'
|
|
43
|
+
export const DENY_REACTION = '👎'
|
|
44
|
+
|
|
45
|
+
/** Reactions that pick options 1 to 10 of a question. */
|
|
46
|
+
export const NUMBER_REACTIONS = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟']
|
|
47
|
+
|
|
48
|
+
/** Prefix of the request ids of prompts that came from Matrix. */
|
|
49
|
+
export const REQUEST_PREFIX = 'matrix:'
|
|
50
|
+
|
|
51
|
+
/** Source kind of the copy a send leaves in the bound session. */
|
|
52
|
+
export const POST_SOURCE_KIND = 'matrix-post'
|
|
53
|
+
|
|
54
|
+
/** Largest file sent or attached, in bytes. */
|
|
55
|
+
export const MAX_FILE_BYTES = 50 * 1024 * 1024
|
|
56
|
+
|
|
57
|
+
/** Shortest pause between two edits of a streamed answer. */
|
|
58
|
+
export const STREAM_EDIT_MS = 2_000
|
|
59
|
+
|
|
60
|
+
/** How long one typing notice lasts; it is renewed while the turn runs. */
|
|
61
|
+
export const TYPING_MS = 30_000
|
|
62
|
+
|
|
63
|
+
/** Command prefixes: `!` works in every client, `/` where the client sends it. */
|
|
64
|
+
export const COMMAND_PREFIXES = ['!', '/']
|
|
65
|
+
|
|
66
|
+
/** Unstable event types of the bot command proposals (MSC4332, MSC4391). */
|
|
67
|
+
export const MSC4332_COMMANDS = 'org.matrix.msc4332.commands'
|
|
68
|
+
export const MSC4332_COMMAND = 'org.matrix.msc4332.command'
|
|
69
|
+
export const MSC4391_DESCRIPTION = 'org.matrix.msc4391.command_description'
|
|
70
|
+
export const MSC4391_COMMAND = 'org.matrix.msc4391.command'
|