@practicalworks/rc-bridge 0.0.0-stage → 0.1.1

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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +157 -2
  3. package/dist/agent.d.ts +52 -0
  4. package/dist/agent.js +255 -0
  5. package/dist/attachment-deps.d.ts +15 -0
  6. package/dist/attachment-deps.js +13 -0
  7. package/dist/attachments.d.ts +255 -0
  8. package/dist/attachments.js +428 -0
  9. package/dist/config.d.ts +50 -0
  10. package/dist/config.js +92 -0
  11. package/dist/conversation-epochs.d.ts +41 -0
  12. package/dist/conversation-epochs.js +121 -0
  13. package/dist/denylist.d.ts +16 -0
  14. package/dist/denylist.js +86 -0
  15. package/dist/followups.d.ts +38 -0
  16. package/dist/followups.js +65 -0
  17. package/dist/hooks.d.ts +26 -0
  18. package/dist/hooks.js +88 -0
  19. package/dist/http.d.ts +33 -0
  20. package/dist/http.js +66 -0
  21. package/dist/index.d.ts +13 -0
  22. package/dist/index.js +11 -0
  23. package/dist/lookback.d.ts +33 -0
  24. package/dist/lookback.js +85 -0
  25. package/dist/main.d.ts +2 -0
  26. package/dist/main.js +104 -0
  27. package/dist/plugin.d.ts +113 -0
  28. package/dist/plugin.js +1 -0
  29. package/dist/reactions.d.ts +42 -0
  30. package/dist/reactions.js +127 -0
  31. package/dist/response.d.ts +52 -0
  32. package/dist/response.js +160 -0
  33. package/dist/run-events.d.ts +19 -0
  34. package/dist/run-events.js +65 -0
  35. package/dist/state.d.ts +57 -0
  36. package/dist/state.js +141 -0
  37. package/dist/stream.d.ts +67 -0
  38. package/dist/stream.js +126 -0
  39. package/dist/threading.d.ts +335 -0
  40. package/dist/threading.js +451 -0
  41. package/dist/turn-timings.d.ts +19 -0
  42. package/dist/turn-timings.js +14 -0
  43. package/dist/turn.d.ts +37 -0
  44. package/dist/turn.js +450 -0
  45. package/package.json +53 -3
