@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/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,165 @@
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
+ * When the message was sent and what it replies to go on `source.envelope`,
15
+ * the metadata dsh-message-context renders for the model. The bot never adds
16
+ * them to the text: DSH titles a session from the first words of its first
17
+ * human message, and those must be the person's own.
18
+ */
19
+
20
+ /** Remembered prompts waiting for their step; the oldest go first past this. */
21
+ export const MAX_PENDING_PRINCIPALS = 1024
22
+
23
+ function nonEmpty(value) {
24
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined
25
+ }
26
+
27
+ /**
28
+ * The Matrix user who wrote a message, and where.
29
+ * @param userId - their Matrix user id.
30
+ * @param where - `{ name, roomId, room }`: their name from the allowlist, the room and its name,
31
+ * recorded as `chat` (where the message was sent), the field renderers read.
32
+ * @returns the principal, or undefined without a sender.
33
+ */
34
+ export function matrixUserPrincipal(userId, { name, roomId, room } = {}) {
35
+ if (nonEmpty(userId) === undefined) return undefined
36
+ return {
37
+ kind: 'matrix-user',
38
+ channel: 'matrix',
39
+ id: userId,
40
+ ...(nonEmpty(name) === undefined ? {} : { name: nonEmpty(name) }),
41
+ ...(nonEmpty(roomId) === undefined ? {} : { chat: { id: roomId, ...(nonEmpty(room) === undefined ? {} : { name: nonEmpty(room) }) } }),
42
+ }
43
+ }
44
+
45
+ /**
46
+ * The sender of a send into a room, from the request's `from`: a scheduled
47
+ * job, else a DSH session, else the free-form label of an outside caller.
48
+ * @param from - `{ job?, jobId?, sessionId?, label? }`.
49
+ * @returns the principal, or undefined when the request names no sender.
50
+ */
51
+ export function sendPrincipal(from) {
52
+ const job = nonEmpty(from?.job)
53
+ const jobId = nonEmpty(from?.jobId)
54
+ const sessionId = nonEmpty(from?.sessionId)
55
+ const label = nonEmpty(from?.label)
56
+ if (job !== undefined || jobId !== undefined) {
57
+ return {
58
+ kind: 'cron-job',
59
+ channel: 'cron',
60
+ id: jobId ?? job,
61
+ ...(job === undefined ? {} : { name: job }),
62
+ ...(sessionId === undefined ? {} : { sessionId }),
63
+ }
64
+ }
65
+ if (sessionId !== undefined) {
66
+ return { kind: 'dsh-session', channel: 'dsh', id: sessionId, ...(label === undefined ? {} : { name: label }) }
67
+ }
68
+ if (label !== undefined) return { kind: 'external', channel: 'external', id: label, name: label }
69
+ return undefined
70
+ }
71
+
72
+ /**
73
+ * A frozen copy of a message whose source records its sender.
74
+ * @param message - the user message.
75
+ * @param principal - its sender.
76
+ * @returns the copy; the message itself when there is no principal.
77
+ */
78
+ export function withPrincipal(message, principal) {
79
+ if (principal === undefined) return message
80
+ return Object.freeze({ ...message, source: Object.freeze({ ...message.source, principal: deepFreeze(principal) }) })
81
+ }
82
+
83
+ /**
84
+ * A frozen copy of a message whose source records its sender and envelope.
85
+ * Fields the message already has are kept.
86
+ * @param message - the user message.
87
+ * @param metadata - `{ principal, envelope }`, each optional.
88
+ * @returns the copy; the message itself when there is nothing to add.
89
+ */
90
+ export function withMetadata(message, { principal, envelope } = {}) {
91
+ const addPrincipal = principal !== undefined && message.source.principal === undefined
92
+ const addEnvelope = envelope !== undefined && message.source.envelope === undefined
93
+ if (!addPrincipal && !addEnvelope) return message
94
+ return Object.freeze({
95
+ ...message,
96
+ source: Object.freeze({
97
+ ...message.source,
98
+ ...(addPrincipal ? { principal: deepFreeze(principal) } : {}),
99
+ ...(addEnvelope ? { envelope: deepFreeze(envelope) } : {}),
100
+ }),
101
+ })
102
+ }
103
+
104
+ function deepFreeze(value) {
105
+ if (typeof value === 'object' && value !== null && !Object.isFrozen(value)) {
106
+ for (const child of Object.values(value)) deepFreeze(child)
107
+ Object.freeze(value)
108
+ }
109
+ return value
110
+ }
111
+
112
+ /**
113
+ * Principals for prompts the bot hands to DSH's session controller, which
114
+ * builds the message itself. The bot remembers the sender by request id
115
+ * before the hand-over; `preStep`, an `agent/pre-step` listener, records it
116
+ * and the envelope on the message as it enters a step, so they are in the
117
+ * session log with the message (DSH lets that hook replace the messages of a
118
+ * step). It is registered without `prepend`, so a prepended renderer sees them.
119
+ * @param limit - most principals remembered at once.
120
+ */
121
+ export function createPrincipalTagger(limit = MAX_PENDING_PRINCIPALS) {
122
+ const pending = new Map()
123
+ return {
124
+ /**
125
+ * Remember the sender and envelope of the prompt with this request id
126
+ * (or, for a message the bot builds itself, this message id).
127
+ * @param requestId - the request or message id.
128
+ * @param metadata - `{ principal, envelope }`, each optional.
129
+ */
130
+ remember(requestId, { principal, envelope } = {}) {
131
+ if (typeof requestId !== 'string' || (principal === undefined && envelope === undefined)) return
132
+ pending.delete(requestId)
133
+ pending.set(requestId, { principal, envelope })
134
+ if (pending.size > limit) pending.delete(pending.keys().next().value)
135
+ },
136
+ /** Pending prompts, for tests. */
137
+ get size() {
138
+ return pending.size
139
+ },
140
+ /**
141
+ * `agent/pre-step` listener: record remembered senders and envelopes on
142
+ * the step's messages.
143
+ */
144
+ async preStep(_payload, next) {
145
+ const decision = await next()
146
+ if (decision?.kind !== 'enter' || !Array.isArray(decision.messages)) return decision
147
+ let changed = false
148
+ const messages = []
149
+ for (const original of decision.messages) {
150
+ let message = original
151
+ const user = message?.source?.kind === 'user'
152
+ const key = !user ? undefined : (typeof message.source.rpcId === 'string' && pending.has(message.source.rpcId) ? message.source.rpcId : message.id)
153
+ const entry = typeof key === 'string' ? pending.get(key) : undefined
154
+ if (entry !== undefined) pending.delete(key)
155
+ if (entry !== undefined) {
156
+ const tagged = withMetadata(message, entry)
157
+ if (tagged !== message) changed = true
158
+ message = tagged
159
+ }
160
+ messages.push(message)
161
+ }
162
+ return changed ? { ...decision, messages } : decision
163
+ },
164
+ }
165
+ }