@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/sessions.js
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DSH side of a room: creating, resuming and prompting sessions through
|
|
3
|
+
* the same Host services the Web UI uses (`sessionController`), with the raw
|
|
4
|
+
* agent registry as the headless fallback.
|
|
5
|
+
*/
|
|
6
|
+
import { randomUUID } from 'node:crypto'
|
|
7
|
+
import { basename } from 'node:path'
|
|
8
|
+
import { REQUEST_PREFIX } from './constants.js'
|
|
9
|
+
|
|
10
|
+
/** @returns the Web session controller, when this deployment mounts it. */
|
|
11
|
+
export function controllerOf(ctx) {
|
|
12
|
+
const controller = ctx.get('sessionController')
|
|
13
|
+
return typeof controller?.create === 'function' && typeof controller?.resolveAgent === 'function' ? controller : undefined
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The live agent of a session, resuming it when needed.
|
|
18
|
+
* @param ctx - Host context.
|
|
19
|
+
* @param sessionId - session id.
|
|
20
|
+
* @returns the agent; throws when the session cannot be resumed.
|
|
21
|
+
*/
|
|
22
|
+
export async function resolveAgent(ctx, sessionId) {
|
|
23
|
+
const agents = ctx.get('agents')
|
|
24
|
+
const live = agents?.get(sessionId)
|
|
25
|
+
if (live !== undefined) return live
|
|
26
|
+
const controller = controllerOf(ctx)
|
|
27
|
+
if (controller !== undefined) {
|
|
28
|
+
const found = await controller.resolveAgent(sessionId)
|
|
29
|
+
if (found?.error !== undefined) throw found.error
|
|
30
|
+
const agent = found?.agent ?? agents?.get(sessionId)
|
|
31
|
+
if (agent === undefined) throw new Error(`session ${sessionId} has no live agent`)
|
|
32
|
+
return agent
|
|
33
|
+
}
|
|
34
|
+
if (agents === undefined) throw new Error('dsh-agent is not mounted in this profile')
|
|
35
|
+
const resumed = await agents.resume({ resumeSessionId: sessionId })
|
|
36
|
+
if (resumed?.agent === undefined) throw new Error(`session ${sessionId} could not be resumed`)
|
|
37
|
+
return resumed.agent
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Attach a session to the DSH workspace of its directory, creating the
|
|
42
|
+
* workspace when needed, so it shows up in the Web UI sidebar.
|
|
43
|
+
* @param ctx - Host context.
|
|
44
|
+
* @param sessionId - session id.
|
|
45
|
+
* @param cwd - session directory.
|
|
46
|
+
* @param warn - logger.
|
|
47
|
+
*/
|
|
48
|
+
async function attachToWorkspace(ctx, sessionId, cwd, warn) {
|
|
49
|
+
const registry = ctx.get('workspaceRegistry')
|
|
50
|
+
if (registry === undefined) return
|
|
51
|
+
try {
|
|
52
|
+
let workspace = registry.list().find((entry) => entry.path === cwd)
|
|
53
|
+
if (workspace === undefined) workspace = await registry.create(cwd)
|
|
54
|
+
await workspace.attachSession(sessionId)
|
|
55
|
+
} catch (error) {
|
|
56
|
+
warn(`workspace attach failed for ${sessionId}: ${error?.message ?? error}`)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* End a new session's blank state with an empty turn that never reaches a
|
|
62
|
+
* model. DSH hands a blank session (one that never started a turn) to the
|
|
63
|
+
* next New conversation in the Web UI; a room's session must not be taken
|
|
64
|
+
* that way. The marker message is rejected at `agent/pre-step`, the same gate
|
|
65
|
+
* DSH uses for archived sessions, so the turn ends as blocked and the marker
|
|
66
|
+
* is never recorded.
|
|
67
|
+
* @param agent - the new session's agent.
|
|
68
|
+
* @param roomId - Matrix room id, for the marker text.
|
|
69
|
+
*/
|
|
70
|
+
async function claimSession(agent, roomId) {
|
|
71
|
+
if (typeof agent?.followup !== 'function' || typeof agent?.ctx?.on !== 'function') return
|
|
72
|
+
const id = randomUUID()
|
|
73
|
+
const dispose = agent.ctx.on('agent/pre-step', (payload, next) => {
|
|
74
|
+
const messages = Array.isArray(payload?.messages) ? payload.messages : []
|
|
75
|
+
if (messages.length > 0 && messages.every((message) => message?.id === id)) return Promise.resolve({ kind: 'reject' })
|
|
76
|
+
return next()
|
|
77
|
+
})
|
|
78
|
+
agent.followup({
|
|
79
|
+
id,
|
|
80
|
+
role: 'user',
|
|
81
|
+
content: [{ type: 'text', text: `[This session belongs to Matrix room ${roomId}]` }],
|
|
82
|
+
source: { kind: 'user', rpcId: `matrix-claim:${id}` },
|
|
83
|
+
})
|
|
84
|
+
const idle = typeof agent.whenIdle === 'function' ? agent.whenIdle() : Promise.resolve()
|
|
85
|
+
void idle.catch(() => undefined).finally(() => { if (typeof dispose === 'function') dispose() })
|
|
86
|
+
let timer
|
|
87
|
+
await Promise.race([
|
|
88
|
+
idle.catch(() => undefined),
|
|
89
|
+
new Promise((resolveWait) => { timer = setTimeout(resolveWait, 10_000) }),
|
|
90
|
+
])
|
|
91
|
+
clearTimeout(timer)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Create a session for a room, composed the way the Web UI composes one.
|
|
96
|
+
* @param ctx - Host context.
|
|
97
|
+
* @param options - `{ cwd, preset, model, roomId, claim, warn }`; `claim` ends
|
|
98
|
+
* the blank state at once (for sessions that will not get a prompt now).
|
|
99
|
+
* @returns the new session's agent.
|
|
100
|
+
*/
|
|
101
|
+
export async function createSession(ctx, { cwd, preset, model, roomId, claim, warn }) {
|
|
102
|
+
const controller = controllerOf(ctx)
|
|
103
|
+
let agent
|
|
104
|
+
if (controller !== undefined) {
|
|
105
|
+
try {
|
|
106
|
+
const created = await controller.create({ cwd, ...(preset ? { agentPreset: preset } : {}) })
|
|
107
|
+
agent = await resolveAgent(ctx, created.sessionId)
|
|
108
|
+
} catch (error) {
|
|
109
|
+
warn(`sessionController create failed, using the agent registry: ${error?.message ?? error}`)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (agent === undefined) {
|
|
113
|
+
const agents = ctx.get('agents')
|
|
114
|
+
if (agents === undefined) throw new Error('dsh-agent is not mounted in this profile')
|
|
115
|
+
const meta = { cwd, ...(preset && ctx.get('agentPresets') !== undefined ? { agentPreset: preset } : {}) }
|
|
116
|
+
const presets = ctx.get('agentPresets')
|
|
117
|
+
const setup = preset && presets !== undefined
|
|
118
|
+
? async (agentCtx) => {
|
|
119
|
+
try {
|
|
120
|
+
await presets.mount(agentCtx, preset)
|
|
121
|
+
} catch (error) {
|
|
122
|
+
warn(`preset ${preset} not mounted: ${error?.message ?? error}`)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
: undefined
|
|
126
|
+
agent = (await agents.create({ sessionId: `session-${randomUUID()}`, meta, ...(setup ? { setup } : {}) })).agent
|
|
127
|
+
}
|
|
128
|
+
const sessionId = agent.session?.id ?? agent.id
|
|
129
|
+
if (model !== undefined) {
|
|
130
|
+
try {
|
|
131
|
+
agent.model.select(model)
|
|
132
|
+
} catch (error) {
|
|
133
|
+
warn(`could not start ${sessionId} on ${model.provider}/${model.model}: ${error?.message ?? error}`)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (claim) await claimSession(agent, roomId)
|
|
137
|
+
await attachToWorkspace(ctx, sessionId, cwd, warn)
|
|
138
|
+
return agent
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Bring an archived session back before a room message starts a turn in it:
|
|
143
|
+
* DSH admits prompts into archived sessions but rejects every model step.
|
|
144
|
+
* @param ctx - Host context.
|
|
145
|
+
* @param sessionId - session id.
|
|
146
|
+
* @returns true when the session was unarchived.
|
|
147
|
+
*/
|
|
148
|
+
export async function unarchive(ctx, sessionId) {
|
|
149
|
+
const registry = ctx.get('workspaceRegistry')
|
|
150
|
+
if (registry?.archivedSessionIds?.includes(sessionId) !== true || typeof registry.unarchiveSession !== 'function') return false
|
|
151
|
+
await registry.unarchiveSession(sessionId)
|
|
152
|
+
return true
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** @returns whether a message the agent has not taken yet carries this request id. */
|
|
156
|
+
export function inInbox(agent, requestId) {
|
|
157
|
+
const matches = (message) => message?.source?.kind === 'user' && message.source.rpcId === requestId
|
|
158
|
+
const inbox = agent?.inbox
|
|
159
|
+
return inbox?.nextTurn?.some?.(matches) === true || inbox?.nextStep?.some?.(matches) === true
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** @returns whether a pending or recorded message carries this request id. */
|
|
163
|
+
export function hasRequest(agent, requestId) {
|
|
164
|
+
if (inInbox(agent, requestId)) return true
|
|
165
|
+
const matches = (message) => message?.source?.kind === 'user' && message.source.rpcId === requestId
|
|
166
|
+
const events = typeof agent?.session?.snapshotEvents === 'function' ? agent.session.snapshotEvents() : []
|
|
167
|
+
return events.some((event) => event?.type === 'user/message' && matches(event.data))
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Hand one prompt to a session. Text goes through the Session controller's
|
|
172
|
+
* `prompt`, the Web UI's own path; prompts with stored attachments go to the
|
|
173
|
+
* agent's `followup` (queue) or `steer` (into the running turn), the methods
|
|
174
|
+
* that path calls. A request id already admitted is skipped, so a message
|
|
175
|
+
* handled twice (a restart between admission and marking it seen) reaches the
|
|
176
|
+
* agent once.
|
|
177
|
+
* @param ctx - Host context.
|
|
178
|
+
* @param agent - the session's agent.
|
|
179
|
+
* @param prompt - `{ requestId, text, attachments, mode, principal }`; `mode` is
|
|
180
|
+
* `queue` or `steer`; `principal` is recorded on prompts built here (the
|
|
181
|
+
* controller's prompts get it at their step, see `createPrincipalTagger`).
|
|
182
|
+
* @param signal - request lifetime.
|
|
183
|
+
* @returns whether the prompt was handed over (false for a duplicate or an empty one).
|
|
184
|
+
*/
|
|
185
|
+
export async function admitPrompt(ctx, agent, { requestId, text, attachments = [], mode, principal, envelope }, signal) {
|
|
186
|
+
if (hasRequest(agent, requestId)) return false
|
|
187
|
+
const content = [...(text.trim().length === 0 ? [] : [{ type: 'text', text }]), ...attachments]
|
|
188
|
+
if (content.length === 0) return false
|
|
189
|
+
const controller = ctx.get('sessionController')
|
|
190
|
+
const sessionId = agent.session?.id ?? agent.id
|
|
191
|
+
if (attachments.length === 0 && typeof controller?.prompt === 'function') {
|
|
192
|
+
await controller.prompt({ sessionId, requestId, mode, content }, signal)
|
|
193
|
+
return true
|
|
194
|
+
}
|
|
195
|
+
const message = { id: randomUUID(), role: 'user', content, source: { kind: 'user', rpcId: requestId, ...(principal === undefined ? {} : { principal }), ...(envelope === undefined ? {} : { envelope }) } }
|
|
196
|
+
if (mode === 'steer' && typeof agent.steer === 'function') agent.steer(message)
|
|
197
|
+
else if (typeof agent.followup === 'function') agent.followup(message)
|
|
198
|
+
else agent.send(message, mode === 'steer' ? 'next-step' : 'next-turn', true)
|
|
199
|
+
return true
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Remove prompts from one room that the agent has not taken yet.
|
|
204
|
+
* @param agent - the session's agent.
|
|
205
|
+
* @param roomId - Matrix room id.
|
|
206
|
+
* @returns how many were removed.
|
|
207
|
+
*/
|
|
208
|
+
export function clearRoomInbox(agent, roomId) {
|
|
209
|
+
const inbox = agent?.inbox
|
|
210
|
+
if (typeof inbox?.remove !== 'function') return 0
|
|
211
|
+
const prefix = `${REQUEST_PREFIX}${roomId}:`
|
|
212
|
+
const ours = (message) => message?.source?.kind === 'user' && typeof message.source.rpcId === 'string' && message.source.rpcId.startsWith(prefix)
|
|
213
|
+
const pending = [...(inbox.nextStep ?? []), ...(inbox.nextTurn ?? [])].filter(ours)
|
|
214
|
+
for (const message of pending) inbox.remove(message.id)
|
|
215
|
+
return pending.length
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** @returns whether the agent still holds input it has not taken. */
|
|
219
|
+
export function hasPendingInput(agent) {
|
|
220
|
+
const inbox = agent?.inbox
|
|
221
|
+
if (inbox === undefined) return false
|
|
222
|
+
if (typeof inbox.hasPending === 'boolean') return inbox.hasPending
|
|
223
|
+
return (inbox.nextStep?.length ?? 0) > 0 || (inbox.nextTurn?.length ?? 0) > 0
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Whether a session's first surface node is its system message, the only
|
|
228
|
+
* state in which a message may be appended outside a step.
|
|
229
|
+
* @param session - DSH session.
|
|
230
|
+
*/
|
|
231
|
+
function hasSystemHead(session) {
|
|
232
|
+
try {
|
|
233
|
+
const nodes = session.surface?.nodes
|
|
234
|
+
if (nodes !== undefined) {
|
|
235
|
+
if (nodes.length === 0) return false
|
|
236
|
+
const event = typeof session.eventAt === 'function'
|
|
237
|
+
? session.eventAt(nodes[0])
|
|
238
|
+
: session.snapshotEvents?.().find((item) => item.seq === nodes[0])
|
|
239
|
+
return event?.type === 'system/message'
|
|
240
|
+
}
|
|
241
|
+
const events = typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : session.events
|
|
242
|
+
if (!Array.isArray(events)) return false
|
|
243
|
+
const surfaceTypes = new Set(['system/message', 'user/message', 'developer/message', 'assistant/message', 'tool/result'])
|
|
244
|
+
return events.find((event) => surfaceTypes.has(event.type))?.type === 'system/message'
|
|
245
|
+
} catch {
|
|
246
|
+
return false
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Put a message into a session without starting a turn: appended now to an
|
|
252
|
+
* idle session, otherwise queued for its next step. The Web UI shows it and
|
|
253
|
+
* the model reads it at its next step.
|
|
254
|
+
* @param agent - the session's agent.
|
|
255
|
+
* @param message - a user-role message (`{ id, role, content, source }`).
|
|
256
|
+
*/
|
|
257
|
+
export function recordMessage(agent, message) {
|
|
258
|
+
if (agent.status === 'idle' && typeof agent.session?.append === 'function' && hasSystemHead(agent.session)) {
|
|
259
|
+
agent.session.append('user/message', message, { surfaceOp: 'append' })
|
|
260
|
+
} else if (typeof agent.inject === 'function') {
|
|
261
|
+
agent.inject(message)
|
|
262
|
+
} else if (typeof agent.send === 'function') {
|
|
263
|
+
agent.send(message, 'next-step', false)
|
|
264
|
+
} else {
|
|
265
|
+
throw new Error('The session cannot record messages.')
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* A session's title, or a short fallback.
|
|
271
|
+
* @param ctx - Host context.
|
|
272
|
+
* @param sessionId - session id.
|
|
273
|
+
* @param header - session header when known.
|
|
274
|
+
*/
|
|
275
|
+
export async function sessionTitle(ctx, sessionId, header) {
|
|
276
|
+
try {
|
|
277
|
+
const snapshot = await ctx.get('sessionQuery')?.readTitleSnapshot(sessionId)
|
|
278
|
+
const title = snapshot?.title?.title
|
|
279
|
+
if (typeof title === 'string' && title.trim().length > 0) return title.trim()
|
|
280
|
+
} catch {
|
|
281
|
+
// No title yet.
|
|
282
|
+
}
|
|
283
|
+
const base = typeof header?.cwd === 'string' && header.cwd.length > 0 ? basename(header.cwd) : 'Session'
|
|
284
|
+
return `${base} · ${String(sessionId).slice(-6)}`
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* The latest assistant texts of a session, newest first.
|
|
289
|
+
* @param ctx - Host context.
|
|
290
|
+
* @param sessionId - session id.
|
|
291
|
+
* @param limit - most texts.
|
|
292
|
+
*/
|
|
293
|
+
export async function recentAssistantTexts(ctx, sessionId, limit) {
|
|
294
|
+
const texts = []
|
|
295
|
+
try {
|
|
296
|
+
const surface = await ctx.get('sessionQuery')?.readSurface(sessionId)
|
|
297
|
+
const events = surface?.events ?? []
|
|
298
|
+
for (let index = events.length - 1; index >= 0 && texts.length < limit; index -= 1) {
|
|
299
|
+
const event = events[index]
|
|
300
|
+
if (event?.type !== 'assistant/message') continue
|
|
301
|
+
const message = event.data?.message ?? event.data
|
|
302
|
+
const content = Array.isArray(message?.content) ? message.content : []
|
|
303
|
+
const text = content.filter((block) => block?.type === 'text').map((block) => block.text).join('\n').trim()
|
|
304
|
+
if (text.length > 0) texts.push(text)
|
|
305
|
+
}
|
|
306
|
+
} catch {
|
|
307
|
+
// An empty result is reported by the caller.
|
|
308
|
+
}
|
|
309
|
+
return texts
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** @returns the registered workspaces, or an empty list. */
|
|
313
|
+
export function listWorkspaces(ctx) {
|
|
314
|
+
try {
|
|
315
|
+
return ctx.get('workspaceRegistry')?.list() ?? []
|
|
316
|
+
} catch {
|
|
317
|
+
return []
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Recent ordinary sessions of a workspace, newest first.
|
|
323
|
+
* @param ctx - Host context.
|
|
324
|
+
* @param workspace - workspace record.
|
|
325
|
+
* @param limit - most sessions.
|
|
326
|
+
* @param signal - request lifetime.
|
|
327
|
+
*/
|
|
328
|
+
export async function sessionsInWorkspace(ctx, workspace, limit, signal) {
|
|
329
|
+
const query = ctx.get('sessionQuery')
|
|
330
|
+
if (query === undefined) return []
|
|
331
|
+
const archived = new Set(ctx.get('workspaceRegistry')?.archivedSessionIds ?? [])
|
|
332
|
+
const records = await query.listSessions(signal)
|
|
333
|
+
return records
|
|
334
|
+
.filter((record) => !archived.has(record.header.id))
|
|
335
|
+
.filter((record) => record.header?.origin !== 'subagent')
|
|
336
|
+
.filter((record) => (workspace.sessionIds ?? []).includes(record.header.id) || record.header.cwd === workspace.path)
|
|
337
|
+
.sort((left, right) => (right.header.createdAt ?? 0) - (left.header.createdAt ?? 0))
|
|
338
|
+
.slice(0, limit)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* The access mode (permission preset) of a session.
|
|
343
|
+
* @param ctx - Host context.
|
|
344
|
+
* @param agent - live agent, or undefined.
|
|
345
|
+
* @returns the preset value, or undefined when unknown.
|
|
346
|
+
*/
|
|
347
|
+
export function currentPermission(ctx, agent) {
|
|
348
|
+
const service = ctx.get('permissionPresets')
|
|
349
|
+
try {
|
|
350
|
+
if (agent !== undefined && typeof service?.current === 'function') return service.current(agent.session)
|
|
351
|
+
} catch {
|
|
352
|
+
// Unknown.
|
|
353
|
+
}
|
|
354
|
+
return service?.defaultPreset
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Access modes offered by this deployment.
|
|
359
|
+
* @param ctx - Host context.
|
|
360
|
+
* @returns `{ value, name }` entries.
|
|
361
|
+
*/
|
|
362
|
+
export function permissionOptions(ctx) {
|
|
363
|
+
try {
|
|
364
|
+
const options = ctx.get('permissionPresets')?.catalog()?.options
|
|
365
|
+
if (Array.isArray(options) && options.length > 0) return options.map((option) => ({ value: option.value, name: option.name ?? option.value }))
|
|
366
|
+
} catch {
|
|
367
|
+
// Fall through.
|
|
368
|
+
}
|
|
369
|
+
return [{ value: 'workspace-write', name: 'workspace-write' }, { value: 'danger-full-access', name: 'danger-full-access' }]
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Set a session's access mode.
|
|
374
|
+
* @param ctx - Host context.
|
|
375
|
+
* @param agent - live agent.
|
|
376
|
+
* @param value - preset value.
|
|
377
|
+
*/
|
|
378
|
+
export function setPermission(ctx, agent, value) {
|
|
379
|
+
const service = ctx.get('permissionPresets')
|
|
380
|
+
if (typeof service?.set === 'function') {
|
|
381
|
+
service.set(agent.session, value)
|
|
382
|
+
return
|
|
383
|
+
}
|
|
384
|
+
const specs = { 'workspace-write': ['workspace-write', 'ask'], 'danger-full-access': ['danger-full-access', 'never'], 'read-only': ['read-only', 'ask'] }
|
|
385
|
+
const spec = specs[value]
|
|
386
|
+
if (spec === undefined) throw new Error(`unknown access mode ${value}`)
|
|
387
|
+
agent.session.append('permission/preset', { preset: value })
|
|
388
|
+
agent.session.append('sandbox/mode', { mode: spec[0] })
|
|
389
|
+
agent.session.append('approval/policy', { policy: spec[1] })
|
|
390
|
+
}
|
package/src/spaces.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Each allowed person's private Space and the rooms in it: making a Space
|
|
3
|
+
* and its lobby, adopting a Space the person made, joining rooms that appear
|
|
4
|
+
* in it, making new rooms, and publishing the command list in each room.
|
|
5
|
+
*/
|
|
6
|
+
import { MSC4332_COMMANDS, MSC4391_DESCRIPTION } from './constants.js'
|
|
7
|
+
|
|
8
|
+
/** Encryption of every room the bot makes. */
|
|
9
|
+
const ENCRYPTION = { type: 'm.room.encryption', state_key: '', content: { algorithm: 'm.megolm.v1.aes-sha2' } }
|
|
10
|
+
/** Power level that may add rooms to a Space when its power levels don't say. */
|
|
11
|
+
const DEFAULT_STATE_LEVEL = 50
|
|
12
|
+
|
|
13
|
+
/** @returns the server part of a user or room id. */
|
|
14
|
+
export function serverOf(id) {
|
|
15
|
+
return String(id).slice(String(id).indexOf(':') + 1)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The power level a Space needs from the bot to add rooms to it, and the
|
|
20
|
+
* bot's own level there.
|
|
21
|
+
* @param powerLevels - the Space's `m.room.power_levels` content.
|
|
22
|
+
* @param userId - the bot.
|
|
23
|
+
* @returns `{ needed, own }`.
|
|
24
|
+
*/
|
|
25
|
+
export function childLevels(powerLevels, userId) {
|
|
26
|
+
const levels = powerLevels ?? {}
|
|
27
|
+
const needed = levels.events?.['m.space.child'] ?? levels.state_default ?? DEFAULT_STATE_LEVEL
|
|
28
|
+
const own = levels.users?.[userId] ?? levels.users_default ?? 0
|
|
29
|
+
return { needed, own }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The command list in the two proposal formats.
|
|
34
|
+
* @param commands - `[name, description, usage?]` entries.
|
|
35
|
+
* @param sigil - prefix clients should put before the command.
|
|
36
|
+
* @returns `{ msc4332, msc4391 }`: the MSC4332 content and the MSC4391 contents by command.
|
|
37
|
+
*/
|
|
38
|
+
export function commandStates(commands, sigil) {
|
|
39
|
+
const text = (body) => ({ 'm.text': [{ body }] })
|
|
40
|
+
const msc4332 = {
|
|
41
|
+
sigil,
|
|
42
|
+
commands: commands.map(([command, description, usage]) => ({
|
|
43
|
+
syntax: usage ? `${command} {args}` : command,
|
|
44
|
+
...(usage ? { arguments: [{ type: 'string', description: text(usage), variadic: true }] } : {}),
|
|
45
|
+
description: text(description),
|
|
46
|
+
})),
|
|
47
|
+
}
|
|
48
|
+
const msc4391 = Object.fromEntries(commands.map(([command, description, usage]) => [command, {
|
|
49
|
+
command,
|
|
50
|
+
description: text(description),
|
|
51
|
+
parameters: usage ? [{ key: 'args', schema: { schema_type: 'primitive', type: 'string' }, description: text(usage), optional: true }] : [],
|
|
52
|
+
}]))
|
|
53
|
+
return { msc4332, msc4391 }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Create the Space manager.
|
|
58
|
+
* @param deps - `{ requireMatrix, getStore, setting, notice, publishCommands, info, warn }`.
|
|
59
|
+
*/
|
|
60
|
+
export function createSpaces({ requireMatrix, getStore, setting, notice, commands, sigil, helpText, info, warn }) {
|
|
61
|
+
/** The last claim of a room or Space by person: claims of one person run one at a time. */
|
|
62
|
+
const claims = new Map()
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Run a claim after the person's earlier ones. An invite and the message
|
|
66
|
+
* already waiting in that room both claim it at once; one at a time, the
|
|
67
|
+
* later finds the room taken instead of making a second Space.
|
|
68
|
+
*/
|
|
69
|
+
function oneAtATime(userId, task) {
|
|
70
|
+
const run = (claims.get(userId) ?? Promise.resolve()).then(task)
|
|
71
|
+
const settled = run.catch(() => {})
|
|
72
|
+
claims.set(userId, settled)
|
|
73
|
+
void settled.then(() => { if (claims.get(userId) === settled) claims.delete(userId) })
|
|
74
|
+
return run
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** @returns the name of new Spaces and lobbies. */
|
|
78
|
+
async function names() {
|
|
79
|
+
const matrix = requireMatrix()
|
|
80
|
+
const display = String(setting('displayName', '')).trim() || await matrix.displayName()
|
|
81
|
+
return { space: String(setting('spaceName', '')).trim() || display, lobby: display }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Make the person an admin of a room the bot made. Done after creation:
|
|
86
|
+
* room version 12 refuses creators in the power levels, older versions
|
|
87
|
+
* would lose the bot's own level if `users` were overridden at creation.
|
|
88
|
+
*/
|
|
89
|
+
async function sharePower(roomId, userId) {
|
|
90
|
+
const matrix = requireMatrix()
|
|
91
|
+
const current = await matrix.getState(roomId, 'm.room.power_levels') ?? {}
|
|
92
|
+
if (current.users?.[userId] === 100) return
|
|
93
|
+
await matrix.sendState(roomId, 'm.room.power_levels', '', { ...current, users: { ...(current.users ?? {}), [userId]: 100 } })
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Publish the command list in a room for clients that offer autocomplete.
|
|
98
|
+
* Rooms where the bot may not set state are left without it.
|
|
99
|
+
*/
|
|
100
|
+
async function publishCommands(roomId) {
|
|
101
|
+
const matrix = requireMatrix()
|
|
102
|
+
const { msc4332, msc4391 } = commandStates(commands, sigil)
|
|
103
|
+
try {
|
|
104
|
+
await matrix.sendState(roomId, MSC4332_COMMANDS, matrix.userId, msc4332)
|
|
105
|
+
for (const [command, content] of Object.entries(msc4391)) await matrix.sendState(roomId, MSC4391_DESCRIPTION, command, content)
|
|
106
|
+
} catch (error) {
|
|
107
|
+
warn(`command list not published in ${roomId}: ${error?.message ?? error}`)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Link a room into a Space (both directions where the bot may). */
|
|
112
|
+
async function linkRoom(spaceId, roomId) {
|
|
113
|
+
const matrix = requireMatrix()
|
|
114
|
+
const via = [serverOf(matrix.userId)]
|
|
115
|
+
await matrix.sendState(spaceId, 'm.space.child', roomId, { via, suggested: true })
|
|
116
|
+
await matrix.sendState(roomId, 'm.space.parent', spaceId, { via, canonical: true }).catch(() => {})
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Make a room for a person in their Space and invite them.
|
|
121
|
+
* @param userId - the person.
|
|
122
|
+
* @param name - room name.
|
|
123
|
+
* @returns the room id.
|
|
124
|
+
*/
|
|
125
|
+
async function createRoom(userId, name) {
|
|
126
|
+
const matrix = requireMatrix()
|
|
127
|
+
const spaceId = await ensureSpace(userId)
|
|
128
|
+
const roomId = await matrix.createRoom({
|
|
129
|
+
name,
|
|
130
|
+
preset: 'private_chat',
|
|
131
|
+
visibility: 'private',
|
|
132
|
+
invite: [userId],
|
|
133
|
+
initial_state: [ENCRYPTION, { type: 'm.space.parent', state_key: spaceId, content: { via: [serverOf(matrix.userId)], canonical: true } }],
|
|
134
|
+
})
|
|
135
|
+
await sharePower(roomId, userId)
|
|
136
|
+
await matrix.sendState(spaceId, 'm.space.child', roomId, { via: [serverOf(matrix.userId)], suggested: true })
|
|
137
|
+
await getStore().describeRoom(roomId, { owner: userId, spaceId })
|
|
138
|
+
await publishCommands(roomId)
|
|
139
|
+
info(`made room ${roomId} in ${userId}'s Space`)
|
|
140
|
+
return roomId
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The person's Space, made with its lobby when they have none.
|
|
145
|
+
* @param userId - the person.
|
|
146
|
+
* @param options - `{ lobbyId }`: a room that becomes the lobby instead of a new one.
|
|
147
|
+
* @returns the Space id.
|
|
148
|
+
*/
|
|
149
|
+
async function ensureSpace(userId, { lobbyId } = {}) {
|
|
150
|
+
const store = getStore()
|
|
151
|
+
const known = store.person(userId)?.spaces?.at(-1)
|
|
152
|
+
if (known !== undefined) return known
|
|
153
|
+
const matrix = requireMatrix()
|
|
154
|
+
const { space, lobby } = await names()
|
|
155
|
+
const spaceId = await matrix.createRoom({
|
|
156
|
+
name: space,
|
|
157
|
+
preset: 'private_chat',
|
|
158
|
+
visibility: 'private',
|
|
159
|
+
invite: [userId],
|
|
160
|
+
creation_content: { type: 'm.space' },
|
|
161
|
+
power_level_content_override: { events_default: 100 },
|
|
162
|
+
})
|
|
163
|
+
await sharePower(spaceId, userId)
|
|
164
|
+
await store.addSpace(userId, spaceId)
|
|
165
|
+
info(`made a Space for ${userId}`)
|
|
166
|
+
if (lobbyId !== undefined) {
|
|
167
|
+
await linkRoom(spaceId, lobbyId)
|
|
168
|
+
await store.describeRoom(lobbyId, { owner: userId, spaceId })
|
|
169
|
+
await store.describePerson(userId, { lobbyId })
|
|
170
|
+
await greet(lobbyId)
|
|
171
|
+
} else {
|
|
172
|
+
const roomId = await createRoom(userId, lobby)
|
|
173
|
+
await store.describePerson(userId, { lobbyId: roomId })
|
|
174
|
+
await greet(roomId)
|
|
175
|
+
}
|
|
176
|
+
return spaceId
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Welcome a person in their lobby and pin the help there. */
|
|
180
|
+
async function greet(roomId) {
|
|
181
|
+
const [eventId] = await notice(roomId, helpText())
|
|
182
|
+
try {
|
|
183
|
+
await requireMatrix().sendState(roomId, 'm.room.pinned_events', '', { pinned: [eventId] })
|
|
184
|
+
} catch (error) {
|
|
185
|
+
warn(`help not pinned in ${roomId}: ${error?.message ?? error}`)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Take a Space a person made and invited the bot to as theirs, when the bot
|
|
191
|
+
* may add rooms to it.
|
|
192
|
+
* @returns true when adopted.
|
|
193
|
+
*/
|
|
194
|
+
async function adoptSpace(userId, spaceId) {
|
|
195
|
+
const matrix = requireMatrix()
|
|
196
|
+
const store = getStore()
|
|
197
|
+
const { needed, own } = childLevels(await matrix.getState(spaceId, 'm.room.power_levels'), matrix.userId)
|
|
198
|
+
if (own < needed) {
|
|
199
|
+
const lobbyId = store.person(userId)?.lobbyId
|
|
200
|
+
const text = `I joined your Space, but I can only add rooms to it with power level ${needed} (I have ${own}). Please give me power level ${needed} there.`
|
|
201
|
+
if (lobbyId !== undefined) await notice(lobbyId, text)
|
|
202
|
+
else await notice(spaceId, text)
|
|
203
|
+
await store.describePerson(userId, { waitingSpace: spaceId })
|
|
204
|
+
return false
|
|
205
|
+
}
|
|
206
|
+
await store.addSpace(userId, spaceId)
|
|
207
|
+
info(`adopted ${userId}'s Space ${spaceId}`)
|
|
208
|
+
for (const event of await matrix.roomState(spaceId)) {
|
|
209
|
+
if (event?.type === 'm.space.child') await onChild(spaceId, event)
|
|
210
|
+
}
|
|
211
|
+
if (store.person(userId)?.lobbyId === undefined) {
|
|
212
|
+
const roomId = await createRoom(userId, (await names()).lobby)
|
|
213
|
+
await store.describePerson(userId, { lobbyId: roomId })
|
|
214
|
+
await greet(roomId)
|
|
215
|
+
}
|
|
216
|
+
return true
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* A room was added to or removed from a person's Space: join a new one and
|
|
221
|
+
* make it theirs.
|
|
222
|
+
* @param spaceId - the Space.
|
|
223
|
+
* @param event - the `m.space.child` state event.
|
|
224
|
+
*/
|
|
225
|
+
async function onChild(spaceId, event) {
|
|
226
|
+
const store = getStore()
|
|
227
|
+
const owner = store.ownerOfSpace(spaceId)
|
|
228
|
+
const roomId = event.state_key
|
|
229
|
+
if (owner === undefined || typeof roomId !== 'string' || roomId.length === 0) return
|
|
230
|
+
const via = Array.isArray(event.content?.via) ? event.content.via : []
|
|
231
|
+
if (via.length === 0 || store.room(roomId)?.owner !== undefined) return
|
|
232
|
+
try {
|
|
233
|
+
await requireMatrix().join(roomId, via)
|
|
234
|
+
} catch (error) {
|
|
235
|
+
const lobbyId = store.person(owner)?.lobbyId
|
|
236
|
+
warn(`could not join ${roomId} from ${owner}'s Space: ${error?.message ?? error}`)
|
|
237
|
+
if (lobbyId !== undefined && lobbyId !== roomId) await notice(lobbyId, 'A new room in your Space is invite-only, so I could not join it. Invite me there and it gets its own session.')
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
await store.describeRoom(roomId, { owner, spaceId })
|
|
241
|
+
await publishCommands(roomId)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* A room an allowed person invited the bot to: a Space is adopted, any
|
|
246
|
+
* other room becomes theirs and goes into their Space.
|
|
247
|
+
* @param roomId - the joined room.
|
|
248
|
+
* @param userId - who invited the bot.
|
|
249
|
+
*/
|
|
250
|
+
async function onJoinedByInvite(roomId, userId) {
|
|
251
|
+
const matrix = requireMatrix()
|
|
252
|
+
const store = getStore()
|
|
253
|
+
const create = await matrix.getState(roomId, 'm.room.create')
|
|
254
|
+
if (create?.type === 'm.space') {
|
|
255
|
+
await adoptSpace(userId, roomId)
|
|
256
|
+
return
|
|
257
|
+
}
|
|
258
|
+
if (store.room(roomId)?.owner !== undefined) return
|
|
259
|
+
const firstContact = store.person(userId)?.spaces === undefined || store.person(userId).spaces.length === 0
|
|
260
|
+
if (firstContact) {
|
|
261
|
+
await ensureSpace(userId, { lobbyId: roomId })
|
|
262
|
+
} else {
|
|
263
|
+
const spaceId = await ensureSpace(userId)
|
|
264
|
+
await linkRoom(spaceId, roomId).catch((error) => warn(`room ${roomId} not added to the Space: ${error?.message ?? error}`))
|
|
265
|
+
await store.describeRoom(roomId, { owner: userId, spaceId })
|
|
266
|
+
}
|
|
267
|
+
await publishCommands(roomId)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return {
|
|
271
|
+
ensureSpace,
|
|
272
|
+
createRoom,
|
|
273
|
+
adoptSpace: (userId, spaceId) => oneAtATime(userId, () => adoptSpace(userId, spaceId)),
|
|
274
|
+
onChild,
|
|
275
|
+
onJoinedByInvite: (roomId, userId) => oneAtATime(userId, () => onJoinedByInvite(roomId, userId)),
|
|
276
|
+
publishCommands,
|
|
277
|
+
}
|
|
278
|
+
}
|