@practicalworks/rc-bridge 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.
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,335 @@
1
+ /** The webhook fields that decide where a reply goes. */
2
+ export interface ThreadablePayload {
3
+ /** The incoming message's own id (RC's "Message Sent" webhook includes it). */
4
+ message_id?: string;
5
+ /** The thread root — set by RC only when the incoming message IS a threaded reply. */
6
+ tmid?: string;
7
+ }
8
+ /**
9
+ * The agent conversation a message belongs to.
10
+ *
11
+ * The rule is "did a human put this in a thread", not "is this a DM".
12
+ *
13
+ * A `tmid` is the human saying, explicitly, that this is a separate topic — so
14
+ * it gets its own conversation wherever it happens, a DM included. Collapsing a
15
+ * DM's threads onto the room key would share one agent context, so topics bleed
16
+ * together, and one lock, so a turn in one thread pushes back a message in another.
17
+ *
18
+ * DM messages often arrive top-level, though, and keying THOSE per thread would
19
+ * mint a new conversation on every message and lose the history each time. That
20
+ * applies to a message with no `tmid`, which is the case below it.
21
+ *
22
+ * So: an explicit thread anywhere → its own conversation. Otherwise a DM stays
23
+ * one continuous conversation per room. Falls back to the room key when RC
24
+ * supplied no message id at all (same case where replies go to the room root).
25
+ *
26
+ * "Continuous" is bounded by `epoch`: the room key carries the
27
+ * current conversation epoch — a daily boundary, bumped by `/new` — so a room's
28
+ * agent context cannot grow without limit (see conversation-epochs.ts). Thread
29
+ * keys never take the epoch: a thread already starts fresh.
30
+ */
31
+ export declare function conversationKey(roomId: string, thread: string | undefined, isDM: boolean, tmid?: string, epoch?: string): string;
32
+ /** The webhook fields the context header is built from. */
33
+ export interface HeaderPayload {
34
+ channel_name?: string;
35
+ channel_id?: string;
36
+ user_name?: string;
37
+ message_id?: string;
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 declare function contextHeader(payload: HeaderPayload, isDM: boolean, thread?: string): string;
56
+ /** The thread a reply to this message belongs in.
57
+ *
58
+ * Already in a thread → that same thread. Otherwise → a new thread rooted on the
59
+ * message we're answering, so the human's request is the thing everything hangs
60
+ * off. `undefined` only when RC gave us no message id at all; the caller then
61
+ * posts to the room root rather than dropping the reply.
62
+ *
63
+ * This always resolves to a thread ROOT, never to a message sitting inside a
64
+ * thread — Rocket.Chat would treat the latter as the root of a NEW thread and
65
+ * split the conversation all over again. */
66
+ export declare function threadFor(payload: ThreadablePayload): string | undefined;
67
+ /** Inputs to the thread-root hydration decision. */
68
+ export interface RootHydrationContext {
69
+ /** Set only when the message IS a reply inside a thread — the root's id. */
70
+ tmid?: string;
71
+ isDM: boolean;
72
+ respondToAll: boolean;
73
+ /** Has a turn already gone to the agent on this conversation? If so the gateway
74
+ * is chaining it and the history is already there. */
75
+ conversationStarted: boolean;
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 declare function shouldHydrateRoot(ctx: RootHydrationContext): boolean;
101
+ /** How many ids a room remembers for the addressing gate. */
102
+ export declare const MAX_TRACKED_IDS = 50;
103
+ /** Remember an id that makes a later threaded reply count as addressed to us:
104
+ * a message the agent posted, or a thread it posted into. Bounded, oldest evicted
105
+ * first — and re-remembering refreshes recency, so a thread that's still active
106
+ * doesn't age out from under an ongoing conversation. */
107
+ export declare function remember(ids: Set<string>, id: string | undefined, max?: number): void;
108
+ /** How many rooms a snapshot keeps. A backstop, not a real limit — a workspace
109
+ * has tens of rooms, and each one's ids are already capped. */
110
+ export declare const MAX_TRACKED_ROOMS = 500;
111
+ /** The room state the addressing gate depends on.
112
+ *
113
+ * `threadOwners` is what makes the gate fail CLOSED: thread id → the
114
+ * lowercased username of the human whose message started the exchange. Only that
115
+ * person gets answered without an @mention. */
116
+ export interface RoomEngagement {
117
+ engagedIds: Set<string>;
118
+ threadOwners: Map<string, string>;
119
+ }
120
+ /** Record who owns a thread, first writer wins.
121
+ *
122
+ * First writer, because the owner is whoever's request the agent engaged with — a
123
+ * later participant does not inherit the right to drive it silently. Bounded
124
+ * alongside the id set so a busy workspace can't grow it forever. */
125
+ export declare function rememberOwner(owners: Map<string, string>, threadId: string | undefined, username: string | undefined, max?: number): void;
126
+ /** Inputs to the addressing decision. */
127
+ export interface AddressingContext {
128
+ mentioned: boolean;
129
+ isDM: boolean;
130
+ /** Thread root, when the message is a threaded reply. */
131
+ tmid?: string;
132
+ /** Who sent this message. */
133
+ sender?: string;
134
+ /** thread id → owning human, from RoomEngagement. */
135
+ threadOwners: Map<string, string>;
136
+ /** Did WE open this thread by naming this sender? See `rootInvites` — the
137
+ * announcement case, where there is no owner to match against because the
138
+ * thread never came through the bridge at all. */
139
+ invited?: boolean;
140
+ /** Is the thread rooted on a message WE posted? See `rootIsOurs` — the same
141
+ * announcement case as `invited`, for the announcements that named nobody. */
142
+ ourRoot?: boolean;
143
+ /** Does the thread's ROOT @mention us? See `rootAddressesUs` — the request
144
+ * case, where a human opened the thread by tagging us and the answer comes
145
+ * from a different human. */
146
+ rootAddressesUs?: boolean;
147
+ }
148
+ /**
149
+ * Should the bridge engage with this message?
150
+ *
151
+ * The test is WHO sent it, not only WHERE it is. A rule of "any message in a
152
+ * thread I've replied in" gives a turn to any account posting into an engaged
153
+ * thread, so another bot's announcement there reads as a request, and a loop
154
+ * between the two can fill the room.
155
+ *
156
+ * So: a mention always works — that is how a human reaches us on purpose. A DM is
157
+ * always us. Otherwise the ONLY silent path is the human who started the thread
158
+ * continuing their own conversation. Every other sender, bot or human, known or
159
+ * unknown, has to @mention us. Unknown senders therefore fail closed, which is
160
+ * the property a denylist can never give: a denylist is empty until someone
161
+ * remembers to fill it.
162
+ *
163
+ * Three widenings, each for a thread whose first message settles who it is for:
164
+ *
165
+ * - `invited`: a thread WE opened by naming someone. Ownership is only recorded
166
+ * when the bridge engages, so a thread rooted on an ANNOUNCEMENT (posted to
167
+ * Rocket.Chat's REST API by some other process, never through this one) has
168
+ * no owner, and the person the announcement asked to decide would be dropped
169
+ * for not retyping the mention. An invitation counts as ownership until the
170
+ * real owner is recorded. A room tag (`@all`, `@here`) in a root we wrote
171
+ * invites every human in the room; see `rootInvites`.
172
+ * - `ourRoot`: a thread WE rooted engages its first replier, for announcements
173
+ * addressed to whoever is reading. An announcement is a question; a reply in
174
+ * its thread is an answer to it. Bounded by the owner map: only while the
175
+ * thread is UNCLAIMED. The first human in becomes its owner (first writer
176
+ * wins, recorded by the caller), and from then on everyone else is back to
177
+ * needing an @mention, so one announcement hands out one seat.
178
+ * - `rootAddressesUs`: a thread a human rooted BY TAGGING US. The agent answers
179
+ * in the thread, often with a question, and whoever answers it is talking to
180
+ * us, not only the person who opened it. The tag is a fact about the thread
181
+ * that Rocket.Chat already stores, needs no state of ours to stay true, and
182
+ * reads the same way to a human looking at the room.
183
+ *
184
+ * None of these lets a loop back in: a thread the bot did not root and that
185
+ * never tagged us fails all three, and bots are dropped several guards before
186
+ * this function is reached — by `payload.bot`, by the account denylist, and by
187
+ * any plugin's `isOwnVoice`. What widens here is which HUMANS may answer.
188
+ */
189
+ export declare function shouldEngage(ctx: AddressingContext): boolean;
190
+ /** The bit of a thread root that decides whether it invited its replies. */
191
+ export interface ThreadRoot {
192
+ /** The root's author, as RC reports it. */
193
+ u?: {
194
+ _id?: string;
195
+ username?: string;
196
+ };
197
+ /** RC's parsed mentions. Absent on older/edited messages, hence the text fallback. */
198
+ mentions?: Array<{
199
+ _id?: string;
200
+ username?: string;
201
+ }>;
202
+ /** The raw text, used only when `mentions` is missing. */
203
+ msg?: string;
204
+ }
205
+ /** Our own identity, for deciding whether a root is ours. */
206
+ export interface BotIdentity {
207
+ userId: string;
208
+ /** Lowercased. */
209
+ username: string;
210
+ /** The OTHER usernames we answer to, lowercased: accounts a plugin speaks
211
+ * through. The agent is one brain behind several faces, and someone writing
212
+ * "@concierge, the heater is out" is addressing us exactly as much as someone
213
+ * writing "@bot". Optional, so a caller that only cares about the bot's own
214
+ * account can leave it out. */
215
+ faces?: readonly string[];
216
+ }
217
+ /** Every username we answer to: our own, plus any other faces, deduped. */
218
+ export declare function botFaces(us: BotIdentity): readonly string[];
219
+ /** Does this text @mention any of our faces? */
220
+ export declare function mentionsUs(text: string, us: BotIdentity): boolean;
221
+ /** Strip the @mention of any of our faces out of a prompt, so the model gets the
222
+ * request rather than the addressing. */
223
+ export declare function stripOurMentions(text: string, us: BotIdentity): string;
224
+ /**
225
+ * Did WE post the message this thread hangs off?
226
+ *
227
+ * The bridge threads its own replies onto the HUMAN's message, so a root we
228
+ * authored is, in practice, exactly one thing: an announcement, posted to
229
+ * Rocket.Chat's REST API by another process, never through this one. That is
230
+ * why it needs a rule of its own; see `shouldEngage`.
231
+ *
232
+ * Matches on either id or username, because RC reports the author both ways and
233
+ * a bridge configured with one but not the other must not silently stop
234
+ * recognising its own posts.
235
+ *
236
+ * The username side reads `botFaces`, not `us.username` alone. One brain wears
237
+ * several faces, and a post by any of them is a post by us in every sense that
238
+ * matters here — the mention gate already treats those names as ours. Compared
239
+ * against the single configured username, a thread rooted on a scheduled post
240
+ * by another face would never be "ours", and every reply in it that had not
241
+ * retyped an @mention would be dropped.
242
+ */
243
+ export declare function rootIsOurs(root: ThreadRoot | undefined, us: BotIdentity): boolean;
244
+ /**
245
+ * Did we open this thread by naming this person?
246
+ *
247
+ * True only when BOTH hold: the root is a message we posted, and it @mentions
248
+ * the sender — by name, or by tagging the whole room. `@all` / `@here` /
249
+ * `@channel` in OUR root invite everyone: a roll call that opens with "@all —
250
+ * one line each" means it, and must not refuse the second human to answer
251
+ * because the first claimed the thread. A room tag we chose to write is an open
252
+ * mic on purpose; when we don't want one, we don't tag the room. The flood
253
+ * properties hold anyway — bots never reach this function (`payload.bot`, the
254
+ * denylist and `isOwnVoice` all return earlier), and the per-thread post cap
255
+ * bounds what any conversation can make us emit.
256
+ *
257
+ * Prefers RC's parsed `mentions` array and falls back to scanning the text,
258
+ * because a message RC never re-parsed (or that we posted before it indexed
259
+ * mentions) still has the `@name` in its body. The fallback is a word-boundary
260
+ * match, so `@mar` does not invite `@maria`.
261
+ */
262
+ export declare function rootInvites(root: ThreadRoot | undefined, us: BotIdentity, sender: string | undefined): boolean;
263
+ /**
264
+ * Did the thread's root address US by name?
265
+ *
266
+ * The counterpart to `rootInvites`: that one asks whether a root WE wrote named
267
+ * the sender, this one asks whether a root THEY wrote named us. A human opening
268
+ * a thread with "@bot do X" has put us in the conversation, so a reply into
269
+ * that thread is addressed to us whoever sends it — see `shouldEngage` for why
270
+ * that is the rule and what it does not reopen.
271
+ *
272
+ * `@all` / `@here` / `@channel` never count. They address the room, and a room
273
+ * broadcast that happened to be threaded would otherwise hand us every reply in
274
+ * it — the same trap `rootInvites` avoids, from the other direction.
275
+ *
276
+ * ANY of our faces counts, not just the bot's own account (`botFaces`): "you may
277
+ * answer a thread that tagged one face, but tagging another never reaches us" is
278
+ * not a rule anyone could hold in their head.
279
+ *
280
+ * Matches on id or username for the reason `rootIsOurs` does: RC reports a
281
+ * mention both ways, and a bridge configured with one but not the other must not
282
+ * silently stop recognising when it was tagged. Prefers RC's parsed `mentions`
283
+ * and falls back to the raw text, because a message RC never re-parsed still
284
+ * carries the `@name` in its body; the fallback is word-bounded, so `@bo` does
285
+ * not read as `@bot`.
286
+ *
287
+ * This widens who may ANSWER, never who may speak AS us. A message authored by
288
+ * another face or any other bot is dropped by the loop guards at the top of
289
+ * `handleMessage` — `payload.bot`, our own id and username, `isOwnVoice`, and
290
+ * the bot denylist — all of which return long before this function is
291
+ * consulted. The faces can be talked TO here; they still cannot talk to each
292
+ * other.
293
+ */
294
+ export declare function rootAddressesUs(root: ThreadRoot | undefined, us: BotIdentity): boolean;
295
+ /** A room's on-disk record. `ids` is OLDEST FIRST — order is the whole point,
296
+ * since `remember` evicts by it and a snapshot that shuffled would quietly change
297
+ * which threads get forgotten first. `owners` is thread id → owning human. */
298
+ export interface RoomSnapshot {
299
+ ids: string[];
300
+ owners?: Record<string, string>;
301
+ }
302
+ /** The on-disk shape. The bare-array form is what earlier builds wrote (ids
303
+ * only); it is still read, so a deploy doesn't drop everyone's engaged threads. */
304
+ export type EngagementSnapshot = Record<string, string[] | RoomSnapshot>;
305
+ /** Rooms → a plain JSON object. Rooms that remember nothing are dropped rather
306
+ * than written as empty arrays. */
307
+ export declare function serializeEngagement(rooms: Map<string, RoomEngagement>, maxRooms?: number): EngagementSnapshot;
308
+ /** A snapshot → rooms, defensively. Anything malformed is skipped rather than
309
+ * thrown: a corrupt state file must cost us engagement memory, never the boot.
310
+ * Re-applies the per-room cap, so a file hand-edited (or written by an older
311
+ * build with a bigger cap) can't reintroduce unbounded growth. */
312
+ export declare function deserializeEngagement(raw: unknown, max?: number): Map<string, RoomEngagement>;
313
+ /** How long before the same thread may be nudged again. */
314
+ export declare const NUDGE_COOLDOWN_MS: number;
315
+ /** Is this dropped message worth a nudge?
316
+ *
317
+ * Only when the sender had real reason to expect an answer: a threaded reply,
318
+ * inside a thread the agent has actually posted in. Everything else is silent.
319
+ *
320
+ * Asking "is this a threaded reply, or an upload?" would ask whether a message
321
+ * was aimed at SOMETHING, never at US: a file dropped in a channel for other
322
+ * humans, or two people threading a conversation the agent had no part in, would
323
+ * draw an interjection nobody invited.
324
+ *
325
+ * Requiring `tmid` also keeps the throttle honest: with no `tmid` the caller's
326
+ * cooldown key falls back to the message's own id, unique every time, so the
327
+ * per-thread throttle would never match.
328
+ *
329
+ * A non-owner posting into an agent thread still gets nudged: they had every
330
+ * reason to expect an answer, so silence would read as "the agent is down"
331
+ * rather than "the agent isn't listening". */
332
+ export declare function worthNudging(payload: ThreadablePayload, room: RoomEngagement): boolean;
333
+ /** Rate-limit gate: at most one nudge per thread per cooldown. Mutates
334
+ * `lastNudges` on success so the caller can't forget to. */
335
+ export declare function nudgeAllowed(lastNudges: Map<string, number>, key: string, now: number, cooldownMs?: number): boolean;