@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
package/dist/turn.js ADDED
@@ -0,0 +1,450 @@
1
+ // One webhook message, from the loop guards to the single final post. Whatever a
2
+ // deployment adds (voices, routing, approvals, dispatch, traces, control verbs)
3
+ // arrives through the hooks in plugin.ts; nothing here knows what they are.
4
+ //
5
+ // The guard ORDER at the top is load-bearing: bot guards before control, so no
6
+ // bot drives the switch; control before the pause, so a resume verb works while
7
+ // paused; upload recovery before the addressing gate,
8
+ // so a paste that carries its @mention inside the file is heard.
9
+ import { documentBlock, fetchMessageAttachments, fetchThreadRoot, getMessage, pastedMessageText, skipNotice, threadRootBlock, BARE_MENTION_PROMPT, DOCUMENT_WITHOUT_CONTEXT_PROMPT, IMAGE_WITHOUT_CONTEXT_PROMPT, } from "./attachments.js";
10
+ import { fetchRecentImages, lookbackNote } from "./lookback.js";
11
+ import { REACTION_HINT, extractReactions, receiptTransition } from "./reactions.js";
12
+ import { describeTools } from "./response.js";
13
+ import { captureRunEvents } from "./run-events.js";
14
+ import { contextHeader, conversationKey, nudgeAllowed, remember, rememberOwner, mentionsUs, rootAddressesUs, rootInvites, rootIsOurs, stripOurMentions, shouldEngage, shouldHydrateRoot, threadFor, worthNudging, } from "./threading.js";
15
+ import { isResetCommand, RESET_ACK } from "./conversation-epochs.js";
16
+ import { FOLLOWUP_TTL_MS, holdFollowUp, takeFollowUp } from "./followups.js";
17
+ import { isTurnTimeout } from "./agent.js";
18
+ export function createTurnHandler(deps) {
19
+ const { config, log, rc, agent, state, turnTimings, hooks, bot, denylist, attachmentDepsFor } = deps;
20
+ // Bound: these are methods of a class instance, and destructured bare they lose `this`.
21
+ const postReply = rc.postReply.bind(rc);
22
+ const react = rc.applyReactions.bind(rc);
23
+ const isDirectMessage = rc.isDirectMessage.bind(rc);
24
+ const cachedRoomType = rc.cachedRoomType.bind(rc);
25
+ const { paused, conversationEpochs, roomFor, persistEngagement } = state;
26
+ const { busyConversations, heldFollowUps, startedConversations, markConversationStarted } = state;
27
+ // Nudge and busy-reply throttles: once per thread, not once per message.
28
+ const lastNudges = new Map();
29
+ const lastBusyReplies = new Map();
30
+ // Consecutive failures reaching the agent; reset on the first success, so the
31
+ // room hears "it broke" once per outage rather than once per message.
32
+ let consecutiveAgentFailures = 0;
33
+ /** The root of `tmid`, read at most once per thread. Never throws: an
34
+ * unreadable root is cached as `null` and answers every question with "no". */
35
+ async function readThreadRoot(roomId, tmid) {
36
+ let root = state.cachedThreadRoot(tmid);
37
+ if (root === undefined) {
38
+ const fetched = await getMessage(await attachmentDepsFor(roomId), tmid);
39
+ root = fetched ? { u: fetched.u, mentions: fetched.mentions, msg: fetched.msg } : null;
40
+ state.cacheThreadRoot(tmid, root);
41
+ }
42
+ return root ?? undefined;
43
+ }
44
+ /** Post as participation: record the posted id and its thread as engaged
45
+ * (persisted), which only gates the "Not picking this up" nudge. Refusals and
46
+ * control output go through `postReply` directly. Never throws. */
47
+ async function reply(roomId, text, tmid) {
48
+ const id = await postReply(roomId, text, tmid);
49
+ const room = roomFor(roomId);
50
+ remember(room.engagedIds, id);
51
+ remember(room.engagedIds, tmid);
52
+ persistEngagement();
53
+ return id;
54
+ }
55
+ /** Everything after the fast 200: run the agent turn and relay its reply. */
56
+ async function handleMessage(payload) {
57
+ // Loop guards: never react to ourselves. `bot` is checked for TRUTH, not
58
+ // `=== true`: Rocket.Chat sends `{ i: "<integration id>" }`.
59
+ if (payload.bot)
60
+ return;
61
+ if (payload.user_id && payload.user_id === config.rc.userId)
62
+ return;
63
+ if (payload.user_name && payload.user_name.toLowerCase() === config.rc.botUsername)
64
+ return;
65
+ // โ€ฆand never react to a voice a plugin says is ours (a second account speaking for us must not answer itself).
66
+ if (hooks.isOwnVoice(payload))
67
+ return;
68
+ // โ€ฆand never to other bots: `payload.bot` is unreliable, so match the denylist.
69
+ if (payload.user_id && denylist.ids.has(payload.user_id)) {
70
+ log(`ignoring message from denylisted bot id ${payload.user_id}`);
71
+ return;
72
+ }
73
+ if (payload.user_name && denylist.usernames.has(payload.user_name.toLowerCase())) {
74
+ log(`ignoring message from denylisted bot ${payload.user_name}`);
75
+ return;
76
+ }
77
+ const roomId = payload.channel_id;
78
+ if (!roomId)
79
+ return;
80
+ if (config.allowedRoomIds.length > 0 && !config.allowedRoomIds.includes(roomId)) {
81
+ log(`ignoring message from unlisted room ${roomId}`);
82
+ return;
83
+ }
84
+ // Control commands: after the bot guards, before the pause and any agent
85
+ // call, so the switch works when the agent is wedged.
86
+ const command = hooks.controlCommand(payload.text ?? "");
87
+ if (command) {
88
+ await command({ payload, roomId, thread: threadFor(payload) });
89
+ return;
90
+ }
91
+ // A near-miss stops here with usage, never an agent turn. Uncapped:
92
+ // a post cap that already fired must not hide the right spelling.
93
+ const usage = hooks.controlNearMiss(payload.text ?? "");
94
+ if (usage) {
95
+ log(`near-miss control command from ${payload.user_name}: ${JSON.stringify(payload.text)}`);
96
+ await postReply(roomId, usage, threadFor(payload), { uncapped: true });
97
+ return;
98
+ }
99
+ // Paused: nothing is picked up, silently โ€” "I'm paused" would be its own flood.
100
+ if (paused.active) {
101
+ log(`paused (by ${paused.by ?? "unknown"}) โ€” ignoring message in ${roomId}`);
102
+ return;
103
+ }
104
+ // An upload arrives with empty `text`; re-read it for the caption. A message
105
+ // RC converted to a text file IS the message, and becomes
106
+ // `rawText` HERE, before the addressing gate: its @mention is inside the file.
107
+ let fetched;
108
+ let rawText = payload.text?.trim() ?? "";
109
+ if (!rawText) {
110
+ if (!payload.message_id)
111
+ return;
112
+ fetched = await fetchMessageAttachments(await attachmentDepsFor(roomId), payload.message_id);
113
+ if (!fetched)
114
+ return;
115
+ rawText = pastedMessageText(fetched) || fetched.text;
116
+ if (!rawText && !fetched.images.length && !fetched.documents.length && !fetched.skipped.length)
117
+ return;
118
+ }
119
+ const room = roomFor(roomId);
120
+ // Threaded replies only, so ordinary prompts pay no extra RC read, and a
121
+ // consumed reply (an approval) never becomes an agent turn.
122
+ if (payload.tmid && hooks.interceptsReplies) {
123
+ const root = await readThreadRoot(roomId, payload.tmid);
124
+ if (await hooks.interceptReply({ payload, roomId, text: rawText, root }))
125
+ return;
126
+ }
127
+ // Everything said about this message goes in ONE thread: the one the human
128
+ // is in, or a new one rooted on their message.
129
+ const thread = threadFor(payload);
130
+ const isDM = await isDirectMessage(roomId);
131
+ // ANY of our faces counts as a mention.
132
+ const mentionedUs = mentionsUs(rawText, bot);
133
+ // Engage only when addressed (see `shouldEngage`): an @mention, a DM, the
134
+ // thread's owner, someone our root named, or anyone under a root
135
+ // that tagged us. The root is read ONLY when the cheap local
136
+ // checks fail. RESPOND_TO_ALL=1 bypasses the gate.
137
+ if (!config.respondToAll) {
138
+ const addressing = {
139
+ mentioned: mentionedUs,
140
+ isDM,
141
+ tmid: payload.tmid,
142
+ sender: payload.user_name,
143
+ threadOwners: room.threadOwners,
144
+ };
145
+ let engage = shouldEngage(addressing);
146
+ if (!engage && payload.tmid) {
147
+ const root = await readThreadRoot(roomId, payload.tmid);
148
+ const invited = rootInvites(root, bot, payload.user_name);
149
+ const ourRoot = rootIsOurs(root, bot);
150
+ const addressesUs = rootAddressesUs(root, bot);
151
+ engage = shouldEngage({ ...addressing, invited, ourRoot, rootAddressesUs: addressesUs });
152
+ if (engage) {
153
+ log(invited
154
+ ? `engaging: ${payload.user_name} was named in thread root ${payload.tmid}`
155
+ : addressesUs
156
+ ? `engaging: ${payload.user_name} replied in thread ${payload.tmid}, whose root @mentions us`
157
+ : `engaging: ${payload.user_name} answered our unclaimed thread ${payload.tmid}`);
158
+ }
159
+ }
160
+ if (!engage) {
161
+ log(`ignoring ${roomId}: not @mentioned, not a DM with us, not named in or owner of thread ${payload.tmid ?? "(none)"}`);
162
+ // Nudge only someone who had reason to expect an answer: a reply in a
163
+ // thread we are already in. `postReply`, not `reply`: a
164
+ // refusal is not participation.
165
+ if (config.nudgeWhenIgnored && worthNudging(payload, room) && nudgeAllowed(lastNudges, `${roomId}:${thread}`, Date.now())) {
166
+ await postReply(roomId, `Not picking this up โ€” @${config.rc.botUsername} me and I will.`, thread);
167
+ }
168
+ hooks.onTurnSettled({
169
+ roomId,
170
+ roomName: payload.channel_name,
171
+ threadId: thread,
172
+ requester: payload.user_name,
173
+ promptChars: rawText.length,
174
+ images: fetched?.images.length ?? 0,
175
+ documents: fetched?.documents.length ?? 0,
176
+ replyChars: 0,
177
+ durationMs: 0,
178
+ tools: [],
179
+ status: "ignored",
180
+ });
181
+ return;
182
+ }
183
+ }
184
+ // First writer wins the thread; recorded before any await.
185
+ rememberOwner(room.threadOwners, thread, payload.user_name);
186
+ // The receipt: ๐Ÿ‘€ on pickup, then โœ… / โš ๏ธ / โณ when the turn
187
+ // settles. Chained so the moves land in order; never awaited by the turn.
188
+ let receipt;
189
+ let receiptChain = Promise.resolve();
190
+ const setReceipt = (to) => {
191
+ const messageId = payload.message_id;
192
+ if (!messageId)
193
+ return;
194
+ const changes = receiptTransition(receipt, to);
195
+ receipt = to;
196
+ if (changes.length)
197
+ receiptChain = receiptChain.then(() => react(roomId, messageId, changes));
198
+ };
199
+ setReceipt("seen");
200
+ let prompt = stripOurMentions(rawText, bot);
201
+ // `/new` starts the room over: after the gate, before any agent
202
+ // call, and never forwarded โ€” the gateway ignores reset triggers here.
203
+ if (isResetCommand(prompt)) {
204
+ const epoch = conversationEpochs.bump(roomId);
205
+ log(`${payload.user_name} reset ${roomId}: top-level conversation now on epoch ${epoch}`);
206
+ await reply(roomId, RESET_ACK, thread);
207
+ setReceipt("done");
208
+ return;
209
+ }
210
+ // Uploads are fetched only now that we engage, so chatter costs no RC read.
211
+ if (!fetched && payload.message_id) {
212
+ fetched = await fetchMessageAttachments(await attachmentDepsFor(roomId), payload.message_id);
213
+ }
214
+ const images = fetched?.images ?? [];
215
+ // A converted paste is already `prompt`; fencing it too would say it twice.
216
+ const pasted = fetched ? pastedMessageText(fetched) : undefined;
217
+ const documents = pasted ? [] : (fetched?.documents ?? []);
218
+ const skipped = fetched?.skipped ?? [];
219
+ if (pasted) {
220
+ log(`read a ${pasted.length}-char message Rocket.Chat had converted to a file`);
221
+ }
222
+ if (skipped.length) {
223
+ await reply(roomId, `I couldn't read what you sent:\n${skipNotice(skipped)}`, thread);
224
+ }
225
+ if (!prompt && !images.length && !documents.length && !mentionedUs) {
226
+ log(`nothing to answer in ${roomId} โ€” empty message, no attachments`);
227
+ setReceipt(undefined);
228
+ return;
229
+ }
230
+ // An attachment alone, or a bare @mention, is not a request โ€”
231
+ // but it is being spoken to, so the agent is told to describe and ask.
232
+ if (!prompt) {
233
+ prompt = images.length || documents.length
234
+ ? (documents.length ? DOCUMENT_WITHOUT_CONTEXT_PROMPT : IMAGE_WITHOUT_CONTEXT_PROMPT)
235
+ : BARE_MENTION_PROMPT;
236
+ }
237
+ // Document text goes AFTER the human's words, fenced as reference material.
238
+ if (documents.length) {
239
+ prompt = `${prompt}\n\n${documentBlock(documents)}`;
240
+ log(`read ${documents.length} document(s): ${documents
241
+ .map((d) => `${d.name} (${d.pages === undefined ? "text" : `${d.pages}p`}, ${d.text.length} chars${d.truncated ? ", truncated" : ""})`)
242
+ .join(", ")}`);
243
+ }
244
+ // `payload.tmid`, not just `thread`: a threaded DM is its own conversation.
245
+ const conversation = conversationKey(roomId, thread, isDM, payload.tmid, conversationEpochs.epochFor(roomId));
246
+ if (busyConversations.has(conversation)) {
247
+ // HELD, not dropped: it runs when this turn ends โ€” see `finally`.
248
+ const { replaced } = holdFollowUp(heldFollowUps, conversation, payload, Date.now());
249
+ log(`busy on ${conversation} โ€” holding this message until the turn ends` +
250
+ (replaced ? " (replacing an earlier held one)" : ""));
251
+ // Throttled, and thread-scoped in its wording on purpose.
252
+ if (nudgeAllowed(lastBusyReplies, conversation, Date.now(), config.loop.busyReplyCooldownMs)) {
253
+ await reply(roomId, "โณ Still on the previous message in this thread โ€” I've got this one and will answer it next. Other threads carry on as normal.", thread);
254
+ }
255
+ else {
256
+ log(`busy on ${conversation} โ€” reply suppressed by cooldown`);
257
+ }
258
+ return;
259
+ }
260
+ // No cap on turns per thread; the post cap bounds what we EMIT.
261
+ busyConversations.add(conversation);
262
+ const startedAt = Date.now();
263
+ // Context images join the message's own under ONE cap.
264
+ let turnImages = images;
265
+ const imageBudget = () => config.attachments.maxImages - turnImages.length;
266
+ // Pulled into a thread that started without us: carry its root as context,
267
+ // once, on the conversation's first turn, images too.
268
+ // DMs and RESPOND_TO_ALL already relayed the root: nothing to recover there.
269
+ if (payload.tmid &&
270
+ shouldHydrateRoot({
271
+ tmid: payload.tmid,
272
+ isDM,
273
+ respondToAll: config.respondToAll,
274
+ conversationStarted: startedConversations.has(conversation),
275
+ })) {
276
+ const root = await fetchThreadRoot(await attachmentDepsFor(roomId), payload.tmid, imageBudget());
277
+ if (root && (root.text || root.images.length)) {
278
+ prompt = `${threadRootBlock(root.text ?? "", root.images.length)}\n\n${prompt}`;
279
+ turnImages = [...turnImages, ...root.images];
280
+ log(`hydrated thread root ${payload.tmid} into ${conversation} (${root.text?.length ?? 0} chars, ${root.images.length} image(s))`);
281
+ }
282
+ if (root?.skipped.length)
283
+ log(`thread root ${payload.tmid}: left out ${skipNotice(root.skipped)}`);
284
+ }
285
+ // An addressed channel message with no image of its own: "that" may be the
286
+ // sender's untagged upload a few minutes ago. One history read,
287
+ // only here, past the gate; a DM or RESPOND_TO_ALL already turned each upload.
288
+ if (!isDM && !config.respondToAll && !images.length && config.attachments.lookbackMs > 0 && imageBudget() > 0) {
289
+ const recent = await fetchRecentImages(await attachmentDepsFor(roomId), {
290
+ roomId,
291
+ roomType: cachedRoomType(roomId),
292
+ senderId: payload.user_id,
293
+ senderName: payload.user_name,
294
+ messageId: payload.message_id,
295
+ tmid: payload.tmid,
296
+ windowMs: config.attachments.lookbackMs,
297
+ budget: imageBudget(),
298
+ now: Date.now(),
299
+ bot,
300
+ });
301
+ if (recent?.images.length) {
302
+ prompt = `${prompt}\n\n${lookbackNote(recent.images.length, config.attachments.lookbackMs)}`;
303
+ turnImages = [...turnImages, ...recent.images];
304
+ log(`carried ${recent.images.length} recent image(s) from ${payload.user_name} into ${conversation}`);
305
+ }
306
+ if (recent?.skipped.length)
307
+ log(`recent uploads in ${roomId}: left out ${skipNotice(recent.skipped)}`);
308
+ }
309
+ const turn = { payload, roomId, thread, isDM, conversation, prompt };
310
+ const streaming = agent.shouldTryStreaming();
311
+ let runEvents;
312
+ // For /health's turn timings: when the agent call began, and which profile took it.
313
+ let agentStartedAt;
314
+ let profile;
315
+ const traceBase = {
316
+ roomId,
317
+ roomName: payload.channel_name,
318
+ threadId: thread,
319
+ requester: payload.user_name,
320
+ conversation,
321
+ promptChars: prompt.length,
322
+ images: turnImages.length,
323
+ documents: documents.length,
324
+ };
325
+ try {
326
+ // The context header tells the agent where it is standing and who asked, with
327
+ // the room and thread ids a scheduled run needs to speak back.
328
+ const framed = [contextHeader(payload, isDM, thread), ...(await hooks.framing(turn)), REACTION_HINT, prompt]
329
+ .filter(Boolean)
330
+ .join("\n");
331
+ const routed = (await hooks.targetForRoom(roomId)) ?? { target: deps.defaultTarget, profile: "default" };
332
+ const { target } = routed;
333
+ profile = routed.profile;
334
+ // The stream went quiet: is the run parked on a human? A plain GET, never a
335
+ // touch on the stream. Told once per turn.
336
+ const parkCheck = async (responseId) => {
337
+ const run = await agent.readRun(target, responseId);
338
+ if (!run.ok) {
339
+ log(`park check failed for ${responseId}: ${run.error}`);
340
+ return "unknown";
341
+ }
342
+ if (run.done || !run.parked)
343
+ return run.done ? "unknown" : "running";
344
+ if (!runEvents) {
345
+ runEvents = captureRunEvents({ url: target.url, apiKey: target.apiKey, runId: responseId });
346
+ }
347
+ const details = runEvents.snapshot();
348
+ await hooks.onRunParked(turn, {
349
+ runId: responseId,
350
+ status: run.status,
351
+ ...(details.command ? { command: details.command } : {}),
352
+ ...(details.choices ? { choices: details.choices } : {}),
353
+ ...(run.createdAt ? { createdAt: run.createdAt } : {}),
354
+ ...(run.lastEvent ? { lastEvent: run.lastEvent } : {}),
355
+ });
356
+ return "parked";
357
+ };
358
+ agentStartedAt = Date.now();
359
+ const { text: answer, tools, unknownTypes, timings, ...turnUsage } = streaming
360
+ ? await agent.askStreaming(target, conversation, framed, turnImages, (responseId) => {
361
+ runEvents = captureRunEvents({ url: target.url, apiKey: target.apiKey, runId: responseId });
362
+ }, parkCheck)
363
+ : await agent.ask(target, conversation, framed, turnImages);
364
+ turnTimings.record({ at: new Date().toISOString(), room: roomId, profile, status: "ok", ...timings, tools: tools.length });
365
+ runEvents?.close();
366
+ runEvents = undefined;
367
+ consecutiveAgentFailures = 0; // reachable again
368
+ // The gateway now chains this conversation: no further root hydration.
369
+ markConversationStarted(conversation);
370
+ log(`turn done in ${Date.now() - startedAt}ms ยท ${describeTools(tools)}`);
371
+ if (unknownTypes.length)
372
+ log(`unrecognised output item types: ${[...new Set(unknownTypes)].join(", ")}`);
373
+ // `[react: ๐Ÿ‘]` anywhere in the reply becomes a reaction on the human's
374
+ // message; a reply that was ONLY a reaction posts nothing.
375
+ const said = extractReactions(answer);
376
+ if (said.unknown.length)
377
+ log(`ignored unknown reaction(s) ${said.unknown.join(" ")} โ€” not on the shortcode map`);
378
+ const finalText = (await hooks.onAnswer(turn, said.text)) || (said.emoji.length ? "" : "(no reply)");
379
+ // Posted ONCE, finished: the creation is the notification.
380
+ if (finalText)
381
+ await reply(roomId, finalText, thread);
382
+ if (said.emoji.length && payload.message_id) {
383
+ const messageId = payload.message_id;
384
+ receiptChain = receiptChain.then(() => react(roomId, messageId, said.emoji.map((emoji) => ({ emoji, shouldReact: true }))));
385
+ }
386
+ // The agent's own reaction already says "answered"; a โœ… beside it is noise.
387
+ setReceipt(said.emoji.length ? undefined : "done");
388
+ hooks.onTurnSettled({
389
+ ...traceBase,
390
+ replyChars: answer.length,
391
+ durationMs: Date.now() - startedAt,
392
+ tools,
393
+ status: "ok",
394
+ startedAt,
395
+ usage: turnUsage,
396
+ answer: said.text,
397
+ });
398
+ }
399
+ catch (err) {
400
+ runEvents?.close();
401
+ runEvents = undefined;
402
+ const message = err?.message ?? String(err);
403
+ log("turn failed:", message);
404
+ if (agentStartedAt !== undefined) {
405
+ const totalMs = Date.now() - agentStartedAt;
406
+ turnTimings.record({ at: new Date().toISOString(), room: roomId, profile, status: "error", firstEventMs: null, firstTextMs: null, totalMs, tools: 0 });
407
+ }
408
+ hooks.onTurnSettled({
409
+ ...traceBase,
410
+ replyChars: 0,
411
+ durationMs: Date.now() - startedAt,
412
+ tools: [],
413
+ status: "error",
414
+ error: message,
415
+ });
416
+ // A turn ceiling is not a failure: the gateway keeps working after we hang
417
+ // up and the conversation keeps its state, so say that calmly. Classified
418
+ // on the error's TYPE: the streamed request's message never matched a regex.
419
+ const agentTimedOut = isTurnTimeout(err);
420
+ // On the message itself, even when the breaker keeps the room quiet.
421
+ setReceipt(agentTimedOut ? "waiting" : "failed");
422
+ // CIRCUIT BREAKER: the agent being down is ONE fact. Say it once,
423
+ // then stay quiet until a turn succeeds; the log still gets every failure.
424
+ if (!agentTimedOut) {
425
+ consecutiveAgentFailures++;
426
+ if (consecutiveAgentFailures > 1) {
427
+ log(`Agent unreachable (${consecutiveAgentFailures} in a row) โ€” staying quiet in ${roomId}: ${message}`);
428
+ return;
429
+ }
430
+ }
431
+ await reply(roomId, agentTimedOut
432
+ ? `This one ran past my ${Math.round(config.agent.timeoutMs / 60_000)}-minute wait, but the agent is still working server-side โ€” anything it announces will land here, and a follow-up in this thread picks the conversation right back up.`
433
+ : `โš ๏ธ Can't reach the agent right now. I'll stay quiet until it's back.`, thread);
434
+ }
435
+ finally {
436
+ busyConversations.delete(conversation);
437
+ // Whatever arrived mid-turn runs now, tracked like a webhook
438
+ // turn so a shutdown waits for it โ€” unless we are draining.
439
+ const held = takeFollowUp(heldFollowUps, conversation, Date.now(), FOLLOWUP_TTL_MS);
440
+ if (held && deps.isDraining()) {
441
+ log(`draining โ€” dropping the message held on ${conversation}`);
442
+ }
443
+ else if (held) {
444
+ log(`running the message held on ${conversation}`);
445
+ deps.track(handleMessage(held));
446
+ }
447
+ }
448
+ }
449
+ return { handleMessage, reply };
450
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@practicalworks/rc-bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Puts Rocket.Chat in front of an OpenAI-compatible agent: an outgoing-webhook relay with one conversation per thread, reactions as receipts, attachments, streaming, and a plugin seam.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "bin": {
16
+ "rc-bridge": "dist/main.js"
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "keywords": [
22
+ "rocket.chat",
23
+ "rocketchat",
24
+ "bridge",
25
+ "agent",
26
+ "openai"
27
+ ],
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "dependencies": {
32
+ "unpdf": "^1.8.0",
33
+ "@practicalworks/rc-client": "0.1.0"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^22.0.0",
37
+ "tsx": "^4.23.0",
38
+ "typescript": "^5.5.0",
39
+ "vitest": "^3.0.0"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/PracticalWorks/rc-bridge.git",
44
+ "directory": "packages/bridge"
45
+ },
46
+ "publishConfig": {
47
+ "registry": "https://registry.npmjs.org/",
48
+ "access": "public",
49
+ "provenance": true
50
+ },
51
+ "scripts": {
52
+ "build": "tsc -p tsconfig.json",
53
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json",
54
+ "test": "vitest run"
55
+ }
6
56
  }