@soffits/dsh-matrix-bot 0.0.0-stage → 0.1.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/src/prompts.js ADDED
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Approval requests and agent questions for turns started from Matrix.
3
+ * Matrix has no buttons, so a question lists its options as numbers and the
4
+ * next message answers it; an approval waits for allow or deny. The bot puts
5
+ * the answers on the question as reactions (👍/👎, keycap digits), so in
6
+ * clients that show reactions an answer is one tap.
7
+ */
8
+ import { randomUUID } from 'node:crypto'
9
+ import { ALLOW_REACTION, COMMAND_PREFIXES, DENY_REACTION, NUMBER_REACTIONS } from './constants.js'
10
+
11
+ /** @returns the reactions that answer a question, or none when it takes several picks or has too many options. */
12
+ export function questionReactions(question) {
13
+ const options = Array.isArray(question?.options) ? question.options : []
14
+ if (question?.multiSelect === true || options.length === 0 || options.length > NUMBER_REACTIONS.length) return []
15
+ return NUMBER_REACTIONS.slice(0, options.length)
16
+ }
17
+
18
+ /**
19
+ * Parse a reply to a question with options.
20
+ * @param text - the reply.
21
+ * @param question - `{ options, multiSelect }`.
22
+ * @returns `{ selected, custom }`: option labels picked by number, or the
23
+ * whole reply as a free answer.
24
+ */
25
+ export function parseAnswer(text, question) {
26
+ const options = Array.isArray(question?.options) ? question.options : []
27
+ const trimmed = String(text ?? '').trim()
28
+ if (options.length > 0 && /^\d+(?:[\s,]+\d+)*$/u.test(trimmed)) {
29
+ const numbers = trimmed.split(/[\s,]+/u).map(Number)
30
+ if (numbers.every((number) => number >= 1 && number <= options.length)) {
31
+ const picked = [...new Set(numbers)].map((number) => options[number - 1].label)
32
+ return { selected: question.multiSelect === true ? picked : picked.slice(0, 1), custom: undefined }
33
+ }
34
+ }
35
+ return { selected: [], custom: trimmed }
36
+ }
37
+
38
+ /**
39
+ * Text of one question.
40
+ * @param question - user question.
41
+ * @param index - its position.
42
+ * @param total - questions in the batch.
43
+ */
44
+ export function questionText(question, index, total) {
45
+ const lines = []
46
+ if (question.header) lines.push(question.header)
47
+ lines.push(`❓ ${question.question}`)
48
+ if (question.detail) lines.push('', String(question.detail).slice(0, 3000))
49
+ const options = Array.isArray(question.options) ? question.options : []
50
+ if (options.length > 0) {
51
+ lines.push('')
52
+ for (const [number, option] of options.entries()) {
53
+ lines.push(`${number + 1}. ${option.label}${option.description ? ` — ${option.description}` : ''}`)
54
+ }
55
+ lines.push('', question.multiSelect === true
56
+ ? 'Reply with one or more numbers (like "1 3"), or write your own answer.'
57
+ : questionReactions(question).length > 0
58
+ ? 'Tap a number below or reply with one, or write your own answer.'
59
+ : 'Reply with a number, or write your own answer.')
60
+ } else {
61
+ lines.push('', 'Reply with your answer.')
62
+ }
63
+ if (total > 1) lines.push(`(Question ${index + 1} of ${total}; !stop cancels.)`)
64
+ return lines.join('\n')
65
+ }
66
+
67
+ /**
68
+ * Create the prompt broker.
69
+ * @param options - `{ roomOfAgent, send, react, warn }`: `roomOfAgent(agent)`
70
+ * gives the room that should answer for a turn, or undefined to leave it to
71
+ * DSH; `send(roomId, text)` resolves to the sent event ids; `react(roomId,
72
+ * eventId, key)` puts a reaction on one.
73
+ * @returns `{ attach, consumeReply, onReaction, settleApproval, cancelRoom, cancelAll, pending }`.
74
+ */
75
+ export function createPrompts({ roomOfAgent, send, react, warn }) {
76
+ const attached = new WeakSet()
77
+ /** Pending question batches by room id. */
78
+ const questions = new Map()
79
+ /** Pending approvals by room id (a list, oldest first). */
80
+ const approvals = new Map()
81
+
82
+ function finishQuestion(roomId, batch, error) {
83
+ if (questions.get(roomId) !== batch) return
84
+ questions.delete(roomId)
85
+ batch.signal?.removeEventListener('abort', batch.onAbort)
86
+ if (error === undefined) batch.resolve({ answers: batch.answers })
87
+ else batch.reject(error)
88
+ }
89
+
90
+ async function askQuestions(roomId, req, next) {
91
+ const list = Array.isArray(req.questions) ? req.questions : []
92
+ if (list.length === 0 || questions.has(roomId)) return next()
93
+ const signal = req.signal
94
+ if (signal?.aborted) return next()
95
+ return new Promise((resolve, reject) => {
96
+ const batch = { id: randomUUID(), questions: list, index: 0, answers: [], resolve, reject, signal, onAbort: undefined }
97
+ batch.onAbort = () => {
98
+ finishQuestion(roomId, batch, signal.reason ?? new Error('question cancelled'))
99
+ void send(roomId, '⏹ Question cancelled.')
100
+ }
101
+ signal?.addEventListener('abort', batch.onAbort, { once: true })
102
+ questions.set(roomId, batch)
103
+ askNext(roomId, batch).catch((error) => {
104
+ warn(`question not sent: ${error?.message ?? error}`)
105
+ finishQuestion(roomId, batch, error)
106
+ })
107
+ })
108
+ }
109
+
110
+ /** Send the batch's current question and put its answer reactions on it. */
111
+ async function askNext(roomId, batch) {
112
+ const question = batch.questions[batch.index]
113
+ const [eventId] = await send(roomId, questionText(question, batch.index, batch.questions.length))
114
+ batch.eventId = eventId
115
+ try {
116
+ for (const key of questionReactions(question)) await react(roomId, eventId, key)
117
+ } catch (error) {
118
+ warn(`answer reactions not sent: ${error?.message ?? error}`)
119
+ }
120
+ }
121
+
122
+ async function askApproval(roomId, req) {
123
+ if (req.signal?.aborted) return 'cancelled'
124
+ const reason = req.displayReason?.en ?? req.reason ?? 'The tool asked for approval.'
125
+ return new Promise((resolve) => {
126
+ const entry = { resolve, toolName: req.toolName, signal: req.signal, onAbort: undefined, eventId: undefined }
127
+ entry.onAbort = () => settle(roomId, entry, 'cancelled')
128
+ req.signal?.addEventListener('abort', entry.onAbort, { once: true })
129
+ const list = approvals.get(roomId) ?? []
130
+ list.push(entry)
131
+ approvals.set(roomId, list)
132
+ const text = `🔐 Approval needed for ${req.toolName}:\n${reason}\n\nTap ${ALLOW_REACTION} to allow or ${DENY_REACTION} to deny, or send !allow or !deny.`
133
+ Promise.resolve(send(roomId, text)).then(async ([eventId]) => {
134
+ entry.eventId = eventId
135
+ try {
136
+ await react(roomId, eventId, ALLOW_REACTION)
137
+ await react(roomId, eventId, DENY_REACTION)
138
+ } catch (error) {
139
+ warn(`approval reactions not sent: ${error?.message ?? error}`)
140
+ }
141
+ }, () => settle(roomId, entry, 'unavailable'))
142
+ })
143
+ }
144
+
145
+ /** Record an answer and ask the next question, or finish the batch. */
146
+ function answer(roomId, batch, { selected, custom }) {
147
+ const question = batch.questions[batch.index]
148
+ batch.answers.push({ id: question.id, selected, ...(custom ? { custom } : {}) })
149
+ batch.index += 1
150
+ batch.eventId = undefined
151
+ if (batch.index < batch.questions.length) {
152
+ askNext(roomId, batch).catch((error) => {
153
+ warn(`question not sent: ${error?.message ?? error}`)
154
+ finishQuestion(roomId, batch, error)
155
+ })
156
+ } else {
157
+ finishQuestion(roomId, batch)
158
+ }
159
+ }
160
+
161
+ function settle(roomId, entry, outcome) {
162
+ const list = approvals.get(roomId) ?? []
163
+ const index = list.indexOf(entry)
164
+ if (index === -1) return false
165
+ list.splice(index, 1)
166
+ if (list.length === 0) approvals.delete(roomId)
167
+ entry.signal?.removeEventListener('abort', entry.onAbort)
168
+ entry.resolve(outcome)
169
+ return true
170
+ }
171
+
172
+ return {
173
+ /** Answer approval and question requests of an agent while its turn belongs to a room. */
174
+ attach(agent) {
175
+ if (attached.has(agent) || typeof agent?.ctx?.on !== 'function') return
176
+ attached.add(agent)
177
+ agent.ctx.on('approval/request', (req, next) => {
178
+ const roomId = roomOfAgent(agent)
179
+ if (roomId === undefined) return next()
180
+ return askApproval(roomId, req)
181
+ }, { prepend: true })
182
+ agent.ctx.on('user-questions/request', (req, next) => {
183
+ const roomId = roomOfAgent(agent)
184
+ if (roomId === undefined) return next()
185
+ return askQuestions(roomId, req, next)
186
+ }, { prepend: true })
187
+ },
188
+ /**
189
+ * Take a message as the answer to the room's open question.
190
+ * @returns true when the message answered a question.
191
+ */
192
+ consumeReply(roomId, text) {
193
+ const batch = questions.get(roomId)
194
+ if (batch === undefined || text.length === 0 || COMMAND_PREFIXES.some((prefix) => text.startsWith(prefix))) return false
195
+ answer(roomId, batch, parseAnswer(text, batch.questions[batch.index]))
196
+ return true
197
+ },
198
+ /**
199
+ * Take a reaction to a question or approval as its answer.
200
+ * @param roomId - room id.
201
+ * @param eventId - the event reacted to.
202
+ * @param key - the reaction.
203
+ * @returns true when the reaction answered something.
204
+ */
205
+ onReaction(roomId, eventId, key) {
206
+ const entry = approvals.get(roomId)?.find((item) => item.eventId === eventId)
207
+ if (entry !== undefined && (key === ALLOW_REACTION || key === DENY_REACTION)) {
208
+ settle(roomId, entry, key === ALLOW_REACTION ? 'allowed-once' : 'rejected')
209
+ void send(roomId, key === ALLOW_REACTION ? `✅ Allowed ${entry.toolName}.` : `❌ Denied ${entry.toolName}.`)
210
+ return true
211
+ }
212
+ const batch = questions.get(roomId)
213
+ if (batch === undefined || batch.eventId !== eventId) return false
214
+ const question = batch.questions[batch.index]
215
+ const index = questionReactions(question).indexOf(key)
216
+ if (index === -1) return false
217
+ answer(roomId, batch, { selected: [question.options[index].label], custom: undefined })
218
+ return true
219
+ },
220
+ /**
221
+ * Resolve the oldest approval of a room.
222
+ * @returns the tool name, or undefined when none was waiting.
223
+ */
224
+ settleApproval(roomId, allowed) {
225
+ const entry = approvals.get(roomId)?.[0]
226
+ if (entry === undefined) return undefined
227
+ settle(roomId, entry, allowed ? 'allowed-once' : 'rejected')
228
+ return entry.toolName
229
+ },
230
+ /** Cancel what a room was asked (on stop). */
231
+ cancelRoom(roomId) {
232
+ const batch = questions.get(roomId)
233
+ if (batch !== undefined) finishQuestion(roomId, batch, new Error('Question cancelled by stop'))
234
+ for (const entry of [...(approvals.get(roomId) ?? [])]) settle(roomId, entry, 'cancelled')
235
+ },
236
+ cancelAll() {
237
+ for (const roomId of [...questions.keys(), ...approvals.keys()]) this.cancelRoom(roomId)
238
+ },
239
+ /** @returns what a room is being asked: `{ question, approvals }`. */
240
+ pending(roomId) {
241
+ return { question: questions.has(roomId), approvals: approvals.get(roomId)?.length ?? 0 }
242
+ },
243
+ }
244
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Working signs: a message the bot works on carries a reaction from the bot
3
+ * (⏳ for a new or queued turn, 👀 when it went into the running turn) until
4
+ * the turn that took it has ended and its answer was sent; the reaction is
5
+ * then redacted. A typing notice only shows while a turn runs, so a queued
6
+ * message needs this sign. Reacted messages are kept in `state.json`, so a
7
+ * sign left by a turn that a Host restart cut off is removed at the next start.
8
+ */
9
+ import { REQUEST_PREFIX, STEER_REACTION, WORKING_REACTION } from './constants.js'
10
+ import { inInbox } from './sessions.js'
11
+
12
+ /**
13
+ * Create the working-sign tracker.
14
+ * @param deps - `{ ctx, getStore, outbound, isRunning, reportError }`.
15
+ * @returns `{ emojiFor, mark, admitted, attach, finishTurn, sweep, resume, release }`.
16
+ */
17
+ export function createReactions({ ctx, getStore, outbound, isRunning, reportError }) {
18
+ /** Reacted messages by event id: `{ roomId, reactionId, admitted, turn }`. */
19
+ const tracked = new Map()
20
+ let loaded = false
21
+
22
+ /** Take over the messages a previous run left reacted. */
23
+ function load() {
24
+ if (loaded) return
25
+ const store = getStore()
26
+ if (store === undefined) return
27
+ loaded = true
28
+ for (const [eventId, entry] of Object.entries(store.reactions())) {
29
+ if (!tracked.has(eventId)) tracked.set(eventId, { roomId: entry.roomId, reactionId: entry.reactionId, admitted: true, turn: undefined })
30
+ }
31
+ }
32
+
33
+ /** @returns the live agent of a room's session, or undefined. */
34
+ function agentOf(roomId) {
35
+ const sessionId = getStore()?.room(roomId)?.sessionId
36
+ return typeof sessionId === 'string' ? ctx.get('agents')?.get(sessionId) : undefined
37
+ }
38
+
39
+ /**
40
+ * The sign for a message about to go to a session.
41
+ * @param running - whether the session runs a turn.
42
+ * @param steer - whether a message during a turn goes into it.
43
+ */
44
+ function emojiFor(running, steer) {
45
+ return running && steer ? STEER_REACTION : WORKING_REACTION
46
+ }
47
+
48
+ /** React to a message and remember it. */
49
+ async function mark(roomId, eventId, emoji) {
50
+ load()
51
+ if (!isRunning()) return
52
+ const entry = { roomId, reactionId: undefined, admitted: false, turn: undefined }
53
+ tracked.set(eventId, entry)
54
+ try {
55
+ entry.reactionId = await outbound.react(roomId, eventId, emoji)
56
+ await getStore()?.noteReaction(eventId, { roomId, reactionId: entry.reactionId })
57
+ } catch (error) {
58
+ reportError(`reaction on ${eventId}`, error)
59
+ }
60
+ }
61
+
62
+ /** The message reached the session, so a sweep may judge it. */
63
+ function admitted(eventId) {
64
+ const entry = tracked.get(eventId)
65
+ if (entry !== undefined) entry.admitted = true
66
+ }
67
+
68
+ /**
69
+ * The message is part of a turn now.
70
+ * @param eventId - Matrix event id.
71
+ * @param turn - key of the turn (session id and turn number).
72
+ */
73
+ function attach(eventId, turn) {
74
+ const entry = tracked.get(eventId)
75
+ if (entry !== undefined) entry.turn = turn
76
+ }
77
+
78
+ /** Remove the bot's reaction from messages. */
79
+ async function release(eventIds) {
80
+ if (eventIds.length === 0 || !isRunning()) return
81
+ const entries = eventIds.map((eventId) => tracked.get(eventId)).filter((entry) => entry?.reactionId !== undefined)
82
+ for (const eventId of eventIds) tracked.delete(eventId)
83
+ await getStore()?.dropReactions(eventIds)
84
+ for (const entry of entries) {
85
+ await outbound.redact(entry.roomId, entry.reactionId).catch((error) => reportError(`reaction ${entry.reactionId}`, error))
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Messages of a room that will get no turn: admitted, not taken into a
91
+ * turn, and no longer waiting in the agent's inbox (dropped by /stop or
92
+ * /clear, or a duplicate).
93
+ */
94
+ function dropped(roomId, { ignoreTurn = false } = {}) {
95
+ const agent = agentOf(roomId)
96
+ return [...tracked].filter(([eventId, entry]) => entry.roomId === roomId && entry.admitted
97
+ && (ignoreTurn || entry.turn === undefined) && !inInbox(agent, `${REQUEST_PREFIX}${roomId}:${eventId}`)).map(([eventId]) => eventId)
98
+ }
99
+
100
+ /**
101
+ * A turn ended and its answer went out: clear its messages (whatever room
102
+ * the session is bound to now) and the room's dropped ones.
103
+ */
104
+ async function finishTurn(roomId, turn) {
105
+ load()
106
+ const own = [...tracked].filter(([, entry]) => entry.turn === turn).map(([eventId]) => eventId)
107
+ await release([...own, ...dropped(roomId)])
108
+ }
109
+
110
+ /** Clear the signs of a room's dropped messages. */
111
+ async function sweep(roomId) {
112
+ load()
113
+ await release(dropped(roomId))
114
+ }
115
+
116
+ /** Clear signs whose session runs no turn, e.g. after a restart. */
117
+ async function resume() {
118
+ load()
119
+ const idle = new Set([...tracked.values()].map((entry) => entry.roomId).filter((roomId) => {
120
+ const agent = agentOf(roomId)
121
+ return agent === undefined || agent.status === undefined || agent.status === 'idle'
122
+ }))
123
+ for (const roomId of idle) await release(dropped(roomId, { ignoreTurn: true }))
124
+ }
125
+
126
+ return { emojiFor, mark, admitted, attach, finishTurn, sweep, resume, release }
127
+ }
package/src/sender.js ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Who sent a message, as data on the message itself.
3
+ *
4
+ * DSH's field for the caller behind a user message is `source.principal`:
5
+ * the session controller writes it for callers other than the owner, so an
6
+ * absent principal means the owner. The bot admits every Matrix prompt as
7
+ * the owner, so it fills the field itself, and also on the copies of sends it
8
+ * records in bound sessions. Readers get the sender from it, not from text.
9
+ *
10
+ * Every principal has `kind`, `channel` and `id`, and `name` when one is
11
+ * known; the other fields depend on the kind. None carries a credential, so
12
+ * all are safe in a session log.
13
+ *
14
+ * The model learns the sender, when the message was sent, and the context of
15
+ * the message (what it replies to, where a forward comes from), from a notice
16
+ * message placed right before the prompt, not from lines inside the prompt: DSH titles a session
17
+ * from the first words of its first human message, and those must be the
18
+ * person's own.
19
+ */
20
+
21
+ import { randomUUID } from 'node:crypto'
22
+
23
+ /** Remembered prompts waiting for their step; the oldest go first past this. */
24
+ export const MAX_PENDING_PRINCIPALS = 1024
25
+
26
+ function nonEmpty(value) {
27
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined
28
+ }
29
+
30
+ /**
31
+ * The Matrix user who wrote a message, and where.
32
+ * @param userId - their Matrix user id.
33
+ * @param where - `{ name, roomId, room }`: their name from the allowlist, the room and its name.
34
+ * @returns the principal, or undefined without a sender.
35
+ */
36
+ export function matrixUserPrincipal(userId, { name, roomId, room } = {}) {
37
+ if (nonEmpty(userId) === undefined) return undefined
38
+ return {
39
+ kind: 'matrix-user',
40
+ channel: 'matrix',
41
+ id: userId,
42
+ ...(nonEmpty(name) === undefined ? {} : { name: nonEmpty(name) }),
43
+ ...(nonEmpty(roomId) === undefined ? {} : { room: { id: roomId, ...(nonEmpty(room) === undefined ? {} : { name: nonEmpty(room) }) } }),
44
+ }
45
+ }
46
+
47
+ /**
48
+ * The sender of a send into a room, from the request's `from`: a scheduled
49
+ * job, else a DSH session, else the free-form label of an outside caller.
50
+ * @param from - `{ job?, jobId?, sessionId?, label? }`.
51
+ * @returns the principal, or undefined when the request names no sender.
52
+ */
53
+ export function sendPrincipal(from) {
54
+ const job = nonEmpty(from?.job)
55
+ const jobId = nonEmpty(from?.jobId)
56
+ const sessionId = nonEmpty(from?.sessionId)
57
+ const label = nonEmpty(from?.label)
58
+ if (job !== undefined || jobId !== undefined) {
59
+ return {
60
+ kind: 'cron-job',
61
+ channel: 'cron',
62
+ id: jobId ?? job,
63
+ ...(job === undefined ? {} : { name: job }),
64
+ ...(sessionId === undefined ? {} : { sessionId }),
65
+ }
66
+ }
67
+ if (sessionId !== undefined) {
68
+ return { kind: 'dsh-session', channel: 'dsh', id: sessionId, ...(label === undefined ? {} : { name: label }) }
69
+ }
70
+ if (label !== undefined) return { kind: 'external', channel: 'external', id: label, name: label }
71
+ return undefined
72
+ }
73
+
74
+ /**
75
+ * A frozen copy of a message whose source records its sender.
76
+ * @param message - the user message.
77
+ * @param principal - its sender.
78
+ * @returns the copy; the message itself when there is no principal.
79
+ */
80
+ export function withPrincipal(message, principal) {
81
+ if (principal === undefined) return message
82
+ return Object.freeze({ ...message, source: Object.freeze({ ...message.source, principal: deepFreeze(principal) }) })
83
+ }
84
+
85
+ /** Source kind of the sender notice before each Matrix prompt. */
86
+ export const SENDER_NOTICE_KIND = 'matrix-sender'
87
+
88
+ /**
89
+ * The line that tells the model who wrote a Matrix message and when. A
90
+ * message can reach the agent long after it was sent (a queued message, a
91
+ * backlog after a restart), so the time is the server's own.
92
+ * @param principal - a `matrix-user` principal.
93
+ * @param sentAt - when the message was sent, as text.
94
+ * @returns a one-line label, or undefined with neither a Matrix sender nor a time.
95
+ */
96
+ export function senderLabel(principal, sentAt) {
97
+ const time = nonEmpty(sentAt) === undefined ? '' : `, sent ${sentAt.trim()}`
98
+ if (principal?.kind !== 'matrix-user' || principal.id === undefined) {
99
+ return time === '' ? undefined : `[Matrix message${time}]`
100
+ }
101
+ const name = nonEmpty(principal.name)
102
+ return name !== undefined ? `[Matrix message from ${name} (${principal.id})${time}]` : `[Matrix message from ${principal.id}${time}]`
103
+ }
104
+
105
+ /**
106
+ * The notice that comes before a prompt: who sent it, when, and the context
107
+ * the bot adds around it. It is its own message with a producer source, so
108
+ * DSH's title input and readers of human messages see only what the person
109
+ * wrote.
110
+ * @param message - a user message entering a step.
111
+ * @param details - `{ context, sentAt }`: context blocks for this prompt (see
112
+ * `composePrompt`) and when it was sent, as text; both optional.
113
+ * @returns the notice, or undefined with no sender, time or context.
114
+ */
115
+ export function senderNotice(message, { context, sentAt } = {}) {
116
+ if (message?.source?.kind !== 'user') return undefined
117
+ const label = senderLabel(message.source.principal, sentAt)
118
+ const extra = typeof context === 'string' && context.trim().length > 0 ? context : undefined
119
+ if (label === undefined && extra === undefined) return undefined
120
+ const text = [label, extra].filter((part) => part !== undefined).join('\n')
121
+ return deepFreeze({
122
+ id: randomUUID(),
123
+ role: 'user',
124
+ content: [{ type: 'text', text }],
125
+ source: { kind: SENDER_NOTICE_KIND, form: 'notice', summary: label ?? text.split('\n')[0] },
126
+ })
127
+ }
128
+
129
+ function deepFreeze(value) {
130
+ if (typeof value === 'object' && value !== null && !Object.isFrozen(value)) {
131
+ for (const child of Object.values(value)) deepFreeze(child)
132
+ Object.freeze(value)
133
+ }
134
+ return value
135
+ }
136
+
137
+ /**
138
+ * Principals for prompts the bot hands to DSH's session controller, which
139
+ * builds the message itself. The bot remembers the sender by request id
140
+ * before the hand-over; `preStep`, an `agent/pre-step` listener, records it
141
+ * on the message as it enters a step, so it is in the session log with the
142
+ * message (DSH lets that hook replace the messages of a step).
143
+ * @param limit - most principals remembered at once.
144
+ */
145
+ export function createPrincipalTagger(limit = MAX_PENDING_PRINCIPALS) {
146
+ const pending = new Map()
147
+ return {
148
+ /**
149
+ * Remember the sender, send time and context of the prompt with this
150
+ * request id (or, for a message the bot builds itself, this message id).
151
+ * @param requestId - the request or message id.
152
+ * @param details - `{ principal, context, sentAt }`, each optional.
153
+ */
154
+ remember(requestId, { principal, context, sentAt } = {}) {
155
+ if (typeof requestId !== 'string' || (principal === undefined && context === undefined && sentAt === undefined)) return
156
+ pending.delete(requestId)
157
+ pending.set(requestId, { principal, context, sentAt })
158
+ if (pending.size > limit) pending.delete(pending.keys().next().value)
159
+ },
160
+ /** Pending prompts, for tests. */
161
+ get size() {
162
+ return pending.size
163
+ },
164
+ /**
165
+ * `agent/pre-step` listener: record remembered senders on the step's
166
+ * messages and put each prompt's notice (sender, time and context) before it.
167
+ */
168
+ async preStep(_payload, next) {
169
+ const decision = await next()
170
+ if (decision?.kind !== 'enter' || !Array.isArray(decision.messages)) return decision
171
+ let changed = false
172
+ const messages = []
173
+ for (const original of decision.messages) {
174
+ let message = original
175
+ const user = message?.source?.kind === 'user'
176
+ const key = !user ? undefined : (typeof message.source.rpcId === 'string' && pending.has(message.source.rpcId) ? message.source.rpcId : message.id)
177
+ const entry = typeof key === 'string' ? pending.get(key) : undefined
178
+ if (entry !== undefined) pending.delete(key)
179
+ if (entry?.principal !== undefined && message.source.principal === undefined) {
180
+ message = withPrincipal(message, entry.principal)
181
+ changed = true
182
+ }
183
+ const notice = senderNotice(message, entry)
184
+ if (notice !== undefined) {
185
+ messages.push(notice)
186
+ changed = true
187
+ }
188
+ messages.push(message)
189
+ }
190
+ return changed ? { ...decision, messages } : decision
191
+ },
192
+ }
193
+ }