@@ -0,0 +1,451 @@
1
+ // Where a reply belongs, and which messages make a later threaded reply "ours".
2
+ // Kept apart from main.ts so it can be tested without booting the bridge:
3
+ // main.ts reads required env at import time and exits when it is missing.
4
+ //
5
+ // The rule this file encodes: ONE request, ONE thread. Everything the bridge
6
+ // says about a message — the ack, the answer, an error, and a result a plugin
7
+ // delivers minutes later — goes to the same place, so a single exchange is
8
+ // never split across the channel and a thread nobody is watching.
9
+ /**
10
+ * The agent conversation a message belongs to.
11
+ *
12
+ * The rule is "did a human put this in a thread", not "is this a DM".
13
+ *
14
+ * A `tmid` is the human saying, explicitly, that this is a separate topic — so
15
+ * it gets its own conversation wherever it happens, a DM included. Collapsing a
16
+ * DM's threads onto the room key would share one agent context, so topics bleed
17
+ * together, and one lock, so a turn in one thread pushes back a message in another.
18
+ *
19
+ * DM messages often arrive top-level, though, and keying THOSE per thread would
20
+ * mint a new conversation on every message and lose the history each time. That
21
+ * applies to a message with no `tmid`, which is the case below it.
22
+ *
23
+ * So: an explicit thread anywhere → its own conversation. Otherwise a DM stays
24
+ * one continuous conversation per room. Falls back to the room key when RC
25
+ * supplied no message id at all (same case where replies go to the room root).
26
+ *
27
+ * "Continuous" is bounded by `epoch`: the room key carries the
28
+ * current conversation epoch — a daily boundary, bumped by `/new` — so a room's
29
+ * agent context cannot grow without limit (see conversation-epochs.ts). Thread
30
+ * keys never take the epoch: a thread already starts fresh.
31
+ */
32
+ export function conversationKey(roomId, thread, isDM, tmid, epoch) {
33
+ if (tmid)
34
+ return `rc:${roomId}:${tmid}`;
35
+ if (isDM || !thread)
36
+ return epoch ? `rc:${roomId}:${epoch}` : `rc:${roomId}`;
37
+ return `rc:${roomId}:${thread}`;
38
+ }
39
+ /**
40
+ * One line of situational context prefixed to every turn, so the agent knows
41
+ * WHERE it's standing (which channel, and so which kind of work) and WHO is
42
+ * asking (the human to attribute work to). Without it
43
+ * the request body is bare message text and the agent is channel-blind.
44
+ *
45
+ * It also carries the ADDRESS — `room=` and, inside a thread, `thread=`. That is
46
+ * what lets a turn schedule something that speaks back later: a scheduled run
47
+ * wakes with no conversation and no platform (Rocket.Chat is not one of the
48
+ * gateway's delivery adapters), so its only way home is a tool that posts to an
49
+ * explicit room and thread. The agent cannot pass an address it was never told,
50
+ * and a reminder that cannot name its own thread lands somewhere else, or nowhere.
51
+ *
52
+ * `thread` is the resolved reply target, not the raw `tmid`: a top-level message
53
+ * threads on its own id, and that is exactly where the answer belongs.
54
+ */
55
+ export function contextHeader(payload, isDM, thread) {
56
+ const where = isDM ? "DM" : `#${payload.channel_name ?? payload.channel_id ?? "unknown"}`;
57
+ const who = payload.user_name ? ` · from @${payload.user_name}` : "";
58
+ const room = payload.channel_id ? ` · room=${payload.channel_id}` : "";
59
+ const inThread = thread ? ` · thread=${thread}` : "";
60
+ // Contract: a caller that acts on this message later re-reads it by THIS id.
61
+ const msg = payload.message_id ? ` · msg=${payload.message_id}` : "";
62
+ return `[${where}${who}${room}${inThread}${msg}]`;
63
+ }
64
+ /** The thread a reply to this message belongs in.
65
+ *
66
+ * Already in a thread → that same thread. Otherwise → a new thread rooted on the
67
+ * message we're answering, so the human's request is the thing everything hangs
68
+ * off. `undefined` only when RC gave us no message id at all; the caller then
69
+ * posts to the room root rather than dropping the reply.
70
+ *
71
+ * This always resolves to a thread ROOT, never to a message sitting inside a
72
+ * thread — Rocket.Chat would treat the latter as the root of a NEW thread and
73
+ * split the conversation all over again. */
74
+ export function threadFor(payload) {
75
+ return payload.tmid ?? payload.message_id;
76
+ }
77
+ /** Does this turn need the thread's root message pulled in?
78
+ *
79
+ * Yes exactly when the agent is being pulled into a thread whose earlier messages
80
+ * it never received: a threaded reply, in a channel, on a conversation that has
81
+ * had no turn yet. That's the case where a human posted the substance — a link,
82
+ * a quote, a paste — as the root WITHOUT mentioning us, so the addressing gate
83
+ * dropped it, and then asked us to act on it in a reply. The agent got the verb and
84
+ * none of the noun.
85
+ *
86
+ * No once the conversation is started, so an ongoing thread doesn't re-read its
87
+ * root on every turn.
88
+ *
89
+ * The real question is narrower than "is this a DM": did the ROOT
90
+ * itself land in THIS conversation? If it did, re-reading it would just say the
91
+ * same thing twice.
92
+ *
93
+ * - In a channel under RESPOND_TO_ALL it did. Every message is relayed, and the
94
+ * root's own key IS this thread's key — a top-level message keys on its own
95
+ * id, which is exactly the `tmid` its replies carry. So: no.
96
+ * - In a DM it did NOT, now that a DM thread has its own conversation. The root
97
+ * was a top-level DM message, which still keys on the ROOM. The thread starts
98
+ * empty, so a reply in it reaches the agent as a bare "do that" with the subject
99
+ * sitting in a conversation it cannot see. So: yes, hydrate, DM or not. */
100
+ export function shouldHydrateRoot(ctx) {
101
+ if (!ctx.tmid)
102
+ return false;
103
+ if (ctx.conversationStarted)
104
+ return false;
105
+ if (ctx.respondToAll && !ctx.isDM)
106
+ return false;
107
+ return true;
108
+ }
109
+ /** How many ids a room remembers for the addressing gate. */
110
+ export const MAX_TRACKED_IDS = 50;
111
+ /** Remember an id that makes a later threaded reply count as addressed to us:
112
+ * a message the agent posted, or a thread it posted into. Bounded, oldest evicted
113
+ * first — and re-remembering refreshes recency, so a thread that's still active
114
+ * doesn't age out from under an ongoing conversation. */
115
+ export function remember(ids, id, max = MAX_TRACKED_IDS) {
116
+ if (!id)
117
+ return;
118
+ ids.delete(id); // a Set keeps FIRST-insert order, so delete+add is what refreshes it
119
+ ids.add(id);
120
+ while (ids.size > max) {
121
+ const oldest = ids.values().next().value;
122
+ if (oldest === undefined)
123
+ break;
124
+ ids.delete(oldest);
125
+ }
126
+ }
127
+ // --- Surviving a restart -----------------------------------------
128
+ // The ids above are what let a human continue a thread WITHOUT retyping the
129
+ // @mention. Held only in memory, they would die on every restart — and because
130
+ // an unaddressed message produces no output at all, the room would just go
131
+ // quiet and read as "the agent is broken". So the set is snapshotted to disk.
132
+ /** How many rooms a snapshot keeps. A backstop, not a real limit — a workspace
133
+ * has tens of rooms, and each one's ids are already capped. */
134
+ export const MAX_TRACKED_ROOMS = 500;
135
+ /** Record who owns a thread, first writer wins.
136
+ *
137
+ * First writer, because the owner is whoever's request the agent engaged with — a
138
+ * later participant does not inherit the right to drive it silently. Bounded
139
+ * alongside the id set so a busy workspace can't grow it forever. */
140
+ export function rememberOwner(owners, threadId, username, max = MAX_TRACKED_IDS) {
141
+ if (!threadId || !username || owners.has(threadId))
142
+ return;
143
+ owners.set(threadId, username.toLowerCase());
144
+ while (owners.size > max) {
145
+ const oldest = owners.keys().next().value;
146
+ if (oldest === undefined)
147
+ break;
148
+ owners.delete(oldest);
149
+ }
150
+ }
151
+ /**
152
+ * Should the bridge engage with this message?
153
+ *
154
+ * The test is WHO sent it, not only WHERE it is. A rule of "any message in a
155
+ * thread I've replied in" gives a turn to any account posting into an engaged
156
+ * thread, so another bot's announcement there reads as a request, and a loop
157
+ * between the two can fill the room.
158
+ *
159
+ * So: a mention always works — that is how a human reaches us on purpose. A DM is
160
+ * always us. Otherwise the ONLY silent path is the human who started the thread
161
+ * continuing their own conversation. Every other sender, bot or human, known or
162
+ * unknown, has to @mention us. Unknown senders therefore fail closed, which is
163
+ * the property a denylist can never give: a denylist is empty until someone
164
+ * remembers to fill it.
165
+ *
166
+ * Three widenings, each for a thread whose first message settles who it is for:
167
+ *
168
+ * - `invited`: a thread WE opened by naming someone. Ownership is only recorded
169
+ * when the bridge engages, so a thread rooted on an ANNOUNCEMENT (posted to
170
+ * Rocket.Chat's REST API by some other process, never through this one) has
171
+ * no owner, and the person the announcement asked to decide would be dropped
172
+ * for not retyping the mention. An invitation counts as ownership until the
173
+ * real owner is recorded. A room tag (`@all`, `@here`) in a root we wrote
174
+ * invites every human in the room; see `rootInvites`.
175
+ * - `ourRoot`: a thread WE rooted engages its first replier, for announcements
176
+ * addressed to whoever is reading. An announcement is a question; a reply in
177
+ * its thread is an answer to it. Bounded by the owner map: only while the
178
+ * thread is UNCLAIMED. The first human in becomes its owner (first writer
179
+ * wins, recorded by the caller), and from then on everyone else is back to
180
+ * needing an @mention, so one announcement hands out one seat.
181
+ * - `rootAddressesUs`: a thread a human rooted BY TAGGING US. The agent answers
182
+ * in the thread, often with a question, and whoever answers it is talking to
183
+ * us, not only the person who opened it. The tag is a fact about the thread
184
+ * that Rocket.Chat already stores, needs no state of ours to stay true, and
185
+ * reads the same way to a human looking at the room.
186
+ *
187
+ * None of these lets a loop back in: a thread the bot did not root and that
188
+ * never tagged us fails all three, and bots are dropped several guards before
189
+ * this function is reached — by `payload.bot`, by the account denylist, and by
190
+ * any plugin's `isOwnVoice`. What widens here is which HUMANS may answer.
191
+ */
192
+ export function shouldEngage(ctx) {
193
+ if (ctx.mentioned || ctx.isDM)
194
+ return true;
195
+ if (!ctx.tmid || !ctx.sender)
196
+ return false;
197
+ if (ctx.threadOwners.get(ctx.tmid) === ctx.sender.toLowerCase())
198
+ return true;
199
+ if (ctx.invited === true)
200
+ return true;
201
+ if (ctx.rootAddressesUs === true)
202
+ return true;
203
+ return ctx.ourRoot === true && !ctx.threadOwners.has(ctx.tmid);
204
+ }
205
+ /** Mentions that address a ROOM rather than a person. In a root a HUMAN wrote
206
+ * they never put US in the conversation (`rootAddressesUs` — a threaded room
207
+ * broadcast must not hand us every reply in it). In a root WE wrote they do the
208
+ * opposite: tagging the room is us inviting everyone in it (`rootInvites`). */
209
+ const ROOM_MENTIONS = new Set(["all", "here", "channel"]);
210
+ /** Every username we answer to: our own, plus any other faces, deduped. */
211
+ export function botFaces(us) {
212
+ return [...new Set([us.username, ...(us.faces ?? [])].map((f) => f.toLowerCase()))];
213
+ }
214
+ /** Escape a username before interpolating it into a mention pattern.
215
+ *
216
+ * Not paranoia: a username like `help.desk` is legal, and an unescaped `.`
217
+ * matches any character — so `@helpxdesk` would read as a mention of it. */
218
+ function escapeForMention(name) {
219
+ return name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
220
+ }
221
+ /** Does this text @mention any of our faces? */
222
+ export function mentionsUs(text, us) {
223
+ return botFaces(us).some((face) => new RegExp(`@${escapeForMention(face)}\\b`, "i").test(text));
224
+ }
225
+ /** Strip the @mention of any of our faces out of a prompt, so the model gets the
226
+ * request rather than the addressing. */
227
+ export function stripOurMentions(text, us) {
228
+ return botFaces(us)
229
+ .reduce((acc, face) => acc.replace(new RegExp(`@${escapeForMention(face)}\\b`, "gi"), ""), text)
230
+ .trim();
231
+ }
232
+ /**
233
+ * Did WE post the message this thread hangs off?
234
+ *
235
+ * The bridge threads its own replies onto the HUMAN's message, so a root we
236
+ * authored is, in practice, exactly one thing: an announcement, posted to
237
+ * Rocket.Chat's REST API by another process, never through this one. That is
238
+ * why it needs a rule of its own; see `shouldEngage`.
239
+ *
240
+ * Matches on either id or username, because RC reports the author both ways and
241
+ * a bridge configured with one but not the other must not silently stop
242
+ * recognising its own posts.
243
+ *
244
+ * The username side reads `botFaces`, not `us.username` alone. One brain wears
245
+ * several faces, and a post by any of them is a post by us in every sense that
246
+ * matters here — the mention gate already treats those names as ours. Compared
247
+ * against the single configured username, a thread rooted on a scheduled post
248
+ * by another face would never be "ours", and every reply in it that had not
249
+ * retyped an @mention would be dropped.
250
+ */
251
+ export function rootIsOurs(root, us) {
252
+ if (!root)
253
+ return false;
254
+ if (root.u?._id === us.userId)
255
+ return true;
256
+ const author = root.u?.username?.toLowerCase();
257
+ return author !== undefined && botFaces(us).includes(author);
258
+ }
259
+ /**
260
+ * Did we open this thread by naming this person?
261
+ *
262
+ * True only when BOTH hold: the root is a message we posted, and it @mentions
263
+ * the sender — by name, or by tagging the whole room. `@all` / `@here` /
264
+ * `@channel` in OUR root invite everyone: a roll call that opens with "@all —
265
+ * one line each" means it, and must not refuse the second human to answer
266
+ * because the first claimed the thread. A room tag we chose to write is an open
267
+ * mic on purpose; when we don't want one, we don't tag the room. The flood
268
+ * properties hold anyway — bots never reach this function (`payload.bot`, the
269
+ * denylist and `isOwnVoice` all return earlier), and the per-thread post cap
270
+ * bounds what any conversation can make us emit.
271
+ *
272
+ * Prefers RC's parsed `mentions` array and falls back to scanning the text,
273
+ * because a message RC never re-parsed (or that we posted before it indexed
274
+ * mentions) still has the `@name` in its body. The fallback is a word-boundary
275
+ * match, so `@mar` does not invite `@maria`.
276
+ */
277
+ export function rootInvites(root, us, sender) {
278
+ if (!root || !sender)
279
+ return false;
280
+ if (!rootIsOurs(root, us))
281
+ return false;
282
+ const who = sender.toLowerCase();
283
+ if (ROOM_MENTIONS.has(who))
284
+ return false;
285
+ const mentioned = (root.mentions ?? [])
286
+ .map((m) => m.username?.toLowerCase())
287
+ .filter((n) => Boolean(n));
288
+ if (mentioned.some((n) => ROOM_MENTIONS.has(n)))
289
+ return true;
290
+ const named = mentioned.filter((n) => !ROOM_MENTIONS.has(n));
291
+ if (named.length > 0)
292
+ return named.includes(who);
293
+ // No parsed mentions — read the text instead. The room tags first, then the
294
+ // sender's own name. Escaped, because a username is interpolated into a
295
+ // pattern here and RC does not promise it is word-safe.
296
+ const text = root.msg ?? "";
297
+ if ([...ROOM_MENTIONS].some((tag) => new RegExp(`@${tag}\\b`, "i").test(text)))
298
+ return true;
299
+ const escaped = who.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
300
+ return new RegExp(`@${escaped}\\b`, "i").test(text);
301
+ }
302
+ /**
303
+ * Did the thread's root address US by name?
304
+ *
305
+ * The counterpart to `rootInvites`: that one asks whether a root WE wrote named
306
+ * the sender, this one asks whether a root THEY wrote named us. A human opening
307
+ * a thread with "@bot do X" has put us in the conversation, so a reply into
308
+ * that thread is addressed to us whoever sends it — see `shouldEngage` for why
309
+ * that is the rule and what it does not reopen.
310
+ *
311
+ * `@all` / `@here` / `@channel` never count. They address the room, and a room
312
+ * broadcast that happened to be threaded would otherwise hand us every reply in
313
+ * it — the same trap `rootInvites` avoids, from the other direction.
314
+ *
315
+ * ANY of our faces counts, not just the bot's own account (`botFaces`): "you may
316
+ * answer a thread that tagged one face, but tagging another never reaches us" is
317
+ * not a rule anyone could hold in their head.
318
+ *
319
+ * Matches on id or username for the reason `rootIsOurs` does: RC reports a
320
+ * mention both ways, and a bridge configured with one but not the other must not
321
+ * silently stop recognising when it was tagged. Prefers RC's parsed `mentions`
322
+ * and falls back to the raw text, because a message RC never re-parsed still
323
+ * carries the `@name` in its body; the fallback is word-bounded, so `@bo` does
324
+ * not read as `@bot`.
325
+ *
326
+ * This widens who may ANSWER, never who may speak AS us. A message authored by
327
+ * another face or any other bot is dropped by the loop guards at the top of
328
+ * `handleMessage` — `payload.bot`, our own id and username, `isOwnVoice`, and
329
+ * the bot denylist — all of which return long before this function is
330
+ * consulted. The faces can be talked TO here; they still cannot talk to each
331
+ * other.
332
+ */
333
+ export function rootAddressesUs(root, us) {
334
+ if (!root)
335
+ return false;
336
+ const faces = new Set(botFaces(us));
337
+ const named = (root.mentions ?? []).filter((m) => !(m.username && ROOM_MENTIONS.has(m.username.toLowerCase())));
338
+ if (named.length > 0) {
339
+ return named.some((m) => m._id === us.userId || faces.has((m.username ?? "").toLowerCase()));
340
+ }
341
+ return mentionsUs(root.msg ?? "", us);
342
+ }
343
+ /** Rooms → a plain JSON object. Rooms that remember nothing are dropped rather
344
+ * than written as empty arrays. */
345
+ export function serializeEngagement(rooms, maxRooms = MAX_TRACKED_ROOMS) {
346
+ const out = {};
347
+ let kept = 0;
348
+ for (const [roomId, room] of rooms) {
349
+ if (room.engagedIds.size === 0)
350
+ continue;
351
+ if (kept++ >= maxRooms)
352
+ break;
353
+ const record = { ids: [...room.engagedIds] };
354
+ if (room.threadOwners.size)
355
+ record.owners = Object.fromEntries(room.threadOwners);
356
+ out[roomId] = record;
357
+ }
358
+ return out;
359
+ }
360
+ /** A snapshot → rooms, defensively. Anything malformed is skipped rather than
361
+ * thrown: a corrupt state file must cost us engagement memory, never the boot.
362
+ * Re-applies the per-room cap, so a file hand-edited (or written by an older
363
+ * build with a bigger cap) can't reintroduce unbounded growth. */
364
+ export function deserializeEngagement(raw, max = MAX_TRACKED_IDS) {
365
+ const rooms = new Map();
366
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
367
+ return rooms;
368
+ for (const [roomId, record] of Object.entries(raw)) {
369
+ if (!roomId || !record)
370
+ continue;
371
+ // Two shapes: the bare array earlier builds wrote, and the {ids, owners}
372
+ // record we write now. A file from before this change loses no engaged
373
+ // threads — it simply has no owners yet, so those threads need one @mention
374
+ // to re-establish who drives them.
375
+ const ids = Array.isArray(record)
376
+ ? record
377
+ : typeof record === "object" && Array.isArray(record.ids)
378
+ ? record.ids
379
+ : null;
380
+ if (!ids)
381
+ continue;
382
+ const engagedIds = new Set();
383
+ for (const id of ids) {
384
+ if (typeof id === "string")
385
+ remember(engagedIds, id, max);
386
+ }
387
+ if (!engagedIds.size)
388
+ continue;
389
+ const threadOwners = new Map();
390
+ const rawOwners = Array.isArray(record) ? undefined : record.owners;
391
+ if (rawOwners && typeof rawOwners === "object" && !Array.isArray(rawOwners)) {
392
+ for (const [threadId, owner] of Object.entries(rawOwners)) {
393
+ // Only for threads we still remember — otherwise an owner map could
394
+ // outlive its ids and grow past the cap they're bounded by.
395
+ if (typeof owner === "string" && engagedIds.has(threadId)) {
396
+ rememberOwner(threadOwners, threadId, owner, max);
397
+ }
398
+ }
399
+ }
400
+ rooms.set(roomId, { engagedIds, threadOwners });
401
+ }
402
+ return rooms;
403
+ }
404
+ // --- Saying something when we ignore someone ----------------------
405
+ // An unaddressed message produces NO output at all, so "the agent isn't
406
+ // listening" and "the agent is down" look identical from the room. So we speak
407
+ // up — but carefully: a channel where every human message drew "I only answer
408
+ // @mentions" would be far worse than silence.
409
+ //
410
+ // Loops are bounded elsewhere: the client's post cap (`withinRate`) counts what
411
+ // the bridge EMITS per thread, never how long a person may talk. If a bot ever
412
+ // reaches that cap, that is a hole in the addressing gate — fix it there, and do
413
+ // not add a limit on how much a person may say.
414
+ /** How long before the same thread may be nudged again. */
415
+ export const NUDGE_COOLDOWN_MS = 30 * 60_000;
416
+ /** Is this dropped message worth a nudge?
417
+ *
418
+ * Only when the sender had real reason to expect an answer: a threaded reply,
419
+ * inside a thread the agent has actually posted in. Everything else is silent.
420
+ *
421
+ * Asking "is this a threaded reply, or an upload?" would ask whether a message
422
+ * was aimed at SOMETHING, never at US: a file dropped in a channel for other
423
+ * humans, or two people threading a conversation the agent had no part in, would
424
+ * draw an interjection nobody invited.
425
+ *
426
+ * Requiring `tmid` also keeps the throttle honest: with no `tmid` the caller's
427
+ * cooldown key falls back to the message's own id, unique every time, so the
428
+ * per-thread throttle would never match.
429
+ *
430
+ * A non-owner posting into an agent thread still gets nudged: they had every
431
+ * reason to expect an answer, so silence would read as "the agent is down"
432
+ * rather than "the agent isn't listening". */
433
+ export function worthNudging(payload, room) {
434
+ return !!payload.tmid && room.engagedIds.has(payload.tmid);
435
+ }
436
+ /** Rate-limit gate: at most one nudge per thread per cooldown. Mutates
437
+ * `lastNudges` on success so the caller can't forget to. */
438
+ export function nudgeAllowed(lastNudges, key, now, cooldownMs = NUDGE_COOLDOWN_MS) {
439
+ const last = lastNudges.get(key);
440
+ if (last !== undefined && now - last < cooldownMs)
441
+ return false;
442
+ lastNudges.set(key, now);
443
+ // Bounded like everything else here — a busy workspace shouldn't accumulate a
444
+ // key per thread forever.
445
+ if (lastNudges.size > MAX_TRACKED_IDS * 4) {
446
+ const oldest = lastNudges.keys().next().value;
447
+ if (oldest !== undefined)
448
+ lastNudges.delete(oldest);
449
+ }
450
+ return true;
451
+ }
@@ -0,0 +1,19 @@
1
+ export interface TurnTiming {
2
+ at: string;
3
+ room: string;
4
+ profile?: string;
5
+ status: "ok" | "error";
6
+ /** ms from the agent request to its first stream event; null when none (non-streaming). */
7
+ firstEventMs: number | null;
8
+ /** ms from the agent request to its first text delta; null when none. */
9
+ firstTextMs: number | null;
10
+ totalMs: number;
11
+ tools: number;
12
+ }
13
+ export declare const DEFAULT_TURN_TIMINGS_MAX = 20;
14
+ export interface TurnTimings {
15
+ record(entry: TurnTiming): void;
16
+ /** Oldest first, newest last. A copy: callers cannot mutate the ring. */
17
+ list(): TurnTiming[];
18
+ }
19
+ export declare function createTurnTimings(max?: number): TurnTimings;
@@ -0,0 +1,14 @@
1
+ // Where a turn's time went, for /health. Room id and numbers only — never message
2
+ // text or prompts. Bounded: it is a debugging aid, not a log.
3
+ export const DEFAULT_TURN_TIMINGS_MAX = 20;
4
+ export function createTurnTimings(max = DEFAULT_TURN_TIMINGS_MAX) {
5
+ const ring = [];
6
+ return {
7
+ record(entry) {
8
+ ring.push(entry);
9
+ while (ring.length > max)
10
+ ring.shift();
11
+ },
12
+ list: () => ring.map((t) => ({ ...t })),
13
+ };
14
+ }
package/dist/turn.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type BotIdentity } from "./threading.js";
2
+ import type { CoreConfig, Log } from "./config.js";
3
+ import { type createAgentClient, type AgentTarget } from "./agent.js";
4
+ import type { Hooks } from "./hooks.js";
5
+ import type { WebhookPayload } from "./plugin.js";
6
+ import type { RocketChatClient } from "@practicalworks/rc-client";
7
+ import type { AttachmentDeps } from "./attachments.js";
8
+ import type { createBridgeState } from "./state.js";
9
+ import type { TurnTimings } from "./turn-timings.js";
10
+ export interface TurnHandlerDeps {
11
+ config: Readonly<CoreConfig>;
12
+ log: Log;
13
+ /** Replies, reactions and room type. Reads of uploads go through `attachmentDepsFor`. */
14
+ rc: Pick<RocketChatClient, "postReply" | "applyReactions" | "isDirectMessage" | "cachedRoomType">;
15
+ /** Attachment reads for one room, as that room's identity (see attachment-deps.ts). */
16
+ attachmentDepsFor(roomId: string): Promise<AttachmentDeps>;
17
+ agent: ReturnType<typeof createAgentClient>;
18
+ state: ReturnType<typeof createBridgeState<WebhookPayload>>;
19
+ turnTimings: TurnTimings;
20
+ hooks: Hooks;
21
+ /** Who we are: every name that counts as addressing us. */
22
+ bot: BotIdentity;
23
+ /** Other bots, by id and lowercased username. Read live: a boot refresh may add to them. */
24
+ denylist: {
25
+ ids: ReadonlySet<string>;
26
+ usernames: ReadonlySet<string>;
27
+ };
28
+ /** Where a turn goes when no plugin routes it. */
29
+ defaultTarget: AgentTarget;
30
+ /** Held follow-ups run through the same tracker as webhook turns, so shutdown waits for them. */
31
+ track(work: Promise<void>): void;
32
+ isDraining(): boolean;
33
+ }
34
+ export declare function createTurnHandler(deps: TurnHandlerDeps): {
35
+ handleMessage: (payload: WebhookPayload) => Promise<void>;
36
+ reply: (roomId: string, text: string, tmid?: string) => Promise<string | undefined>;
37
+ };