@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.
- package/LICENSE +21 -0
- package/README.md +157 -2
- package/dist/agent.d.ts +52 -0
- package/dist/agent.js +255 -0
- package/dist/attachment-deps.d.ts +15 -0
- package/dist/attachment-deps.js +13 -0
- package/dist/attachments.d.ts +255 -0
- package/dist/attachments.js +428 -0
- package/dist/config.d.ts +50 -0
- package/dist/config.js +92 -0
- package/dist/conversation-epochs.d.ts +41 -0
- package/dist/conversation-epochs.js +121 -0
- package/dist/denylist.d.ts +16 -0
- package/dist/denylist.js +86 -0
- package/dist/followups.d.ts +38 -0
- package/dist/followups.js +65 -0
- package/dist/hooks.d.ts +26 -0
- package/dist/hooks.js +88 -0
- package/dist/http.d.ts +33 -0
- package/dist/http.js +66 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +11 -0
- package/dist/lookback.d.ts +33 -0
- package/dist/lookback.js +85 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +104 -0
- package/dist/plugin.d.ts +113 -0
- package/dist/plugin.js +1 -0
- package/dist/reactions.d.ts +42 -0
- package/dist/reactions.js +127 -0
- package/dist/response.d.ts +52 -0
- package/dist/response.js +160 -0
- package/dist/run-events.d.ts +19 -0
- package/dist/run-events.js +65 -0
- package/dist/state.d.ts +57 -0
- package/dist/state.js +141 -0
- package/dist/stream.d.ts +67 -0
- package/dist/stream.js +126 -0
- package/dist/threading.d.ts +335 -0
- package/dist/threading.js +451 -0
- package/dist/turn-timings.d.ts +19 -0
- package/dist/turn-timings.js +14 -0
- package/dist/turn.d.ts +37 -0
- package/dist/turn.js +450 -0
- package/package.json +53 -3
package/dist/lookback.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// The sender's recent, untagged image uploads, for an addressed channel message
|
|
2
|
+
// that carries none: "@bot remind me about that" after posting an
|
|
3
|
+
// image without tagging. A DM needs none of this: every upload there got its own turn.
|
|
4
|
+
import { attachmentsOf, captionOf, isImageType, } from "./attachments.js";
|
|
5
|
+
import { botFaces, mentionsUs } from "./threading.js";
|
|
6
|
+
/** How many messages the one history call asks for; the window is the real bound. */
|
|
7
|
+
export const LOOKBACK_COUNT = 50;
|
|
8
|
+
/** The history endpoint for a room type, or undefined for rooms that have none here. */
|
|
9
|
+
export function historyEndpoint(roomType) {
|
|
10
|
+
return roomType === "c" ? "channels.history" : roomType === "p" ? "groups.history" : undefined;
|
|
11
|
+
}
|
|
12
|
+
/** Did this message already reach us? Then it was answered with its image. */
|
|
13
|
+
function addressedUs(m, bot) {
|
|
14
|
+
const faces = new Set(botFaces(bot));
|
|
15
|
+
const named = (m.mentions ?? []).some((x) => x._id === bot.userId || faces.has((x.username ?? "").toLowerCase()));
|
|
16
|
+
return named || mentionsUs(captionOf(m), bot);
|
|
17
|
+
}
|
|
18
|
+
/** Which history messages are the sender's own untagged images, in scope and
|
|
19
|
+
* in the window, oldest first. RC lists newest first; the newest win the budget. */
|
|
20
|
+
export function recentImageMessages(messages, req) {
|
|
21
|
+
const since = req.now - req.windowMs;
|
|
22
|
+
const picked = messages.filter((m) => {
|
|
23
|
+
const bySender = req.senderId && m.u?._id ? m.u._id === req.senderId : !!req.senderName && m.u?.username === req.senderName;
|
|
24
|
+
if (!bySender || (req.messageId && m._id === req.messageId))
|
|
25
|
+
return false;
|
|
26
|
+
if ((m.tmid ?? undefined) !== req.tmid)
|
|
27
|
+
return false;
|
|
28
|
+
const at = Date.parse(m.ts ?? "");
|
|
29
|
+
if (!Number.isNaN(at) && at < since)
|
|
30
|
+
return false;
|
|
31
|
+
if (addressedUs(m, req.bot))
|
|
32
|
+
return false;
|
|
33
|
+
return (m.attachments ?? []).some((a) => isImageType(a.image_type ?? m.file?.type));
|
|
34
|
+
});
|
|
35
|
+
return picked
|
|
36
|
+
.sort((a, b) => Date.parse(b.ts ?? "") - Date.parse(a.ts ?? ""))
|
|
37
|
+
.slice(0, req.budget)
|
|
38
|
+
.reverse();
|
|
39
|
+
}
|
|
40
|
+
/** ONE history call, then the chosen images downloaded as the room's identity.
|
|
41
|
+
* Never throws; `undefined` when there is no lookback for this room or it failed. */
|
|
42
|
+
export async function fetchRecentImages(deps, req) {
|
|
43
|
+
const endpoint = historyEndpoint(req.roomType);
|
|
44
|
+
if (!endpoint || req.budget <= 0 || req.windowMs <= 0)
|
|
45
|
+
return undefined;
|
|
46
|
+
const query = new URLSearchParams({
|
|
47
|
+
roomId: req.roomId,
|
|
48
|
+
oldest: new Date(req.now - req.windowMs).toISOString(),
|
|
49
|
+
count: String(LOOKBACK_COUNT),
|
|
50
|
+
});
|
|
51
|
+
// RC documents showThreadMessages on channels.history without stating its
|
|
52
|
+
// default, so a threaded lookback asks for replies explicitly rather than
|
|
53
|
+
// relying on it. groups.history does not document the param, so it is not sent.
|
|
54
|
+
if (req.tmid && endpoint === "channels.history")
|
|
55
|
+
query.set("showThreadMessages", "true");
|
|
56
|
+
let messages;
|
|
57
|
+
try {
|
|
58
|
+
const res = await deps.get(`${deps.rcUrl}/api/v1/${endpoint}?${query}`, deps.headers);
|
|
59
|
+
if (!res.ok) {
|
|
60
|
+
deps.log?.(`${endpoint} ${req.roomId} failed: ${res.status}`);
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
messages = (await res.json()).messages ?? [];
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
deps.log?.(`${endpoint} ${req.roomId} threw: ${err?.message ?? err}`);
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
const images = [];
|
|
70
|
+
const skipped = [];
|
|
71
|
+
for (const m of recentImageMessages(messages, req)) {
|
|
72
|
+
const budget = req.budget - images.length;
|
|
73
|
+
if (budget <= 0)
|
|
74
|
+
break;
|
|
75
|
+
const got = await attachmentsOf(deps, m, { budget, imagesOnly: true });
|
|
76
|
+
images.push(...got.images);
|
|
77
|
+
skipped.push(...got.skipped);
|
|
78
|
+
}
|
|
79
|
+
return { images, skipped };
|
|
80
|
+
}
|
|
81
|
+
/** The one line that tells the agent these images were not on this message. */
|
|
82
|
+
export function lookbackNote(count, windowMs) {
|
|
83
|
+
const what = count === 1 ? "The attached image is" : `The ${count} attached images are`;
|
|
84
|
+
return `(${what} from your recent messages here, posted in the last ${Math.round(windowMs / 60_000)} min without tagging me β not from this message.)`;
|
|
85
|
+
}
|
package/dist/main.d.ts
ADDED
package/dist/main.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The relay with NO plugins: what someone running only the connector starts
|
|
3
|
+
// (`rc-bridge`, or `tsx src/main.ts` from a checkout). Core env only
|
|
4
|
+
// (config.ts), plain HTTP, the state files under ~/rocketchat-bridge/.
|
|
5
|
+
// core.e2e.test.ts spawns this file to prove the core stands alone. A deployment
|
|
6
|
+
// with plugins composes these same pieces, with its own list in `plugins`.
|
|
7
|
+
import http from "node:http";
|
|
8
|
+
import { RocketChatClient } from "@practicalworks/rc-client";
|
|
9
|
+
import { createAgentClient } from "./agent.js";
|
|
10
|
+
import { createAttachmentDeps } from "./attachment-deps.js";
|
|
11
|
+
import { createLog, loadCoreConfig } from "./config.js";
|
|
12
|
+
import { createBotDenylist } from "./denylist.js";
|
|
13
|
+
import { composeHooks } from "./hooks.js";
|
|
14
|
+
import { createHttpHandler } from "./http.js";
|
|
15
|
+
import { createBridgeState, stateFilesFromEnv } from "./state.js";
|
|
16
|
+
import { createTurnHandler } from "./turn.js";
|
|
17
|
+
import { createTurnTimings } from "./turn-timings.js";
|
|
18
|
+
const log = createLog();
|
|
19
|
+
const config = loadCoreConfig(log);
|
|
20
|
+
const plugins = [];
|
|
21
|
+
const hooks = composeHooks(plugins, log);
|
|
22
|
+
const rc = new RocketChatClient({
|
|
23
|
+
baseUrl: config.rc.url,
|
|
24
|
+
userId: config.rc.userId,
|
|
25
|
+
authToken: config.rc.authToken,
|
|
26
|
+
timeoutMs: config.rc.timeoutMs,
|
|
27
|
+
// Passed explicitly: the client defaults it to off, the bridge to on.
|
|
28
|
+
threadShow: config.rc.threadShow,
|
|
29
|
+
maxMessageChars: config.rc.maxMessageChars,
|
|
30
|
+
postCap: { rate: new Map(), maxPosts: config.loop.maxPostsPerThread, windowMs: config.loop.windowMs },
|
|
31
|
+
log,
|
|
32
|
+
identityForRoom: (roomId) => hooks.identityForRoom(roomId),
|
|
33
|
+
isDirectMessageFallback: (roomId) => hooks.isDirectMessageFallback(roomId),
|
|
34
|
+
outbound: (text) => hooks.outbound(text),
|
|
35
|
+
});
|
|
36
|
+
const attachmentDepsFor = createAttachmentDeps({ rc, rcUrl: config.rc.url, limits: config.attachments, log });
|
|
37
|
+
const agent = createAgentClient({
|
|
38
|
+
timeoutMs: config.agent.timeoutMs,
|
|
39
|
+
parkCheckMs: config.agent.parkCheckMs,
|
|
40
|
+
streaming: config.agent.streaming,
|
|
41
|
+
log,
|
|
42
|
+
});
|
|
43
|
+
const state = createBridgeState({ ...stateFilesFromEnv(), log });
|
|
44
|
+
const denylist = createBotDenylist({ rc, rcUrl: config.rc.url, selfUserId: config.rc.userId, log });
|
|
45
|
+
const turnTimings = createTurnTimings();
|
|
46
|
+
// Turns run detached after the webhook's 200; shutdown waits for these.
|
|
47
|
+
let draining = false;
|
|
48
|
+
const running = new Set();
|
|
49
|
+
const inFlight = {
|
|
50
|
+
count: () => running.size,
|
|
51
|
+
track(work) {
|
|
52
|
+
running.add(work);
|
|
53
|
+
void work.catch(() => { }).finally(() => running.delete(work));
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
const turns = createTurnHandler({
|
|
57
|
+
config,
|
|
58
|
+
log,
|
|
59
|
+
rc,
|
|
60
|
+
attachmentDepsFor,
|
|
61
|
+
agent,
|
|
62
|
+
state,
|
|
63
|
+
turnTimings,
|
|
64
|
+
hooks,
|
|
65
|
+
bot: { userId: config.rc.userId, username: config.rc.botUsername },
|
|
66
|
+
denylist: { ids: denylist.ids, usernames: denylist.usernames },
|
|
67
|
+
defaultTarget: { url: config.agent.url, apiKey: config.agent.apiKey, model: config.agent.model },
|
|
68
|
+
track: (work) => inFlight.track(work),
|
|
69
|
+
isDraining: () => draining,
|
|
70
|
+
});
|
|
71
|
+
const server = http.createServer(createHttpHandler({
|
|
72
|
+
port: config.port,
|
|
73
|
+
tlsEnabled: false,
|
|
74
|
+
webhookToken: config.rc.webhookToken,
|
|
75
|
+
isDraining: () => draining,
|
|
76
|
+
inFlight,
|
|
77
|
+
handleMessage: turns.handleMessage,
|
|
78
|
+
pluginHealth: hooks.health,
|
|
79
|
+
turns: turnTimings.list,
|
|
80
|
+
}));
|
|
81
|
+
process.on("unhandledRejection", (reason) => log("unhandledRejection:", reason));
|
|
82
|
+
// Stop taking webhooks (RC gets a 503 and may resend), let running turns finish
|
|
83
|
+
// within the drain deadline, then exit.
|
|
84
|
+
function shutdown(signal) {
|
|
85
|
+
if (draining)
|
|
86
|
+
return;
|
|
87
|
+
draining = true;
|
|
88
|
+
log(`${signal} received β draining, ${running.size} turn(s) still running`);
|
|
89
|
+
setTimeout(() => {
|
|
90
|
+
log(`drain deadline hit β abandoning ${running.size} turn(s)`);
|
|
91
|
+
process.exit(0);
|
|
92
|
+
}, config.drainDeadlineMs).unref();
|
|
93
|
+
void (async () => {
|
|
94
|
+
while (running.size > 0)
|
|
95
|
+
await Promise.allSettled([...running]);
|
|
96
|
+
server.close(() => process.exit(0));
|
|
97
|
+
})();
|
|
98
|
+
}
|
|
99
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
100
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
101
|
+
server.listen(config.port, () => {
|
|
102
|
+
log(`core relay listening on http://:${config.port} β POST /rocketchat/webhook Β· agent β ${config.agent.url}`);
|
|
103
|
+
void denylist.refreshFromRc();
|
|
104
|
+
});
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { AgentTarget } from "./agent.js";
|
|
2
|
+
import type { ResponseSummary, ToolCall } from "./response.js";
|
|
3
|
+
import type { PostVoice } from "@practicalworks/rc-client";
|
|
4
|
+
import type { ThreadRoot } from "./threading.js";
|
|
5
|
+
/** What Rocket.Chat's outgoing webhook POSTs for one message. */
|
|
6
|
+
export interface WebhookPayload {
|
|
7
|
+
token?: string;
|
|
8
|
+
channel_id?: string;
|
|
9
|
+
channel_name?: string;
|
|
10
|
+
user_id?: string;
|
|
11
|
+
user_name?: string;
|
|
12
|
+
text?: string;
|
|
13
|
+
bot?: unknown;
|
|
14
|
+
/** The message's own id: used to re-read uploads, and as the thread root of a top-level message. */
|
|
15
|
+
message_id?: string;
|
|
16
|
+
/** The thread root, set when the message IS a threaded reply. */
|
|
17
|
+
tmid?: string;
|
|
18
|
+
}
|
|
19
|
+
/** A threaded reply, before the addressing gate: all interceptReply is shown. */
|
|
20
|
+
export interface ThreadedReply {
|
|
21
|
+
payload: WebhookPayload;
|
|
22
|
+
roomId: string;
|
|
23
|
+
/** The message text, after upload recovery. */
|
|
24
|
+
text: string;
|
|
25
|
+
/** The thread's root, or undefined when Rocket.Chat would not give it to us. */
|
|
26
|
+
root: ThreadRoot | undefined;
|
|
27
|
+
}
|
|
28
|
+
/** One engaged turn, as the hooks after the addressing gate see it. */
|
|
29
|
+
export interface Turn {
|
|
30
|
+
payload: WebhookPayload;
|
|
31
|
+
roomId: string;
|
|
32
|
+
/** Where everything about this message is posted. */
|
|
33
|
+
thread: string | undefined;
|
|
34
|
+
isDM: boolean;
|
|
35
|
+
conversation: string;
|
|
36
|
+
/** The prompt as the agent receives it, before framing. */
|
|
37
|
+
prompt: string;
|
|
38
|
+
}
|
|
39
|
+
/** A run that has parked on a human approval. */
|
|
40
|
+
export interface ParkedRun {
|
|
41
|
+
runId: string;
|
|
42
|
+
status: string;
|
|
43
|
+
command?: string;
|
|
44
|
+
choices?: readonly string[];
|
|
45
|
+
createdAt?: string;
|
|
46
|
+
lastEvent?: string;
|
|
47
|
+
}
|
|
48
|
+
/** Where a turn goes, and the profile name /health and the turn timings show. */
|
|
49
|
+
export interface RoutedTarget {
|
|
50
|
+
target: AgentTarget;
|
|
51
|
+
profile: string;
|
|
52
|
+
}
|
|
53
|
+
/** How a turn ended. `ignored` = the addressing gate declined it. */
|
|
54
|
+
export interface TurnRecord {
|
|
55
|
+
status: "ok" | "error" | "ignored";
|
|
56
|
+
roomId: string;
|
|
57
|
+
roomName?: string;
|
|
58
|
+
threadId?: string;
|
|
59
|
+
requester?: string;
|
|
60
|
+
conversation?: string;
|
|
61
|
+
promptChars: number;
|
|
62
|
+
images: number;
|
|
63
|
+
documents: number;
|
|
64
|
+
replyChars: number;
|
|
65
|
+
durationMs: number;
|
|
66
|
+
tools: ToolCall[];
|
|
67
|
+
error?: string;
|
|
68
|
+
/** ok only: when the turn began. */
|
|
69
|
+
startedAt?: number;
|
|
70
|
+
/** ok only: the response's id, model and token counts. */
|
|
71
|
+
usage?: Pick<ResponseSummary, "id" | "model" | "usage">;
|
|
72
|
+
/** ok only: the agent's reply text, reaction markers removed, before onAnswer ran. */
|
|
73
|
+
answer?: string;
|
|
74
|
+
}
|
|
75
|
+
/** Where a control command is answered. */
|
|
76
|
+
export interface ControlContext {
|
|
77
|
+
payload: WebhookPayload;
|
|
78
|
+
roomId: string;
|
|
79
|
+
thread: string | undefined;
|
|
80
|
+
}
|
|
81
|
+
export interface ControlVerbs {
|
|
82
|
+
/** A runner when the WHOLE message is one of this plugin's commands. */
|
|
83
|
+
match(text: string): ((ctx: ControlContext) => Promise<void>) | undefined;
|
|
84
|
+
/** The usage reply for a message that claims to be a command but is not one. */
|
|
85
|
+
nearMiss?(text: string): string | undefined;
|
|
86
|
+
}
|
|
87
|
+
export interface BridgePlugin {
|
|
88
|
+
name: string;
|
|
89
|
+
/** Auth headers to speak AS in this room; undefined = the bot's own. */
|
|
90
|
+
identityForRoom?(roomId: string): Promise<Record<string, string> | undefined>;
|
|
91
|
+
/** Asked when rooms.info refuses us: is this nonetheless a DM we answer? */
|
|
92
|
+
isDirectMessageFallback?(roomId: string): Promise<boolean | undefined>;
|
|
93
|
+
/** Is this message ours, in a voice the core does not know? */
|
|
94
|
+
isOwnVoice?(payload: WebhookPayload): boolean;
|
|
95
|
+
targetForRoom?(roomId: string): Promise<RoutedTarget | undefined>;
|
|
96
|
+
/** A preamble placed after the context header. */
|
|
97
|
+
framing?(turn: Turn): Promise<string | undefined>;
|
|
98
|
+
/** Rewrites a reply before it is split: strips markers, picks a voice (alias and avatar). */
|
|
99
|
+
outbound?(text: string): {
|
|
100
|
+
text: string;
|
|
101
|
+
voice?: PostVoice;
|
|
102
|
+
};
|
|
103
|
+
/** True when the reply was consumed and must not become a turn. */
|
|
104
|
+
interceptReply?(reply: ThreadedReply): Promise<boolean>;
|
|
105
|
+
onRunParked?(turn: Turn, run: ParkedRun): Promise<void>;
|
|
106
|
+
/** Rewrites the answer before its single post. */
|
|
107
|
+
onAnswer?(turn: Turn, text: string): Promise<string>;
|
|
108
|
+
/** Never awaited: a slow sink must not hold the turn. */
|
|
109
|
+
onTurnSettled?(record: TurnRecord): void | Promise<void>;
|
|
110
|
+
controlVerbs?: ControlVerbs;
|
|
111
|
+
/** Fields merged into /health next to the core's. */
|
|
112
|
+
health?(): Record<string, unknown>;
|
|
113
|
+
}
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** The shortcode name for an emoji the agent wrote, or `undefined` when we do not
|
|
2
|
+
* know it. Accepts the character itself, `:name:`, or a bare `name` β whichever
|
|
3
|
+
* form the model reaches for β but only names on the map, for the same reason
|
|
4
|
+
* the map exists. */
|
|
5
|
+
export declare function shortcodeFor(raw: string): string | undefined;
|
|
6
|
+
export interface ReplyReactions {
|
|
7
|
+
/** The reply with every marker removed β what the room should read. */
|
|
8
|
+
text: string;
|
|
9
|
+
/** Shortcode names to react with, deduplicated, in the order written. */
|
|
10
|
+
emoji: string[];
|
|
11
|
+
/** What was inside a marker but is not on the map β logged, never sent. */
|
|
12
|
+
unknown: string[];
|
|
13
|
+
}
|
|
14
|
+
/** Split the agent's reply into what it SAID and what it REACTED with. */
|
|
15
|
+
export declare function extractReactions(reply: string): ReplyReactions;
|
|
16
|
+
/** The receipt a turn leaves on the message that started it. */
|
|
17
|
+
export declare const RECEIPT: {
|
|
18
|
+
readonly seen: "eyes";
|
|
19
|
+
readonly done: "white_check_mark";
|
|
20
|
+
readonly failed: "warning";
|
|
21
|
+
/** A turn that ran past the bridge's wait: the agent is still working server-side,
|
|
22
|
+
* so it has neither finished nor failed. */
|
|
23
|
+
readonly waiting: "hourglass_flowing_sand";
|
|
24
|
+
};
|
|
25
|
+
export type ReceiptState = keyof typeof RECEIPT;
|
|
26
|
+
/** The calls that move a message's receipt from one state to the next: take the
|
|
27
|
+
* old reaction off, put the new one on. `to` undefined only takes the old one
|
|
28
|
+
* off β a turn that ended without answering, or one the agent answered with its
|
|
29
|
+
* own reaction, where a β
beside it would be noise. `chat.react` with
|
|
30
|
+
* `shouldReact` is a setter, so replaying either half is harmless. */
|
|
31
|
+
export declare function receiptTransition(from: ReceiptState | undefined, to: ReceiptState | undefined): Array<{
|
|
32
|
+
emoji: string;
|
|
33
|
+
shouldReact: boolean;
|
|
34
|
+
}>;
|
|
35
|
+
/** How the agent learns it can react, sent with every turn.
|
|
36
|
+
*
|
|
37
|
+
* In the framing, not an agent-side skill: a skill an agent loads only when a
|
|
38
|
+
* request matches it is never loaded for "a reply that is just an
|
|
39
|
+
* acknowledgement", because that matches no request.
|
|
40
|
+
* The framing reaches every profile the bridge fronts, on every turn, whatever
|
|
41
|
+
* model is behind it. One line, because it rides on every turn. */
|
|
42
|
+
export declare const REACTION_HINT = "(Rocket.Chat: to react to the user's message with an emoji, include [react: \uD83D\uDC4D] in your reply \u2014 it is applied as a reaction and removed from the text. A reply that is only a marker posts no message. Use it for acknowledgements that need no words.)";
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// Reactions: the bridge's receipt on a message it picked up, and
|
|
2
|
+
// the agent's way of answering with an emoji instead of a sentence.
|
|
3
|
+
//
|
|
4
|
+
// Both exist because of how Rocket.Chat NOTIFIES. It notifies when a message is
|
|
5
|
+
// CREATED, never when one is edited. A reply created early (a "Thinkingβ¦"
|
|
6
|
+
// holding line, or the first streamed fragment) and grown with chat.update
|
|
7
|
+
// notifies with the placeholder, and the real answer arrives in silence.
|
|
8
|
+
//
|
|
9
|
+
// So the reply is posted ONCE, when it is finished, and "I heard you" moves
|
|
10
|
+
// to a reaction, which notifies nobody: π the moment a message is picked up, β
|
|
11
|
+
// when the answer lands, β οΈ when the turn fails.
|
|
12
|
+
//
|
|
13
|
+
// Kept apart from main.ts so it can be tested without booting the bridge.
|
|
14
|
+
/** `chat.react` wants a shortcode NAME that exists on the server β a raw Unicode
|
|
15
|
+
* character is refused ("the emoji must exist"). So the emoji the agent may react
|
|
16
|
+
* with are an explicit map, not a guess at RC's emoji index: an unknown one is
|
|
17
|
+
* reported and skipped rather than 400ing in the dark. */
|
|
18
|
+
const SHORTCODES = {
|
|
19
|
+
"π": "eyes",
|
|
20
|
+
"β
": "white_check_mark",
|
|
21
|
+
"β οΈ": "warning",
|
|
22
|
+
"β ": "warning",
|
|
23
|
+
"β³": "hourglass_flowing_sand",
|
|
24
|
+
"π": "thumbsup",
|
|
25
|
+
"π": "thumbsdown",
|
|
26
|
+
"π": "tada",
|
|
27
|
+
"β€οΈ": "heart",
|
|
28
|
+
"β€": "heart",
|
|
29
|
+
"π": "joy",
|
|
30
|
+
"π": "smile",
|
|
31
|
+
"π": "slight_smile",
|
|
32
|
+
"π": "blush",
|
|
33
|
+
"π": "pray",
|
|
34
|
+
"π₯": "fire",
|
|
35
|
+
"π": "clap",
|
|
36
|
+
"π―": "100",
|
|
37
|
+
"π€": "thinking",
|
|
38
|
+
"π’": "cry",
|
|
39
|
+
"π": "raised_hands",
|
|
40
|
+
"π": "ok_hand",
|
|
41
|
+
"β¨": "sparkles",
|
|
42
|
+
"π": "rocket",
|
|
43
|
+
"πͺ": "muscle",
|
|
44
|
+
"π
": "sweat_smile",
|
|
45
|
+
"π€": "handshake",
|
|
46
|
+
"π": "pushpin",
|
|
47
|
+
"π
": "date",
|
|
48
|
+
"π ": "house",
|
|
49
|
+
};
|
|
50
|
+
const KNOWN_NAMES = new Set(Object.values(SHORTCODES));
|
|
51
|
+
/** The shortcode name for an emoji the agent wrote, or `undefined` when we do not
|
|
52
|
+
* know it. Accepts the character itself, `:name:`, or a bare `name` β whichever
|
|
53
|
+
* form the model reaches for β but only names on the map, for the same reason
|
|
54
|
+
* the map exists. */
|
|
55
|
+
export function shortcodeFor(raw) {
|
|
56
|
+
const trimmed = raw.trim();
|
|
57
|
+
const mapped = SHORTCODES[trimmed] ?? SHORTCODES[trimmed.replace(/οΈ/g, "")];
|
|
58
|
+
if (mapped)
|
|
59
|
+
return mapped;
|
|
60
|
+
const name = trimmed.replace(/^:|:$/g, "");
|
|
61
|
+
return KNOWN_NAMES.has(name) ? name : undefined;
|
|
62
|
+
}
|
|
63
|
+
// `[react: π]`, `[react: π π]`, `[react: :tada:]`. Case-insensitive, and
|
|
64
|
+
// anywhere in the reply, because a model does not reliably put a marker first.
|
|
65
|
+
const REACT_MARKER = /\[react:\s*([^\]]*)\]/gi;
|
|
66
|
+
/** Split the agent's reply into what it SAID and what it REACTED with. */
|
|
67
|
+
export function extractReactions(reply) {
|
|
68
|
+
const emoji = [];
|
|
69
|
+
const unknown = [];
|
|
70
|
+
const text = reply
|
|
71
|
+
.replace(REACT_MARKER, (_m, inner) => {
|
|
72
|
+
for (const token of splitEmoji(inner)) {
|
|
73
|
+
const name = shortcodeFor(token);
|
|
74
|
+
if (name) {
|
|
75
|
+
if (!emoji.includes(name))
|
|
76
|
+
emoji.push(name);
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
unknown.push(token);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return "";
|
|
83
|
+
})
|
|
84
|
+
.replace(/[ \t]+\n/g, "\n")
|
|
85
|
+
.trim();
|
|
86
|
+
return { text, emoji, unknown };
|
|
87
|
+
}
|
|
88
|
+
/** Tokens inside a marker. Separated by spaces or commas when the model does
|
|
89
|
+
* that; otherwise by grapheme, so `[react: ππ]` is two reactions, not one
|
|
90
|
+
* unknown string. */
|
|
91
|
+
function splitEmoji(inner) {
|
|
92
|
+
const parts = inner.split(/[\s,]+/).filter(Boolean);
|
|
93
|
+
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
94
|
+
return parts.flatMap((part) => part.startsWith(":") || /^[a-z0-9_+-]+$/i.test(part)
|
|
95
|
+
? [part]
|
|
96
|
+
: [...segmenter.segment(part)].map((s) => s.segment));
|
|
97
|
+
}
|
|
98
|
+
/** The receipt a turn leaves on the message that started it. */
|
|
99
|
+
export const RECEIPT = {
|
|
100
|
+
seen: "eyes",
|
|
101
|
+
done: "white_check_mark",
|
|
102
|
+
failed: "warning",
|
|
103
|
+
/** A turn that ran past the bridge's wait: the agent is still working server-side,
|
|
104
|
+
* so it has neither finished nor failed. */
|
|
105
|
+
waiting: "hourglass_flowing_sand",
|
|
106
|
+
};
|
|
107
|
+
/** The calls that move a message's receipt from one state to the next: take the
|
|
108
|
+
* old reaction off, put the new one on. `to` undefined only takes the old one
|
|
109
|
+
* off β a turn that ended without answering, or one the agent answered with its
|
|
110
|
+
* own reaction, where a β
beside it would be noise. `chat.react` with
|
|
111
|
+
* `shouldReact` is a setter, so replaying either half is harmless. */
|
|
112
|
+
export function receiptTransition(from, to) {
|
|
113
|
+
if (from === to)
|
|
114
|
+
return [];
|
|
115
|
+
return [
|
|
116
|
+
...(from ? [{ emoji: RECEIPT[from], shouldReact: false }] : []),
|
|
117
|
+
...(to ? [{ emoji: RECEIPT[to], shouldReact: true }] : []),
|
|
118
|
+
];
|
|
119
|
+
}
|
|
120
|
+
/** How the agent learns it can react, sent with every turn.
|
|
121
|
+
*
|
|
122
|
+
* In the framing, not an agent-side skill: a skill an agent loads only when a
|
|
123
|
+
* request matches it is never loaded for "a reply that is just an
|
|
124
|
+
* acknowledgement", because that matches no request.
|
|
125
|
+
* The framing reaches every profile the bridge fronts, on every turn, whatever
|
|
126
|
+
* model is behind it. One line, because it rides on every turn. */
|
|
127
|
+
export const REACTION_HINT = "(Rocket.Chat: to react to the user's message with an emoji, include [react: π] in your reply β it is applied as a reaction and removed from the text. A reply that is only a marker posts no message. Use it for acknowledgements that need no words.)";
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** Token counts off a response's `usage`, for a usage ledger. */
|
|
2
|
+
export interface TokenUsage {
|
|
3
|
+
tokensIn: number | null;
|
|
4
|
+
tokensOut: number | null;
|
|
5
|
+
tokensCached: number | null;
|
|
6
|
+
}
|
|
7
|
+
/** Token counts in either wire shape the gateway sends (Responses or Chat
|
|
8
|
+
* Completions), bare or under `usage`; null when neither count is there. */
|
|
9
|
+
export declare function usageFrom(body: unknown): TokenUsage | null;
|
|
10
|
+
/** One tool the agent called, paired with its result when we can match one. */
|
|
11
|
+
export interface ToolCall {
|
|
12
|
+
name: string;
|
|
13
|
+
/** A short, truncated look at the arguments β enough to tell
|
|
14
|
+
* `search_notes(query:"invoices")` from a different search, without
|
|
15
|
+
* copying whole file contents into the trace. */
|
|
16
|
+
args?: string;
|
|
17
|
+
/** Size of a successful tool result. Successful output remains a count so
|
|
18
|
+
* traces do not become a second copy of every message. */
|
|
19
|
+
outputChars?: number;
|
|
20
|
+
/** A failed tool result's text, RAW: whoever persists it redacts and bounds it
|
|
21
|
+
* (a tracing plugin does, before the row is written). */
|
|
22
|
+
error?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface ResponseSummary {
|
|
25
|
+
text: string;
|
|
26
|
+
tools: ToolCall[];
|
|
27
|
+
/** The response's own id, the ledger's idempotency key for this turn. */
|
|
28
|
+
id?: string;
|
|
29
|
+
/** The model the gateway reports having served the turn. */
|
|
30
|
+
model?: string;
|
|
31
|
+
/** Token counts off the response's `usage`, when the gateway stamped one. */
|
|
32
|
+
usage?: TokenUsage;
|
|
33
|
+
/** Item types we didn't recognise. Logged rather than ignored, so a gateway
|
|
34
|
+
* upgrade that adds a type shows up as a line in the log instead of silently
|
|
35
|
+
* vanishing the way the tool calls did. */
|
|
36
|
+
unknownTypes: string[];
|
|
37
|
+
}
|
|
38
|
+
/** Collapse a tool's arguments to a compact preview. `arguments` arrives as a
|
|
39
|
+
* JSON *string*; when it parses we re-render it compactly (dropping whitespace
|
|
40
|
+
* the model emitted), and when it doesn't we keep the raw string rather than
|
|
41
|
+
* losing it. */
|
|
42
|
+
export declare function previewArgs(raw: unknown, max?: number): string | undefined;
|
|
43
|
+
/** A failed tool result as text: a string as-is, anything else as JSON. */
|
|
44
|
+
export declare function errorText(output: unknown): string | undefined;
|
|
45
|
+
export declare function outputLength(output: unknown): number | undefined;
|
|
46
|
+
/** Split a /v1/responses body into the reply text and the trace of what it took
|
|
47
|
+
* to produce it. Never throws β a malformed body yields empty text, which the
|
|
48
|
+
* caller already handles as "(no reply)". */
|
|
49
|
+
export declare function summarizeResponse(body: unknown): ResponseSummary;
|
|
50
|
+
/** One log line naming what the turn actually did β `search_notesΓ3`
|
|
51
|
+
* style, with result sizes, so a search that found nothing is visible as such. */
|
|
52
|
+
export declare function describeTools(tools: ToolCall[]): string;
|