@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,121 @@
1
+ // Bounding a room's agent conversation.
2
+ //
3
+ // `conversationKey` maps every top-level message in a DM (or an unthreaded
4
+ // channel message) to ONE named agent conversation, and a Responses API that
5
+ // chains named conversations chains them forever: a gateway's session reset may
6
+ // default to never, and a named conversation never sees `/new` because the
7
+ // bridge forwards it as prose. So a room's context only ever grows.
8
+ //
9
+ // Unbounded, it breaks quietly: each turn spends its time compressing the
10
+ // history, and the model answers from the compressed summary, claiming its
11
+ // tools are unreachable without calling one, while every tool is up.
12
+ //
13
+ // Two bounds, both applied only to the ROOM-level key. A thread key already
14
+ // starts fresh and is left alone:
15
+ //
16
+ // 1. A daily boundary at a fixed local hour, 04:00, so the boundary falls where nobody is
17
+ // mid-conversation. Continuity WITHIN a day is unchanged.
18
+ // 2. A human typing `/new` or `/reset` bumps the room's epoch by hand, for
19
+ // the day the context has gone bad before the boundary. Persisted, so a
20
+ // bridge restart cannot quietly hand a "reset" room its old context back.
21
+ //
22
+ // Nothing here talks to Rocket.Chat or the agent, so it is testable without
23
+ // booting the bridge.
24
+ import { readFileSync, writeFileSync } from "node:fs";
25
+ /** The daily boundary: 4 AM local. */
26
+ const DAILY_RESET_HOUR = 4;
27
+ const pad = (n) => String(n).padStart(2, "0");
28
+ /**
29
+ * The calendar day a moment belongs to, where days roll over at `atHour`
30
+ * local time rather than midnight. 03:59 on the 2nd is still the 1st's day.
31
+ *
32
+ * Decided from the LOCAL clock, not by subtracting `atHour` hours from the
33
+ * instant: those differ whenever the UTC offset moves. On the morning the
34
+ * clocks fall back, 03:30 EST is four hours and thirty minutes after the
35
+ * previous 04:00 boundary by the instant arithmetic, yet still before 04:00
36
+ * by the clock on the wall — and the wall clock is the one the boundary was
37
+ * promised in.
38
+ */
39
+ export function dailyEpoch(now, atHour = DAILY_RESET_HOUR) {
40
+ // `new Date(y, m, d - 1)` normalises across month and year ends.
41
+ const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - (now.getHours() < atHour ? 1 : 0));
42
+ return `${day.getFullYear()}-${pad(day.getMonth() + 1)}-${pad(day.getDate())}`;
43
+ }
44
+ /**
45
+ * Is this message a request to start over? `/new` or `/reset`, on its own,
46
+ * case-insensitive, with any @mentions of us already stripped or still
47
+ * present — "@bot /new" and "/new" both count. Anything else ("/new plan
48
+ * for the week") is prose and goes to the agent as usual.
49
+ */
50
+ export function isResetCommand(text) {
51
+ return /^\s*(?:@[\w.-]+\s+)*\/(?:new|reset)(?:\s+@[\w.-]+)*\s*$/i.test(text);
52
+ }
53
+ /** What the bridge says back. One line, in the thread the human is in. */
54
+ export const RESET_ACK = "🧹 Fresh conversation started for this room — earlier messages here are no longer in my context. Threads always start fresh on their own.";
55
+ /**
56
+ * Per-room manual resets, persisted as `{ [roomId]: { day, n } }`.
57
+ *
58
+ * The counter is scoped to a day so the epoch string stays short and a
59
+ * long-lived room never accumulates a number that means nothing: a `/new`
60
+ * yesterday is already covered by today's boundary.
61
+ */
62
+ export class ConversationEpochs {
63
+ file;
64
+ log;
65
+ atHour;
66
+ rooms = new Map();
67
+ constructor(file, log = () => { }, atHour = DAILY_RESET_HOUR) {
68
+ this.file = file;
69
+ this.log = log;
70
+ this.atHour = atHour;
71
+ this.load();
72
+ }
73
+ /** The epoch to key this room's top-level conversation on, right now. */
74
+ epochFor(roomId, now = new Date()) {
75
+ const day = dailyEpoch(now, this.atHour);
76
+ const manual = this.rooms.get(roomId);
77
+ return manual && manual.day === day && manual.n > 0 ? `${day}.${manual.n}` : day;
78
+ }
79
+ /** A human asked for a fresh start: advance the room's epoch and persist. */
80
+ bump(roomId, now = new Date()) {
81
+ const day = dailyEpoch(now, this.atHour);
82
+ const current = this.rooms.get(roomId);
83
+ const n = current && current.day === day ? current.n + 1 : 1;
84
+ this.rooms.set(roomId, { day, n });
85
+ this.persist();
86
+ return this.epochFor(roomId, now);
87
+ }
88
+ load() {
89
+ if (!this.file)
90
+ return;
91
+ let raw;
92
+ try {
93
+ raw = readFileSync(this.file, "utf8");
94
+ }
95
+ catch {
96
+ return; // no state yet — every room is on its daily epoch
97
+ }
98
+ try {
99
+ const parsed = JSON.parse(raw);
100
+ for (const [roomId, value] of Object.entries(parsed)) {
101
+ const v = value;
102
+ if (typeof v?.day === "string" && typeof v?.n === "number" && v.n > 0) {
103
+ this.rooms.set(roomId, { day: v.day, n: v.n });
104
+ }
105
+ }
106
+ }
107
+ catch (err) {
108
+ this.log(`ignoring unreadable conversation epochs in ${this.file}: ${err?.message ?? err}`);
109
+ }
110
+ }
111
+ persist() {
112
+ if (!this.file)
113
+ return;
114
+ try {
115
+ writeFileSync(this.file, JSON.stringify(Object.fromEntries(this.rooms)), "utf8");
116
+ }
117
+ catch (err) {
118
+ this.log(`could not persist conversation epochs to ${this.file}: ${err?.message ?? err}`);
119
+ }
120
+ }
121
+ }
@@ -0,0 +1,16 @@
1
+ import { type Log } from "./config.js";
2
+ import type { RocketChatClient } from "@practicalworks/rc-client";
3
+ export interface BotDenylistOptions {
4
+ rc: Pick<RocketChatClient, "get" | "botHeaders">;
5
+ rcUrl: string;
6
+ /** Our own id: never denylisted here, the self-guard owns it. */
7
+ selfUserId: string;
8
+ log: Log;
9
+ env?: NodeJS.ProcessEnv;
10
+ }
11
+ /** The lists, loaded from env and the file now; `refreshFromRc` tops them up. */
12
+ export declare function createBotDenylist(opts: BotDenylistOptions): {
13
+ ids: Set<string>;
14
+ usernames: Set<string>;
15
+ refreshFromRc: () => Promise<void>;
16
+ };
@@ -0,0 +1,86 @@
1
+ // The other-bot denylist. We never react to a bot's messages (loop risk / noise).
2
+ // Rocket.Chat doesn't reliably set `payload.bot`, so we match on user id/username
3
+ // instead: static env, plus an optional JSON file, topped up by ONE `users.list`
4
+ // call at boot, never per message. Belt-and-braces: `shouldEngage`
5
+ // is what actually holds.
6
+ import { readFileSync } from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { envList } from "./config.js";
10
+ /** Roles that make an account a bot. Anything else is a person. */
11
+ const BOT_ROLES = new Set(["bot", "app"]);
12
+ /** The lists, loaded from env and the file now; `refreshFromRc` tops them up. */
13
+ export function createBotDenylist(opts) {
14
+ const { rc, log } = opts;
15
+ const env = opts.env ?? process.env;
16
+ const ids = new Set(envList("ROCKETCHAT_IGNORE_USER_IDS", env));
17
+ const usernames = new Set(envList("ROCKETCHAT_IGNORE_USERNAMES", env).map((s) => s.toLowerCase()));
18
+ const file = env.ROCKETCHAT_BOT_DENYLIST_FILE ?? path.join(os.homedir(), "rocketchat-bridge", "bot-users.json");
19
+ let raw;
20
+ try {
21
+ raw = readFileSync(file, "utf8");
22
+ }
23
+ catch {
24
+ log(`no bot denylist file at ${file} — relying on self-guard + env ignore lists`);
25
+ }
26
+ if (raw !== undefined) {
27
+ try {
28
+ const parsed = JSON.parse(raw);
29
+ for (const id of parsed.ids ?? [])
30
+ ids.add(id);
31
+ for (const u of parsed.usernames ?? [])
32
+ usernames.add(u.toLowerCase());
33
+ log(`loaded bot denylist from ${file}: ${ids.size} ids, ${usernames.size} usernames`);
34
+ }
35
+ catch (err) {
36
+ log(`bot denylist file ${file} is not valid JSON: ${err?.message ?? err}`);
37
+ }
38
+ }
39
+ const refreshEnabled = !/^(0|false|no)$/i.test(env.RC_BOT_REFRESH ?? "");
40
+ /**
41
+ * One `users.list` at boot, so the list is never left to be filled by hand.
42
+ * Rocket.Chat ignores a server-side `roles` query and returns every user, which
43
+ * would denylist every human: filter client-side.
44
+ * Best-effort: an account that cannot list users keeps what env and file gave.
45
+ */
46
+ async function refreshFromRc() {
47
+ if (!refreshEnabled)
48
+ return log("bot denylist refresh disabled (RC_BOT_REFRESH=0)");
49
+ try {
50
+ const res = await rc.get(`${opts.rcUrl}/api/v1/users.list?count=0&fields=${encodeURIComponent(JSON.stringify({ username: 1, roles: 1 }))}`, rc.botHeaders(), "Rocket.Chat users.list");
51
+ if (!res.ok) {
52
+ log(`bot denylist refresh skipped: users.list returned ${res.status} (needs an admin-capable account)`);
53
+ return;
54
+ }
55
+ const { users = [] } = (await res.json());
56
+ // FILTER HERE, NOT ON THE SERVER: current Rocket.Chat ignores a `query` on
57
+ // roles and returns EVERY user, which would mute every human.
58
+ const bots = users.filter((u) => (u.roles ?? []).some((r) => BOT_ROLES.has(r.toLowerCase())));
59
+ // Refuse a result that looks unfiltered: denylisting everyone must fail
60
+ // safe rather than quietly mute the bridge.
61
+ if (users.length > 0 && bots.length === users.length) {
62
+ log(`bot denylist refresh REFUSED: all ${users.length} accounts claim a bot role, which cannot be right. ` +
63
+ `Keeping the existing list. Set ROCKETCHAT_IGNORE_USERNAMES if you need one.`);
64
+ return;
65
+ }
66
+ let added = 0;
67
+ for (const u of bots) {
68
+ // Never denylist ourselves via this path; an id in two places is a debugging trap.
69
+ if (u._id === opts.selfUserId)
70
+ continue;
71
+ if (u._id && !ids.has(u._id)) {
72
+ ids.add(u._id);
73
+ added++;
74
+ }
75
+ if (u.username)
76
+ usernames.add(u.username.toLowerCase());
77
+ }
78
+ log(`bot denylist refreshed: ${bots.length} bot account(s) of ${users.length} users, ${added} new` +
79
+ (bots.length ? ` — ${bots.map((b) => b.username).filter(Boolean).join(", ")}` : ""));
80
+ }
81
+ catch (err) {
82
+ log(`bot denylist refresh failed: ${err?.message ?? err}`);
83
+ }
84
+ }
85
+ return { ids, usernames, refreshFromRc };
86
+ }
@@ -0,0 +1,38 @@
1
+ /** A message held while its conversation was busy. */
2
+ export interface HeldFollowUp<T> {
3
+ payload: T;
4
+ /** When it was held, for the TTL below. */
5
+ at: number;
6
+ }
7
+ /** How long a held message stays worth running.
8
+ *
9
+ * A hold exists to survive ONE turn, and a turn is bounded by
10
+ * `AGENT_TIMEOUT_MS` (six minutes). Past that the turn it was waiting behind
11
+ * did not merely run long, something went wrong — the gateway hung, the process
12
+ * restarted mid-flight — and replaying a stale message into a conversation that
13
+ * has since moved on is worse than dropping it, because it arrives with no
14
+ * indication that it is ten minutes late. */
15
+ export declare const FOLLOWUP_TTL_MS: number;
16
+ /**
17
+ * Hold this message until the conversation's current turn ends.
18
+ *
19
+ * ONE per conversation, and the LATEST wins. A person who types three lines
20
+ * while waiting is not asking for three turns — the later lines are usually a
21
+ * correction or a completion of the first, and replaying a backlog into a
22
+ * conversation that has already been answered is its own kind of wrong.
23
+ *
24
+ * Returns whether this REPLACED an earlier hold, so the caller can log the
25
+ * message it is choosing not to run. Discarding silently is the failure this
26
+ * module exists to prevent; discarding on purpose and saying so in the log is not.
27
+ */
28
+ export declare function holdFollowUp<T>(held: Map<string, HeldFollowUp<T>>, conversation: string, payload: T, now: number, max?: number): {
29
+ replaced: boolean;
30
+ };
31
+ /**
32
+ * Take the message held for this conversation, if it is still worth running.
33
+ *
34
+ * Always removes it, expired or not: a hold that is too old to run is also too
35
+ * old to keep, and leaving it would let one abandoned conversation pin a payload
36
+ * in memory forever.
37
+ */
38
+ export declare function takeFollowUp<T>(held: Map<string, HeldFollowUp<T>>, conversation: string, now: number, ttlMs?: number): T | undefined;
@@ -0,0 +1,65 @@
1
+ // A message that arrives mid-turn is a message, not noise.
2
+ //
3
+ // The busy guard is right that a second message cannot join a turn
4
+ // already in flight: the gateway is mid-run, and two answers interleaving in one
5
+ // thread is the confusion it was written to prevent. But it must not DROP that
6
+ // message: a person told "⏳ Still on your last message" reads it as queued, and
7
+ // a dropped message never reaches the agent at all.
8
+ //
9
+ // That window is not small: turns of a minute or two are ordinary, and
10
+ // `AGENT_TIMEOUT_MS` allows six. So hold the message instead, and say so. Kept
11
+ // apart from main.ts, which reads required env at import time, so this is
12
+ // unit-testable.
13
+ /** How long a held message stays worth running.
14
+ *
15
+ * A hold exists to survive ONE turn, and a turn is bounded by
16
+ * `AGENT_TIMEOUT_MS` (six minutes). Past that the turn it was waiting behind
17
+ * did not merely run long, something went wrong — the gateway hung, the process
18
+ * restarted mid-flight — and replaying a stale message into a conversation that
19
+ * has since moved on is worse than dropping it, because it arrives with no
20
+ * indication that it is ten minutes late. */
21
+ export const FOLLOWUP_TTL_MS = 10 * 60_000;
22
+ /** How many conversations may hold a message at once. A backstop: holds are one
23
+ * per conversation and are consumed by the turn they queue behind, so this only
24
+ * matters if turns stop finishing. */
25
+ const MAX_HELD_FOLLOWUPS = 200;
26
+ /**
27
+ * Hold this message until the conversation's current turn ends.
28
+ *
29
+ * ONE per conversation, and the LATEST wins. A person who types three lines
30
+ * while waiting is not asking for three turns — the later lines are usually a
31
+ * correction or a completion of the first, and replaying a backlog into a
32
+ * conversation that has already been answered is its own kind of wrong.
33
+ *
34
+ * Returns whether this REPLACED an earlier hold, so the caller can log the
35
+ * message it is choosing not to run. Discarding silently is the failure this
36
+ * module exists to prevent; discarding on purpose and saying so in the log is not.
37
+ */
38
+ export function holdFollowUp(held, conversation, payload, now, max = MAX_HELD_FOLLOWUPS) {
39
+ const replaced = held.has(conversation);
40
+ held.set(conversation, { payload, at: now });
41
+ // Bounded like every other map in the bridge. Oldest key first, and never the
42
+ // one just written — evicting the hold we were asked to keep would be the
43
+ // original bug with extra steps.
44
+ while (held.size > max) {
45
+ const oldest = held.keys().next().value;
46
+ if (oldest === undefined || oldest === conversation)
47
+ break;
48
+ held.delete(oldest);
49
+ }
50
+ return { replaced };
51
+ }
52
+ /**
53
+ * Take the message held for this conversation, if it is still worth running.
54
+ *
55
+ * Always removes it, expired or not: a hold that is too old to run is also too
56
+ * old to keep, and leaving it would let one abandoned conversation pin a payload
57
+ * in memory forever.
58
+ */
59
+ export function takeFollowUp(held, conversation, now, ttlMs = FOLLOWUP_TTL_MS) {
60
+ const pending = held.get(conversation);
61
+ if (!pending)
62
+ return undefined;
63
+ held.delete(conversation);
64
+ return now - pending.at > ttlMs ? undefined : pending.payload;
65
+ }
@@ -0,0 +1,26 @@
1
+ import type { PostVoice } from "@practicalworks/rc-client";
2
+ import type { Log } from "./config.js";
3
+ import type { BridgePlugin, ControlContext, ParkedRun, RoutedTarget, ThreadedReply, Turn, TurnRecord, WebhookPayload } from "./plugin.js";
4
+ export type Hooks = ReturnType<typeof composeHooks>;
5
+ export declare function composeHooks(plugins: readonly BridgePlugin[], log: Log): {
6
+ identityForRoom: (roomId: string) => Promise<Record<string, string> | undefined>;
7
+ isDirectMessageFallback: (roomId: string) => Promise<boolean>;
8
+ isOwnVoice: (payload: WebhookPayload) => boolean;
9
+ targetForRoom: (roomId: string) => Promise<RoutedTarget | undefined>;
10
+ /** Every plugin's preamble, in plugin order. */
11
+ framing(turn: Turn): Promise<string[]>;
12
+ outbound(text: string): {
13
+ text: string;
14
+ voice?: PostVoice;
15
+ };
16
+ /** Whether any plugin looks at threaded replies; if none, the root is not read. */
17
+ interceptsReplies: boolean;
18
+ interceptReply(reply: ThreadedReply): Promise<boolean>;
19
+ onRunParked(turn: Turn, run: ParkedRun): Promise<void>;
20
+ onAnswer(turn: Turn, text: string): Promise<string>;
21
+ /** Called in plugin order and never awaited; a throw is logged, never raised. */
22
+ onTurnSettled(record: TurnRecord): void;
23
+ controlCommand(text: string): ((ctx: ControlContext) => Promise<void>) | undefined;
24
+ controlNearMiss(text: string): string | undefined;
25
+ health(): Record<string, unknown>;
26
+ };
package/dist/hooks.js ADDED
@@ -0,0 +1,88 @@
1
+ export function composeHooks(plugins, log) {
2
+ /** The first plugin whose hook answers something other than undefined. */
3
+ async function first(ask) {
4
+ for (const p of plugins) {
5
+ const answer = await ask(p);
6
+ if (answer !== undefined)
7
+ return answer;
8
+ }
9
+ return undefined;
10
+ }
11
+ return {
12
+ identityForRoom: (roomId) => first((p) => p.identityForRoom?.(roomId)),
13
+ isDirectMessageFallback: async (roomId) => (await first((p) => p.isDirectMessageFallback?.(roomId))) ?? false,
14
+ isOwnVoice: (payload) => plugins.some((p) => p.isOwnVoice?.(payload) === true),
15
+ targetForRoom: (roomId) => first((p) => p.targetForRoom?.(roomId)),
16
+ /** Every plugin's preamble, in plugin order. */
17
+ async framing(turn) {
18
+ const parts = [];
19
+ for (const p of plugins) {
20
+ const part = await p.framing?.(turn);
21
+ if (part)
22
+ parts.push(part);
23
+ }
24
+ return parts;
25
+ },
26
+ outbound(text) {
27
+ let out = { text };
28
+ for (const p of plugins) {
29
+ if (!p.outbound)
30
+ continue;
31
+ const next = p.outbound(out.text);
32
+ out = { text: next.text, voice: next.voice ?? out.voice };
33
+ }
34
+ return out;
35
+ },
36
+ /** Whether any plugin looks at threaded replies; if none, the root is not read. */
37
+ interceptsReplies: plugins.some((p) => p.interceptReply),
38
+ async interceptReply(reply) {
39
+ for (const p of plugins)
40
+ if (await p.interceptReply?.(reply))
41
+ return true;
42
+ return false;
43
+ },
44
+ async onRunParked(turn, run) {
45
+ for (const p of plugins)
46
+ await p.onRunParked?.(turn, run);
47
+ },
48
+ async onAnswer(turn, text) {
49
+ let out = text;
50
+ for (const p of plugins)
51
+ if (p.onAnswer)
52
+ out = await p.onAnswer(turn, out);
53
+ return out;
54
+ },
55
+ /** Called in plugin order and never awaited; a throw is logged, never raised. */
56
+ onTurnSettled(record) {
57
+ for (const p of plugins) {
58
+ try {
59
+ const pending = p.onTurnSettled?.(record);
60
+ if (pending)
61
+ void pending.catch((err) => log(`${p.name} onTurnSettled failed: ${err?.message ?? err}`));
62
+ }
63
+ catch (err) {
64
+ log(`${p.name} onTurnSettled threw: ${err?.message ?? err}`);
65
+ }
66
+ }
67
+ },
68
+ controlCommand(text) {
69
+ for (const p of plugins) {
70
+ const run = p.controlVerbs?.match(text);
71
+ if (run)
72
+ return run;
73
+ }
74
+ return undefined;
75
+ },
76
+ controlNearMiss(text) {
77
+ for (const p of plugins) {
78
+ const usage = p.controlVerbs?.nearMiss?.(text);
79
+ if (usage)
80
+ return usage;
81
+ }
82
+ return undefined;
83
+ },
84
+ health() {
85
+ return Object.assign({}, ...plugins.map((p) => p.health?.() ?? {}));
86
+ },
87
+ };
88
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { WebhookPayload } from "./plugin.js";
3
+ export interface HttpHandlerDeps {
4
+ port: number;
5
+ tlsEnabled: boolean;
6
+ webhookToken: string;
7
+ isDraining(): boolean;
8
+ inFlight: {
9
+ count(): number;
10
+ track(work: Promise<void>): unknown;
11
+ };
12
+ handleMessage(payload: WebhookPayload): Promise<void>;
13
+ /** The readiness verdict and body: 200 serving, 503 draining, `extra` merged in.
14
+ * Unset, `coreHealthResponse` answers. A deployment can pass its own, for
15
+ * example to fail health on a rejected bot credential. */
16
+ healthResponse?(draining: boolean, extra: Record<string, unknown>): {
17
+ code: number;
18
+ body: Record<string, unknown>;
19
+ } | Promise<{
20
+ code: number;
21
+ body: Record<string, unknown>;
22
+ }>;
23
+ /** Plugin fields, merged between the core's in-flight count and its turn timings. */
24
+ pluginHealth(): Record<string, unknown>;
25
+ turns(): unknown[];
26
+ }
27
+ /** The readiness reply a deployment gets when it passes none: 200 serving, 503
28
+ * draining, `extra` merged in. */
29
+ export declare function coreHealthResponse(draining: boolean, extra: Record<string, unknown>): {
30
+ code: number;
31
+ body: Record<string, unknown>;
32
+ };
33
+ export declare function createHttpHandler(deps: HttpHandlerDeps): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
package/dist/http.js ADDED
@@ -0,0 +1,66 @@
1
+ // The bridge's two routes: GET /health and POST /rocketchat/webhook. The webhook
2
+ // is acked fast and its turn runs detached, tracked so a restart waits for it.
3
+ import { timingSafeEqual } from "node:crypto";
4
+ /** The readiness reply a deployment gets when it passes none: 200 serving, 503
5
+ * draining, `extra` merged in. */
6
+ export function coreHealthResponse(draining, extra) {
7
+ return { code: draining ? 503 : 200, body: { ok: !draining, draining, ...extra } };
8
+ }
9
+ function readBody(req) {
10
+ return new Promise((resolve, reject) => {
11
+ let data = "";
12
+ req.on("data", (c) => (data += c));
13
+ req.on("end", () => resolve(data));
14
+ req.on("error", reject);
15
+ });
16
+ }
17
+ export function createHttpHandler(deps) {
18
+ const tokenBytes = Buffer.from(deps.webhookToken);
19
+ const validWebhookToken = (token) => {
20
+ if (!token)
21
+ return false;
22
+ const bytes = Buffer.from(token);
23
+ return bytes.length === tokenBytes.length && timingSafeEqual(bytes, tokenBytes);
24
+ };
25
+ const healthResponse = deps.healthResponse ?? coreHealthResponse;
26
+ const json = (res, code, body) => res.writeHead(code, { "content-type": "application/json" }).end(JSON.stringify(body));
27
+ return async (req, res) => {
28
+ const url = new URL(req.url ?? "/", `${deps.tlsEnabled ? "https" : "http"}://localhost:${deps.port}`);
29
+ if (req.method === "GET" && url.pathname === "/health") {
30
+ const { code, body } = await healthResponse(deps.isDraining(), {
31
+ inFlight: deps.inFlight.count(),
32
+ ...deps.pluginHealth(),
33
+ // Where recent turns' time went: room ids and numbers only.
34
+ turns: deps.turns(),
35
+ });
36
+ json(res, code, body);
37
+ return;
38
+ }
39
+ if (req.method === "POST" && url.pathname === "/rocketchat/webhook") {
40
+ let payload;
41
+ try {
42
+ payload = JSON.parse(await readBody(req));
43
+ }
44
+ catch {
45
+ json(res, 400, { error: "bad json" });
46
+ return;
47
+ }
48
+ // Token check before anything else — a wrong/absent token never triggers a turn.
49
+ if (!validWebhookToken(payload.token)) {
50
+ json(res, 401, { error: "bad token" });
51
+ return;
52
+ }
53
+ // Draining: refuse honestly. RC treats a 200 as delivered and never
54
+ // resends, so an accepted-then-abandoned turn is a silently lost message.
55
+ if (deps.isDraining()) {
56
+ json(res, 503, { error: "draining" });
57
+ return;
58
+ }
59
+ // Ack fast so RC's webhook does not time out; the reply comes back via postMessage.
60
+ json(res, 200, { ok: true });
61
+ void deps.inFlight.track(deps.handleMessage(payload));
62
+ return;
63
+ }
64
+ res.writeHead(404, { "content-type": "text/plain" }).end("POST /rocketchat/webhook or GET /health\n");
65
+ };
66
+ }
@@ -0,0 +1,13 @@
1
+ export type { BridgePlugin, ControlContext, ControlVerbs, ParkedRun, RoutedTarget, ThreadedReply, Turn, TurnRecord, WebhookPayload, } from "./plugin.js";
2
+ export { composeHooks, type Hooks } from "./hooks.js";
3
+ export { createLog, envList, loadCoreConfig, type CoreConfig, type Log } from "./config.js";
4
+ export { createAgentClient, isTurnTimeout, type AgentClientOptions, type AgentTarget, type AgentTimings, type AgentTurn, type ParkVerdict, type RunRead, } from "./agent.js";
5
+ export { createAttachmentDeps, type AttachmentDepsOptions } from "./attachment-deps.js";
6
+ export { MAX_RESIZE_INPUT_BYTES, type AttachmentDeps, type AttachmentLimits, type ImageResizer, } from "./attachments.js";
7
+ export { createBotDenylist, type BotDenylistOptions } from "./denylist.js";
8
+ export { coreHealthResponse, createHttpHandler, type HttpHandlerDeps } from "./http.js";
9
+ export { createBridgeState, jsonStateFile, stateFilesFromEnv, type BridgeStateOptions, type JsonStateFile, type JsonStateFileOptions, type PauseState, } from "./state.js";
10
+ export { createTurnHandler, type TurnHandlerDeps } from "./turn.js";
11
+ export { createTurnTimings, type TurnTiming, type TurnTimings } from "./turn-timings.js";
12
+ export type { BotIdentity, ThreadRoot } from "./threading.js";
13
+ export { describeTools, errorText, summarizeResponse, usageFrom, type ResponseSummary, type TokenUsage, type ToolCall, } from "./response.js";
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ export { composeHooks } from "./hooks.js";
2
+ export { createLog, envList, loadCoreConfig } from "./config.js";
3
+ export { createAgentClient, isTurnTimeout, } from "./agent.js";
4
+ export { createAttachmentDeps } from "./attachment-deps.js";
5
+ export { MAX_RESIZE_INPUT_BYTES, } from "./attachments.js";
6
+ export { createBotDenylist } from "./denylist.js";
7
+ export { coreHealthResponse, createHttpHandler } from "./http.js";
8
+ export { createBridgeState, jsonStateFile, stateFilesFromEnv, } from "./state.js";
9
+ export { createTurnHandler } from "./turn.js";
10
+ export { createTurnTimings } from "./turn-timings.js";
11
+ export { describeTools, errorText, summarizeResponse, usageFrom, } from "./response.js";
@@ -0,0 +1,33 @@
1
+ import { type AttachmentDeps, type InlineImage, type RcMessage, type SkippedImage } from "./attachments.js";
2
+ import { type BotIdentity } from "./threading.js";
3
+ /** How many messages the one history call asks for; the window is the real bound. */
4
+ export declare const LOOKBACK_COUNT = 50;
5
+ export interface LookbackRequest {
6
+ roomId: string;
7
+ /** RC's room type (`c` public, `p` private); anything else has no lookback. */
8
+ roomType: string | undefined;
9
+ senderId: string | undefined;
10
+ senderName: string | undefined;
11
+ /** The addressed message itself, never its own lookback. */
12
+ messageId: string | undefined;
13
+ /** Scope: this thread's replies, or top-level messages when undefined. */
14
+ tmid: string | undefined;
15
+ windowMs: number;
16
+ budget: number;
17
+ now: number;
18
+ bot: BotIdentity;
19
+ }
20
+ /** The history endpoint for a room type, or undefined for rooms that have none here. */
21
+ export declare function historyEndpoint(roomType: string | undefined): string | undefined;
22
+ /** Which history messages are the sender's own untagged images, in scope and
23
+ * in the window, oldest first. RC lists newest first; the newest win the budget. */
24
+ export declare function recentImageMessages(messages: readonly RcMessage[], req: LookbackRequest): RcMessage[];
25
+ export interface RecentImages {
26
+ images: InlineImage[];
27
+ skipped: SkippedImage[];
28
+ }
29
+ /** ONE history call, then the chosen images downloaded as the room's identity.
30
+ * Never throws; `undefined` when there is no lookback for this room or it failed. */
31
+ export declare function fetchRecentImages(deps: AttachmentDeps, req: LookbackRequest): Promise<RecentImages | undefined>;
32
+ /** The one line that tells the agent these images were not on this message. */
33
+ export declare function lookbackNote(count: number, windowMs: number): string;